title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Convert a Set to Stream in Java | 11 Dec, 2018
Set interface extends Collection interface and Collection has stream() method that returns a sequential stream of the collection.
Below given are some examples to understand the implementation in a better way.
Example 1 : Converting Integer HashSet to Stream of Integers.
// Java code for converting // Set to Streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Integer HashSet Set<Integer> set = new HashSet<>(); // adding elements in set set.add(2); set.add(4); set.add(6); set.add(8); set.add(10); set.add(12); // converting Set to Stream Stream<Integer> stream = set.stream(); // displaying elements of Stream using lambda expression stream.forEach(elem->System.out.print(elem+" ")); }}
Example 2 : Converting HashSet of String to stream.
// Java code for converting // Set to Streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an String HashSet Set<String> set = new HashSet<>(); // adding elements in set set.add("Geeks"); set.add("for"); set.add("GeeksQuiz"); set.add("GeeksforGeeks"); // converting Set to Stream Stream<String> stream = set.stream(); // displaying elements of Stream stream.forEach(elem -> System.out.print(elem+" ")); }}
Note : Objects that you insert in HashSet are not guaranteed to be inserted in same order. Objects are inserted based on their hash code.
Convert Stream to Set in Java
Java - util package
Java-Collections
java-hashset
java-set
Java-Set-Programs
java-stream
Java-Stream-programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "Set interface extends Collection interface and Collection has stream() method that returns a sequential stream of the collection."
},
{
"code": null,
"e": 238,
"s": 158,
"text": "Below given are some examples to understand the implementation in a better way."
},
{
"code": null,
"e": 300,
"s": 238,
"text": "Example 1 : Converting Integer HashSet to Stream of Integers."
},
{
"code": "// Java code for converting // Set to Streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an Integer HashSet Set<Integer> set = new HashSet<>(); // adding elements in set set.add(2); set.add(4); set.add(6); set.add(8); set.add(10); set.add(12); // converting Set to Stream Stream<Integer> stream = set.stream(); // displaying elements of Stream using lambda expression stream.forEach(elem->System.out.print(elem+\" \")); }}",
"e": 892,
"s": 300,
"text": null
},
{
"code": null,
"e": 944,
"s": 892,
"text": "Example 2 : Converting HashSet of String to stream."
},
{
"code": "// Java code for converting // Set to Streamimport java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating an String HashSet Set<String> set = new HashSet<>(); // adding elements in set set.add(\"Geeks\"); set.add(\"for\"); set.add(\"GeeksQuiz\"); set.add(\"GeeksforGeeks\"); // converting Set to Stream Stream<String> stream = set.stream(); // displaying elements of Stream stream.forEach(elem -> System.out.print(elem+\" \")); }}",
"e": 1513,
"s": 944,
"text": null
},
{
"code": null,
"e": 1651,
"s": 1513,
"text": "Note : Objects that you insert in HashSet are not guaranteed to be inserted in same order. Objects are inserted based on their hash code."
},
{
"code": null,
"e": 1681,
"s": 1651,
"text": "Convert Stream to Set in Java"
},
{
"code": null,
"e": 1701,
"s": 1681,
"text": "Java - util package"
},
{
"code": null,
"e": 1718,
"s": 1701,
"text": "Java-Collections"
},
{
"code": null,
"e": 1731,
"s": 1718,
"text": "java-hashset"
},
{
"code": null,
"e": 1740,
"s": 1731,
"text": "java-set"
},
{
"code": null,
"e": 1758,
"s": 1740,
"text": "Java-Set-Programs"
},
{
"code": null,
"e": 1770,
"s": 1758,
"text": "java-stream"
},
{
"code": null,
"e": 1791,
"s": 1770,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 1796,
"s": 1791,
"text": "Java"
},
{
"code": null,
"e": 1801,
"s": 1796,
"text": "Java"
},
{
"code": null,
"e": 1818,
"s": 1801,
"text": "Java-Collections"
}
]
|
Node.js querystring.stringify() Method | 08 Oct, 2021
The querystring.stringify() method is used to produce an URL query string from the given object that contains the key-value pairs. The method iterates through the object’s own properties to generate the query string.
It can serialize a single or an array of strings, numbers, and booleans. Any other types of values are coerced to empty strings.
During serializing, the UTF-8 encoding format is used to encode any character that requires percent-encoding. To encode using an alternative character encoding, the encodeURIComponent option has to be specified.
Syntax:
querystring.stringify( obj[, sep[, eq[, options]]] )
Parameters: This function accepts four parameters as mentioned above and described below:
obj: It is an Object that has to be serialized into the URL query string.
sep: It is a String that specifies the substring used to delimit the key and value pairs in the query string. The default value is “&”.
eq: It is a String that specifies the substring used to delimit keys and values in the query string. The default value is “=”.
options: It is an Object which can be used to modify the behaviour of the method. It has the following parameters:encodeURIComponent: It is a function that would be used to convert URL-unsafe characters to percent-encoding in the query string. The default value is querystring.escape().
encodeURIComponent: It is a function that would be used to convert URL-unsafe characters to percent-encoding in the query string. The default value is querystring.escape().
Return Value: It returns a String that contains the URL query produced from the given object.
Below programs illustrate the querystring.stringify() method in Node.js:
Example 1:
// Import the querystring moduleconst querystring = require("querystring"); // Specify the URL object// to be serializedlet urlObject = { user: "sam", access: true, role: ["admin", "editor", "manager"],}; // Use the stringify() method on the objectlet parsedQuery = querystring.stringify(urlObject); console.log("Parsed Query:", parsedQuery);
Output:
Parsed Query: user=sam&access=true&role=admin&role=editor&role=manager
Example 2:
// Import the querystring moduleconst querystring = require("querystring"); // Specify the URL object// to be serializedlet urlObject = { user: "max", access: false, role: ["editor", "manager"],}; // Use the stringify() method on the object// with sep as `, ` and eq as `:`let parsedQuery = querystring.stringify(urlObject, ", ", ":"); console.log("Parsed Query 1:", parsedQuery); // Use the stringify() method on the object// with sep as `&&&` and eq as `==`parsedQuery = querystring.stringify(urlObject, "&&&", "=="); console.log("\nParsed Query 2:", parsedQuery);
Output:
Parsed Query 1: user:max, access:false, role:editor, role:manager
Parsed Query 2: user==max&&&access==false&&&role==editor&&&role==manager
Reference: https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options
Node.js- querystring-Module
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 ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The querystring.stringify() method is used to produce an URL query string from the given object that contains the key-value pairs. The method iterates through the object’s own properties to generate the query string."
},
{
"code": null,
"e": 374,
"s": 245,
"text": "It can serialize a single or an array of strings, numbers, and booleans. Any other types of values are coerced to empty strings."
},
{
"code": null,
"e": 586,
"s": 374,
"text": "During serializing, the UTF-8 encoding format is used to encode any character that requires percent-encoding. To encode using an alternative character encoding, the encodeURIComponent option has to be specified."
},
{
"code": null,
"e": 594,
"s": 586,
"text": "Syntax:"
},
{
"code": null,
"e": 647,
"s": 594,
"text": "querystring.stringify( obj[, sep[, eq[, options]]] )"
},
{
"code": null,
"e": 737,
"s": 647,
"text": "Parameters: This function accepts four parameters as mentioned above and described below:"
},
{
"code": null,
"e": 811,
"s": 737,
"text": "obj: It is an Object that has to be serialized into the URL query string."
},
{
"code": null,
"e": 947,
"s": 811,
"text": "sep: It is a String that specifies the substring used to delimit the key and value pairs in the query string. The default value is “&”."
},
{
"code": null,
"e": 1074,
"s": 947,
"text": "eq: It is a String that specifies the substring used to delimit keys and values in the query string. The default value is “=”."
},
{
"code": null,
"e": 1361,
"s": 1074,
"text": "options: It is an Object which can be used to modify the behaviour of the method. It has the following parameters:encodeURIComponent: It is a function that would be used to convert URL-unsafe characters to percent-encoding in the query string. The default value is querystring.escape()."
},
{
"code": null,
"e": 1534,
"s": 1361,
"text": "encodeURIComponent: It is a function that would be used to convert URL-unsafe characters to percent-encoding in the query string. The default value is querystring.escape()."
},
{
"code": null,
"e": 1628,
"s": 1534,
"text": "Return Value: It returns a String that contains the URL query produced from the given object."
},
{
"code": null,
"e": 1701,
"s": 1628,
"text": "Below programs illustrate the querystring.stringify() method in Node.js:"
},
{
"code": null,
"e": 1712,
"s": 1701,
"text": "Example 1:"
},
{
"code": "// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL object// to be serializedlet urlObject = { user: \"sam\", access: true, role: [\"admin\", \"editor\", \"manager\"],}; // Use the stringify() method on the objectlet parsedQuery = querystring.stringify(urlObject); console.log(\"Parsed Query:\", parsedQuery);",
"e": 2067,
"s": 1712,
"text": null
},
{
"code": null,
"e": 2075,
"s": 2067,
"text": "Output:"
},
{
"code": null,
"e": 2146,
"s": 2075,
"text": "Parsed Query: user=sam&access=true&role=admin&role=editor&role=manager"
},
{
"code": null,
"e": 2157,
"s": 2146,
"text": "Example 2:"
},
{
"code": "// Import the querystring moduleconst querystring = require(\"querystring\"); // Specify the URL object// to be serializedlet urlObject = { user: \"max\", access: false, role: [\"editor\", \"manager\"],}; // Use the stringify() method on the object// with sep as `, ` and eq as `:`let parsedQuery = querystring.stringify(urlObject, \", \", \":\"); console.log(\"Parsed Query 1:\", parsedQuery); // Use the stringify() method on the object// with sep as `&&&` and eq as `==`parsedQuery = querystring.stringify(urlObject, \"&&&\", \"==\"); console.log(\"\\nParsed Query 2:\", parsedQuery);",
"e": 2738,
"s": 2157,
"text": null
},
{
"code": null,
"e": 2746,
"s": 2738,
"text": "Output:"
},
{
"code": null,
"e": 2886,
"s": 2746,
"text": "Parsed Query 1: user:max, access:false, role:editor, role:manager\n\nParsed Query 2: user==max&&&access==false&&&role==editor&&&role==manager"
},
{
"code": null,
"e": 2990,
"s": 2886,
"text": "Reference: https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options"
},
{
"code": null,
"e": 3018,
"s": 2990,
"text": "Node.js- querystring-Module"
},
{
"code": null,
"e": 3026,
"s": 3018,
"text": "Node.js"
},
{
"code": null,
"e": 3043,
"s": 3026,
"text": "Web Technologies"
},
{
"code": null,
"e": 3141,
"s": 3043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3189,
"s": 3141,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3222,
"s": 3189,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3252,
"s": 3222,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 3272,
"s": 3252,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 3326,
"s": 3272,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 3388,
"s": 3326,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3449,
"s": 3388,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3499,
"s": 3449,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3542,
"s": 3499,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
LR Parser | 31 Mar, 2021
In this article, we will discuss LR parser, and it’s overview and then will discuss the algorithm. Also, we will discuss the parsing table and LR parser working diagram. Let’s discuss it one by one.
LR parser :LR parser is a bottom-up parser for context-free grammar that is very generally used by computer programming language compiler and other associated tools. LR parser reads their input from left to right and produces a right-most derivation. It is called a Bottom-up parser because it attempts to reduce the top-level grammar productions by building up from the leaves. LR parsers are the most powerful parser of all deterministic parsers in practice.
Description of LR parser :The term parser LR(k) parser, here the L refers to the left-to-right scanning, R refers to the rightmost derivation in reverse and k refers to the number of unconsumed “look ahead” input symbols that are used in making parser decisions. Typically, k is 1 and is often omitted. A context-free grammar is called LR (k) if the LR (k) parser exists for it. This first reduces the sequence of tokens to the left. But when we read from above, the derivation order first extends to non-terminal.
The stack is empty, and we are looking to reduce the rule by S’→S$.Using a “.” in the rule represents how many of the rules are already on the stack.A dotted item, or simply, the item is a production rule with a dot indicating how much RHS has so far been recognized. Closing an item is used to see what production rules can be used to expand the current structure. It is calculated as follows:
The stack is empty, and we are looking to reduce the rule by S’→S$.
Using a “.” in the rule represents how many of the rules are already on the stack.
A dotted item, or simply, the item is a production rule with a dot indicating how much RHS has so far been recognized. Closing an item is used to see what production rules can be used to expand the current structure. It is calculated as follows:
Rules for LR parser :The rules of LR parser as follows.
The first item from the given grammar rules adds itself as the first closed set.If an object is present in the closure of the form A→ α. β. γ, where the next symbol after the symbol is non-terminal, add the symbol’s production rules where the dot precedes the first item.Repeat steps (B) and (C) for new items added under (B).
The first item from the given grammar rules adds itself as the first closed set.
If an object is present in the closure of the form A→ α. β. γ, where the next symbol after the symbol is non-terminal, add the symbol’s production rules where the dot precedes the first item.
Repeat steps (B) and (C) for new items added under (B).
LR parser algorithm :LR Parsing algorithm is the same for all the parser, but the parsing table is different for each parser. It consists following components as follows.
Input Buffer – It contains the given string, and it ends with a $ symbol. Stack – The combination of state symbol and current input symbol is used to refer to the parsing table in order to take the parsing decisions.
Input Buffer – It contains the given string, and it ends with a $ symbol.
Stack – The combination of state symbol and current input symbol is used to refer to the parsing table in order to take the parsing decisions.
Parsing Table : Parsing table is divided into two parts- Action table and Go-To table. The action table gives a grammar rule to implement the given current state and current terminal in the input stream. There are four cases used in action table as follows.
Shift Action- In shift action the present terminal is removed from the input stream and the state n is pushed onto the stack, and it becomes the new present state.Reduce Action- The number m is written to the output stream.The symbol m mentioned in the left-hand side of rule m says that state is removed from the stack.The symbol m mentioned in the left-hand side of rule m says that a new state is looked up in the goto table and made the new current state by pushing it onto the stack.
Shift Action- In shift action the present terminal is removed from the input stream and the state n is pushed onto the stack, and it becomes the new present state.
Reduce Action- The number m is written to the output stream.
The symbol m mentioned in the left-hand side of rule m says that state is removed from the stack.
The symbol m mentioned in the left-hand side of rule m says that a new state is looked up in the goto table and made the new current state by pushing it onto the stack.
An accept - the string is accepted
No action - a syntax error is reported
Note –The go-to table indicates which state should proceed.
LR parser diagram :
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Checking in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
S - attributed and L - attributed SDTs in Syntax directed translation
Data flow analysis in Compiler
Runtime Environments in Compiler Design
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 251,
"s": 52,
"text": "In this article, we will discuss LR parser, and it’s overview and then will discuss the algorithm. Also, we will discuss the parsing table and LR parser working diagram. Let’s discuss it one by one."
},
{
"code": null,
"e": 712,
"s": 251,
"text": "LR parser :LR parser is a bottom-up parser for context-free grammar that is very generally used by computer programming language compiler and other associated tools. LR parser reads their input from left to right and produces a right-most derivation. It is called a Bottom-up parser because it attempts to reduce the top-level grammar productions by building up from the leaves. LR parsers are the most powerful parser of all deterministic parsers in practice."
},
{
"code": null,
"e": 1227,
"s": 712,
"text": "Description of LR parser :The term parser LR(k) parser, here the L refers to the left-to-right scanning, R refers to the rightmost derivation in reverse and k refers to the number of unconsumed “look ahead” input symbols that are used in making parser decisions. Typically, k is 1 and is often omitted. A context-free grammar is called LR (k) if the LR (k) parser exists for it. This first reduces the sequence of tokens to the left. But when we read from above, the derivation order first extends to non-terminal."
},
{
"code": null,
"e": 1622,
"s": 1227,
"text": "The stack is empty, and we are looking to reduce the rule by S’→S$.Using a “.” in the rule represents how many of the rules are already on the stack.A dotted item, or simply, the item is a production rule with a dot indicating how much RHS has so far been recognized. Closing an item is used to see what production rules can be used to expand the current structure. It is calculated as follows:"
},
{
"code": null,
"e": 1690,
"s": 1622,
"text": "The stack is empty, and we are looking to reduce the rule by S’→S$."
},
{
"code": null,
"e": 1773,
"s": 1690,
"text": "Using a “.” in the rule represents how many of the rules are already on the stack."
},
{
"code": null,
"e": 2019,
"s": 1773,
"text": "A dotted item, or simply, the item is a production rule with a dot indicating how much RHS has so far been recognized. Closing an item is used to see what production rules can be used to expand the current structure. It is calculated as follows:"
},
{
"code": null,
"e": 2075,
"s": 2019,
"text": "Rules for LR parser :The rules of LR parser as follows."
},
{
"code": null,
"e": 2402,
"s": 2075,
"text": "The first item from the given grammar rules adds itself as the first closed set.If an object is present in the closure of the form A→ α. β. γ, where the next symbol after the symbol is non-terminal, add the symbol’s production rules where the dot precedes the first item.Repeat steps (B) and (C) for new items added under (B)."
},
{
"code": null,
"e": 2483,
"s": 2402,
"text": "The first item from the given grammar rules adds itself as the first closed set."
},
{
"code": null,
"e": 2675,
"s": 2483,
"text": "If an object is present in the closure of the form A→ α. β. γ, where the next symbol after the symbol is non-terminal, add the symbol’s production rules where the dot precedes the first item."
},
{
"code": null,
"e": 2731,
"s": 2675,
"text": "Repeat steps (B) and (C) for new items added under (B)."
},
{
"code": null,
"e": 2902,
"s": 2731,
"text": "LR parser algorithm :LR Parsing algorithm is the same for all the parser, but the parsing table is different for each parser. It consists following components as follows."
},
{
"code": null,
"e": 3119,
"s": 2902,
"text": "Input Buffer – It contains the given string, and it ends with a $ symbol. Stack – The combination of state symbol and current input symbol is used to refer to the parsing table in order to take the parsing decisions."
},
{
"code": null,
"e": 3194,
"s": 3119,
"text": "Input Buffer – It contains the given string, and it ends with a $ symbol. "
},
{
"code": null,
"e": 3337,
"s": 3194,
"text": "Stack – The combination of state symbol and current input symbol is used to refer to the parsing table in order to take the parsing decisions."
},
{
"code": null,
"e": 3595,
"s": 3337,
"text": "Parsing Table : Parsing table is divided into two parts- Action table and Go-To table. The action table gives a grammar rule to implement the given current state and current terminal in the input stream. There are four cases used in action table as follows."
},
{
"code": null,
"e": 4084,
"s": 3595,
"text": "Shift Action- In shift action the present terminal is removed from the input stream and the state n is pushed onto the stack, and it becomes the new present state.Reduce Action- The number m is written to the output stream.The symbol m mentioned in the left-hand side of rule m says that state is removed from the stack.The symbol m mentioned in the left-hand side of rule m says that a new state is looked up in the goto table and made the new current state by pushing it onto the stack."
},
{
"code": null,
"e": 4248,
"s": 4084,
"text": "Shift Action- In shift action the present terminal is removed from the input stream and the state n is pushed onto the stack, and it becomes the new present state."
},
{
"code": null,
"e": 4309,
"s": 4248,
"text": "Reduce Action- The number m is written to the output stream."
},
{
"code": null,
"e": 4407,
"s": 4309,
"text": "The symbol m mentioned in the left-hand side of rule m says that state is removed from the stack."
},
{
"code": null,
"e": 4576,
"s": 4407,
"text": "The symbol m mentioned in the left-hand side of rule m says that a new state is looked up in the goto table and made the new current state by pushing it onto the stack."
},
{
"code": null,
"e": 4650,
"s": 4576,
"text": "An accept - the string is accepted\nNo action - a syntax error is reported"
},
{
"code": null,
"e": 4710,
"s": 4650,
"text": "Note –The go-to table indicates which state should proceed."
},
{
"code": null,
"e": 4730,
"s": 4710,
"text": "LR parser diagram :"
},
{
"code": null,
"e": 4746,
"s": 4730,
"text": "Compiler Design"
},
{
"code": null,
"e": 4754,
"s": 4746,
"text": "GATE CS"
},
{
"code": null,
"e": 4852,
"s": 4754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4885,
"s": 4852,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 4943,
"s": 4885,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 5013,
"s": 4943,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 5044,
"s": 5013,
"text": "Data flow analysis in Compiler"
},
{
"code": null,
"e": 5084,
"s": 5044,
"text": "Runtime Environments in Compiler Design"
},
{
"code": null,
"e": 5104,
"s": 5084,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 5128,
"s": 5104,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 5155,
"s": 5128,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 5168,
"s": 5155,
"text": "TCP/IP Model"
}
]
|
Full screen OpenCV / GtK application in C++ running on Raspberry PI | 15 Dec, 2021
C++, OpenCV and Gtk are a nice triplet to build applications that run on a Raspberry PI, taking images from the camera, process them, display them and have an unlimited user interface. In this article, I will show you a naive path to display camera captures to a full-screen window. In a second article, I will amend some of the shortcomings of this too-simple method. I hope these two articles can help you through the boring problems you need to solve before reaching the place where you can have fun.
I assume that you know about coding but you are not familiar with C++, Gtk or OpenCV. It was my case when I started this little project, and I spent a huge amount of time discovering the specifics of this rich language and its dependencies. As this is not a C++ tutorial, I will only name the concepts and provide links to the explanations.
Here you will find the project sources: https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv. The master branch shows only the very first step of this tutorial. Further steps are in branches Step1, Step2, etc. To have the full version, you can check out the last step, or the last release.
An important element is to be able to build and test your project in your preferred desktop computer or notebook. Raspberry Pi is meant to be an embedded system platform. It is an amazing one but has not the right keyboard, mouse, monitor or amount of memory required to be a comfortable as a development tool.
I’m using the following technical stack:
Raspberry Pi – The ultimate goal is to launch the application on it.
CMake – This is the needed ingredient to make your code buildable on most of the platforms. It also exports your project to Xcode, VisualStudio, Eclipse and a long list of others, so you will be able to choose your preferred IDE.
Mac OS X, Ubuntu, Windows – Where you can write and test your application.
C++ – Python is fashionable, young, efficient and well supported by Raspberry folks. But I happen to like C++ more. If Python is your thing, then stop reading.
OpenCV – One very widely used open source (hence the Open) computer vision (hence the CV) library.
Gtkmm, which is the C++ oriented port of Gtk – Although OpenCV lets you display images on screen, it is somewhat limited when interacting with the user. Being easily compatible, Gtk / Gtkmm are a great complement to OpenCV for building real user interfaces around computer vision applications.
The first thing you need is a working development environment. I’ve tried the three majors, Mac OS X, Windows and Linux. Linux instructions also apply to Raspberry.
In Mac OS world, the default IDE is Xcode. The other packages are installed via Homebrew.
You have a Mac, so you’re entitled to use Xcode for free. I know that plenty of people who hate it, and they have their reasons. If you know better, then use the IDE you prefer. If not, then use Xcode:
From your Mac, open App Store.
Browse or search Xcode.
Get it or update it.
At first launch, it will propose to install more things. Accept them.
It is a package manager for Mac OS X, and the easiest way to install the rest of packages you need.
Go visit https://brew.sh/
Follow instructions
If you have already an installed version of Homebrew, now it is a good moment to verify, update and fix all that is needed. The following command will give you plenty of suggestions:
$ brew update
$ brew doctor
Follow instructions until you have all of them fixed (well, don’t get too paranoid in any case; fix all that you can).
This package helps to link your project to the OpenCV and GtK libraries (see Wikipedia on pkg-config).
To install it:
$ brew install pkg-config
When installation is finished, you can check if all is right by typing:
$ pkg-config --version
> 0.29.2
$ pkg-config --list-all
> zlib zlib - zlib compression library
> ... etc...
> ... etc...
> ... etc...
> harfbuzz-icu HarfBuzz text shaping library ICU integration
We install OpenCV with third parties contributions. You won’t need them at the beginning, but they won’t bother you either. And we use Gtkmm3, which is the GtK for C++:
brew install opencv3 --with-contrib
brew install gtkmm3
To verify that libraries are now in place:
$ pkg-config --list-all | grep opencv
> opencv OpenCV - Open Source Computer Vision Library
$ pkg-config --list-all | grep gtkmm
> gtkmm-3.0 gtkmm - C++ binding for the GTK+ toolkit
You probably had it installed when you ran brew doctor, and it required to execute the following:
$ xcode-select --install
To verify that you indeed have it:
$ git --version
git version 2.17.2 (Apple Git-113)
TODO
To write this part, my initial intention after installing a fresh Ubuntu distribution was to set up any well known IDE and click around until I could compile, debug and run the project. Boy, was I not naive! Several days later, I have had discarded Clion because it is a paying application, I had unsuccessfully tried Code::Blocks, Eclipse, and lost my patience before trying Qt Builder — yet, I have not been able to find an acceptable IDE to just do the basic stuff with reasonable simplicity. And then I found this Stack Overflow question «C++ IDE for Linux?» where accepted and most voted answer states that «UNIX is an IDE. All of it».
Let’s accept that in Linux we are not going to get a fancy IDE and content ourselves with a text editor. Two popular choices are:
Sublime Text
Real hardcore geeks can configure Vim to be an IDE.
The tool to debug code is gdb. It seems bleak, but you can actually do quite a job with it. Have a look on those videos:
C Programming in Linux Tutorial #056 – GDB debugger (1/2)
Quick Intro to gdb
CppCon 2015: Greg Law ” Give me 15 minutes & I’ll change your view of GDB”
Hitchhikers guide to the gdb
In the first step, a little bit below, I will give short specific instructions for compiling with debug symbols, and debug the programs with gdb.
This is the official package manager of most Linux distribution. Most popular applications are distributed through it and it is most usually pre-installed.
In a Linux distribution, there is the highest chance that pkg-config is already installed. Anyway, you can give it a try; should it be already installed it will just tell you:
sudo apt-get update
sudo apt-get install pkg-config
You will need it to compile OpenCV, so you better install it now:
$ sudo apt-get install cmake
As a prerequisite, you need to have the following libraries from apt-get:
# required:
sudo apt-get install \
libgtk-3-dev \
pkg-config \
libavcodec-dev \
libavformat-dev \
libswscale-dev
# Optional:
sudo apt-get install \
python-dev \
python-numpy \
libjpeg-dev \
libpng-dev \
libtiff-dev \
libjasper-dev \
libdc1394-22-dev
Once you’ve installed all prerequisites, fetch the latest version of OpenCV sources, and unzip it:
$ wget https://github.com/opencv/opencv/archive/3.4.1.zip
$ unzip 3.4.1.zip
Prepare and compile:
$ cd opencv-3.4.1
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local ..
$ make -j4 # Number of processors. Don't use more that you computer has.
Go for a walk; this takes ages. If process breaks, you can launch again by just retyping:
$ make -j4
When compilation is done, complete the installation:
$ sudo make install
$ sudo ldconfig
To check if the library is available as a dependency:
$ pkg-config --list-all | grep opencv
> opencv OpenCV - Open Source Computer Vision Library
You can now delete the sources folder; you don’t need it any more:
$ cd ..
$ cd ..
$ rm -rf opencv-3.4.1
$ rm 3.4.1.zip
Gtkmm is the Gtk for C++:
$ sudo apt-get install libgtkmm-3.0-dev
To check if the library is available as a dependency:
$ pkg-config --list-all | grep gtkmm
gtkmm-3.0 gtkmm - C++ binding for the GTK+ toolkit
To install Git:
$ sudo apt-get install git
And to verify that Git is present:
$ git --version
> git version 2.7.4
There are several great articles that discuss about the best folder structure for a project built with CMake:
https://arne-mertz.de/2018/06/cmake-project-structure/: I like this one because it discusses how to integrate those header-only libraries, and uses Catch as an example.
https://rix0r.nl/blog/2015/08/13/cmake-guide/: I like this one because it shows in detail how to configure CMake and why, and also acknowledges the difference between library (which is easily unit tested) and application (which is the user interface, and not very easy to unit test).
In this first stage (there is more on the second part of the article), I’m proposing a simplified folder structure. Projects having multiple executables and libraries need one folder per module, and the structure is much more complex. In this case, as there will be one single executable, I’m just having one root folder, called src and, in it, one folder for each type of file – sources, headers, and resources.
.gitignore <-- Ignore xcode, codeb, build folders.
/src <----- All sources are here
CMakeList.txt <-- The CMake configuration file.
/cpp <----- Contains the C++ source files.
/hpp <----- Contains the C++ header files.
/res <----- Contains resource files.
/build <----- Contains the temporary build files.
Not under version control
/xcode <----- Contains the XCode project.
Not under version control.
/codeb <----- Contains the Code::Blocks project.
Not under version control.
In this first step we build a very simple single-window application using CMake to configure the project and Gtk to display windows. Source code is available as master branch at: https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv. To retrieve it:
This is the CMakeLists.txt that goes on the src folder:
# src/CMakeLists.txt
cmake_minimum_required(VERSION 3.3 FATAL_ERROR)
# Project name and current version
project(rascam VERSION 0.1 LANGUAGES CXX)
# Enable general warnings
# See http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
# Use 2014 C++ standard.
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# Must use GNUInstallDirs to install libraries into correct locations on all platforms:
include(GNUInstallDirs)
# Pkg_config is used to locate headers and files for dependency libraries:
find_package(PkgConfig)
# Defines variables GTKMM_INCLUDE_DIRS, GTKMM_LIBRARY_DIRS and GTKMM_LIBRARIES.
pkg_check_modules(GTKMM gtkmm-3.0)
# Adds GTKMM_INCLUDE_DIRS, GTKMM_LIBRARY_DIRS to the list of folders the
# compiler and linker will use to look for dependencies:
link_directories( ${GTKMM_LIBRARY_DIRS} )
include_directories( ${GTKMM_INCLUDE_DIRS} )
# Declares a new executable target called rascapp
# and lists the files to compile for it:
add_executable(rascapp
cpp/main.cpp
cpp/main-window.cpp
)
# Adds the folder with all headers:
target_include_directories(rascapp PRIVATE hpp)
# Link files:
target_link_libraries(rascapp
${GTKMM_LIBRARIES}
)
Let’s review the commands one by one:
cmake_minimum_required requires a minimum version of CMake. This allows you do confidently use the features existing in the specified version, or show an explicit error message if installed version is too old.
project declares the name of the global project, rascam, specifies the current version and list the languages that we are using, namely C++. Historically, the extension for C++ was *.c++, but in some context there are problems with «+», so they switched to cpp or cxx. In CMake, CXX means C++.
set(CMAKE_CXX...) sets a few flags that are appropriate for modern C++.
find_package(PkgConfig) links to the pkg-config command, so we can use it later on.
pkg_check_modules(GTKMM gtkmm-3.0) does the same as executing pkg-config gtkmm-3.0 in the terminal (try it, if you wish), and then copies each section of the answer into variables prefixed with the specified GTKMM. Therefore, after this command we have three variables named GTKMM_LIBRARY_DIRS, GTKMM_INCLUDE_DIRS and GTKMM_LIBRARIES.
Then we declare a target. One project can have multiple targets. In general, targets comprise executables or libraries which are defined by calling add_executable or add_library and which can have many properties set (see distinction between a “target” and a “command”). As this is a single target project, it is perfectly convenient to define the target directly in the main CMakeLists.txt file. We list the source files to compile to create the target.
target_include_directories sets the list of folders where to look for the files referred in sources as include "...".
target_link_libraries sets the list of libraries the linker (see about what do linkers do) has to link to complete the build.
In case you want to read more about compilation steps:
How C++ Works: Understanding Compilation
Stack Overflow – How does the compilation/linking process work?
All C++ executables need a main method as entry point. To launch a GtK application, you need to specify a main window, which will act as a base for all other user interaction, including to open more windows.
#include "main-window.hpp" int main(int argc, char* argv[]){ auto app = Gtk::Application::create(argc, argv, "raspberry-cpp-gtk-opencv"); MainWindow mainWindow(300, 300); return app->run(mainWindow);}
Declaring a variable as auto specifies that the type of the variable that is being declared will be automatically deduced from its initialiser. This is called type inference.
The call to Gtk::Application::create initialises a new GtK execution context, passes the Program Arguments, and sets the application id (that can be anything, but convention says that it should contain your domain name in reverse, followed by its name, like in ch.agl-developpement.cpp-tutorial.raspberry-cpp-gtk-opencv)
Once you have a context ready you can use it to open a window. The window that can be an instance of any class that extends Gtk::Window. In this case our main window is called quite explicitly mainWindow and it is an instance of class MainWindow, that we will define later.
The way we define (see the difference between define and declare) the mainWindow variable makes it an automatic variable (not same as auto type inference modifier seen before). Automatic variables are initialised and allocated in memory at the point of definition, and uninitialised and deallocated automatically when their scope is ended (read more about scope). On a local variable, this happens at the closing ‘}’ of their code block. We don’t need to care about deleting automatic variables (see, in contrast, Dynamic memory allocation with new and delete, or also dynamic memory allocation here at geeks for geeks).
Whenever the type of variable is a class (as opposed to a basic type like int), the class constructor is called with the construction arguments and returns the initialised instance. In this case, construction arguments are the initial size of the window.
The call to run will return when the user closes the window. This gives to Gtk execution context the opportunity to control the exit status.
In Gtk, all buttons, labels, checkboxes and elements that displays or interacts with the user are called Widgets. Here is a gallery of Widgets.
Then, gtkmm adds its own sauce:
gtkmm arranges widgets hierarchically, using containers. A Container widget contains other widgets. Most gtkmm widgets are containers. Windows, Notebook tabs, and Buttons are all container widgets. There are two flavors of containers: single-child containers, which are all descendants of Gtk::Bin, and multiple-child containers, which are descendants of Gtk::Container. Most widgets in gtkmm are descendants of Gtk::Bin, including Gtk::Window
See Gtkmm official documentation.
class MainWindow : public Gtk::Window declares MainWindow as a class, and as descendant of, or inheriting from, Gtk::Window. The public modifier makes all public members of the ancestor to be also public members of the descendant. Public inheritance is the most usual way of extending a class (in contrast to private inheritance). We are providing MainWindow to the Gtk execution context, which is expecting all functionalities of a Gtk::Window to be available, so we avoid restricting their access.
As a descendant of Gtk::Window, MainWindow is a single-child container that can only contain one Gtk::Widget. I choose it to be a Gtk::Box, which is a Gtk::Container so, in turn, it is able to contain several widgets. In this occasion I want them to be one Gtk::Button and two Gtk::Label, to illustrate the Packing mechanism that GtK uses to stack together a bunch of controls. For MainWindow to respond to clicks on the button, we declare a buttonClick method (could be any other name, but keep them meaningful) — I’m explaining later how to connect the ‘click’ signal to it.
#ifndef MAIN_WINDOW_H#define MAIN_WINDOW_H #include <gtkmm.h> class MainWindow : public Gtk::Window {public: MainWindow(int width, int height); virtual ~MainWindow() = default; private: void buttonClick(); Gtk::Button m_button; Gtk::Box m_box; Gtk::Label m_label1, m_label2;}; #endif
The two first methods are the constructor and the destructor. As said before, a constructor is called every time we declare a new instance of this class. This constructor accepts initial width and height of the window as parameters.
Whenever an instance is destroyed, the class destructor is called to perform all needed clean up tasks. This destructor has two important modifiers:
virtual means that, in case of inheritance, the method called will be that of the dynamic type. Read more about what is dynamic type of object, virtual functions, and why most of the time it is a good idea to have virtual destructors.
default means that we define this destructor to have a default implementation. The default implementation of a destructor is able to deallocate all defined members of the class, which are m_box, m_button, m_label1 and m_label2 (code>buttonClick is a method therefore it does not need allocation or deallocation). By specifying the default implementation, we spare ourselves the need to define the destructor.
The memory model of C++ has no garbage collector. Reserving and freeing memory is relies on the presence of class constructors and destructors and on a strategy called Resource Acquisition Is Initialisation, or RAII.
Declaration of MainWindow requires two further definitions – the class constructor and the buttonClick method. Here is the code:
#include "main-window.hpp"#include <iostream> MainWindow::MainWindow(int witdh, int height) : m_button("Hello World"), m_box(Gtk::ORIENTATION_VERTICAL), m_label1("First Label"), m_label2("Second Label"){ // Configure this window: this->set_default_size(witdh, height); // Connect the 'click' signal and make the button visible: m_button.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::buttonClick)); m_button.show(); // Make the first label visible: m_label1.show(); // Make the second label visible: m_label2.show(); // Pack all elements in the box: m_box.pack_start(m_button, Gtk::PACK_SHRINK); m_box.pack_start(m_label1, Gtk::PACK_SHRINK); m_box.pack_start(m_label2, Gtk::PACK_EXPAND_WIDGET); // Add the box in this window: add(m_box); // Make the box visible: m_box.show();} void MainWindow::buttonClick(){ std::cout << "Hello World" << std::endl;}
The full name of the constructor is MainWindow::MainWindow, meaning it is the function called MainWindow (the name of the constructor is the same as the class) that belongs to the class MainWindow. It takes width and height as parameters, and starts by calling the constructors of all declared members (read more about constructor member initialiser lists).
Then we set the window’s default size by calling this->set_default_size. The this is a pointer to the current class instance. As it is a pointer, we use -> to access its members. As class MainWindow extends Gtk::Window, this instance contain all public or protected members of this class and those of the the parent class. This is called inheritance. The use of this pointer is actually optional, and the following snippet would also be valid:
.
// Configure this window (now, without the 'this'):
set_default_size(witdh, height);
Next we want to react to the m_button being clicked. One way to achieve this is to connect a function to the click signal of the m_button instance (to see all available signals of a widget, you can check the official documentation, for example, the Gtk::Button has only the clicked signal). Connecting functions to widget’s signals allows to process the event from anywhere in the code, as long as you have access to the widget and you can provide the address of the function.
m_button.signal_clicked().connect([address of the method to call]);
The address of the function could be as simple as placing the function’s name (see about the address of a function). Our case is more complex because the function we want to specify is a member of a class. Member functions need to be provided with the this pointer, so it can access other members of the same instance. To build the pointer to a method of a specific instance, we use sigc::mem_fun:
sigc::mem_fun( // Convert member function to function pointer.
*this, // The address of the instance.
&MainWindow::buttonClick // The address of the method.
);
By default, widgets are not visible. We need to set their visibility explicitly by calling show(). We do this for all widgets, including the m_box.
Next, we pack all elements in the box. During initialisation we already set the box to Gtk::ORIENTATION_VERTICAL, which means that widgets will be positioned one below the other, using all available horizontal space. pack_start adds a new widget to the box, Gtk::PACK_SHRINK specifies that the widget’s vertical size should be as small as possible (Gtk::ORIENTATION_VERTICAL already specifies that all widgets in the box should have a width as big as possible, so the result will be widgets very wide and very flat.)
In contrast, Gtk::PACK_EXPAND_WIDGET specifies that the widget should take all available space. This makes the m_label2 to expand when the user expands the window (you can test this shortly).
The last step is to make the m_box itself visible.
As for the buttonClick method, we just display a message to the standard output.
Start by checking out the source code in some folder where you want place the project. Enter the checked out folder and create a xcode folder that will contain all working data for Xcode. Enter the working folder, create the Xcode project:
$ cd go-to-your-working-folder
$ git clone https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv.git
$ cd raspberry-cpp-gtk-opencv
$ mkdir xcode
$ cd xcode
$ cmake -G Xcode ../src
$ make
Now open Xcode, from the menu, do a File and Open and navigate for the xcode folder, and open one file called rascam.xcodeproj (notice that rascam is the name of the project specified in Cmake. The navigator shall open, showing one folder per target. Some of the targets, like ALL_BUILD and ZERO_CHECK are Xcode internals. There should be one target called rascapp, which is the name of the executable target in Cmake. You will find there your sources and headers. Open any one that you fancy, and place a break point. Then select the rascapp target in the non-descript drop list in the tool bar and, finally, play. If all is right, the application should execute. It is possible that the windows is not on top, so you don’t see it directly.
Clone the example project, configure it with debug symbols, and build it:
$ cd go-to-your-working-folder
$ git clone https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv.git
$ cd raspberry-cpp-gtk-opencv
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Debug ../src
$ make
To debug with gdb, assuming that you’re still in build folder:
$ gdb ./rascapp
[Now you're in gdb]
b main-window.cpp:10 # Place a break-point on line 10 of this file.
run # Run the program. It will stop at the breakpoint.
where # It will show the stack trace
list # It will show some context.
print width # Displays the value of this variable
n # Step over
s # Step into
c # To continue the program
q # Quit gdb
This second step adds a couple of small improvements to the application. First one is to react to key events. As the application will be on the Raspberry Pi, and not always easily accessible via a mouse, it may be handy to have some keyboard shortcuts, in particular, to toggle full-size window or close application. The second improvement is to log events in the system log. Applications that run from command line can cout messages that are directly visible. However, if you launch your window application from a user desktop, you will not see the console, nor the result of cout.
As window application are usually launched from the desktop, the content produced via cout is not easily visible. Instead, you can submit syslog messages (see also a syslog example). It is quite easy to do, and works across all platforms.
In Linux (Ubuntu), you can see the system logs via the System Log application. In Mac OS X it is the Console application. In Windows you can use the Event viewer.
Another way to react to events is to override a specific function in the Widget, that is called whenever that event happens. For example, to react to keyboard events in the MainWindow we have to override the on_key_press_event method. To override a function in C++:
The function has to be declared as virtual in one of the ancestors of our class.
We need to declare it again, in our class, with the exact same signature and accessibility.
We may add the override keyword on the function declaration, to acknowledge the fact that we’re overriding an existing method from a parent class. The compiler shows an error when we use override on a method that doesn’t exist or it is not virtual.
on_key_press_event is declared in class Gtk::Widget as follows:
/// This is a default handler for the signal signal_key_press_event().
virtual bool on_key_press_event(GdkEventKey* key_event);
In consequence, we have to re-declare it our class.
#ifndef MAIN_WINDOW_H#define MAIN_WINDOW_H #include <gtkmm.h> #include "camera-drawing-area.hpp" class MainWindow : public Gtk::Window {public: MainWindow(int width, int height); virtual ~MainWindow() = default; protected: bool on_key_press_event(GdkEventKey* event) override; private: void buttonClick(); bool probablyInFullScreen; Gtk::Button m_button; Gtk::Box m_box; Gtk::Label m_label1; CameraDrawingArea cameraDrawingArea;}; #endif
The Widget where the event is originated is the first to receive it on its on_xx_xxx_event() event handler. If it returns true, the event is considered handled and nothing more is done about it. On the contrary, if the handler cannot do anything about the event, it returns false making the event to be offered to the same handler of its parent widget, and parent’s parent, and so on (see about event propagation in the official documentation). The default implementation of handlers like on_key_press_event is to do nothing but returning false, so events are propagated unless otherwise specified.
[Ctrl] + [C] exits the application, [F] or [f] toggle the full screen mode, and [esc] turns the full mode off:
#include "main-window.hpp"#include <syslog.h> MainWindow::MainWindow(int witdh, int height) : probablyInFullScreen(false), m_button("Hello World"), m_box(Gtk::ORIENTATION_VERTICAL), m_label1("First Label"){ // Configure this window: this->set_default_size(witdh, height); // Connect the 'click' signal and make the button visible: m_button.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::buttonClick)); m_button.show(); // Make the first label visible: m_label1.show(); // Make the second label visible: cameraDrawingArea.show(); // Pack all elements in the box: m_box.pack_start(m_button, Gtk::PACK_SHRINK); m_box.pack_start(m_label1, Gtk::PACK_SHRINK); m_box.pack_start(cameraDrawingArea, Gtk::PACK_EXPAND_WIDGET); // Add the box in this window: add(m_box); // Make the box visible: m_box.show(); // Activate Key-Press events add_events(Gdk::KEY_PRESS_MASK);} void MainWindow::buttonClick(){ syslog(LOG_NOTICE, "Hello world!");} bool MainWindow::on_key_press_event(GdkEventKey* event){ switch (event->keyval) { // Ctrl + C: Ends the app: case GDK_KEY_C: case GDK_KEY_c: if ((event->state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK) { get_application()->quit(); } return true; // [F] toggles fullscreen mode: case GDK_KEY_F: case GDK_KEY_f: if (probablyInFullScreen) { unfullscreen(); probablyInFullScreen = false; } else { fullscreen(); probablyInFullScreen = true; } return true; // [esc] exits fullscreen mode: case GDK_KEY_Escape: unfullscreen(); probablyInFullScreen = false; return true; } return false;}
By default, the events are not captured. add_events(Gdk::KEY_PRESS_MASK) activates the capture of keyboard events.
The functions to toggle full screen are fullscreen() and unfullscreen(), both belong to the Gtk::Window class (here we’re omitting the this pointer). The documentation warns that you shouldn’t assume the window is definitely full screen afterward, because other entities (e.g. the user or window manager) could toggle it on or off again, and not all window managers honor those requests. That’s why we have added a probablyInFullScreen status, that conveys the possibility that window is not in the expected state.
To exit the application we are not directly calling exit(), instead we use get_application()->quit() to tell the Gtk execution context to call exit. It will, eventually, but first it is going to close all windows and open devices for us.
To capture images we’re using OpenCV. If you just want to capture an image from the camera, you could use other libraries, but the final objective is to apply computer vision algorithms to the captured image. Hence, OpenCV is the best alternative.
For security reasons, Mac OS X forces applications to request user’s permission before using the camera. The procedure for this is to include a Info.plist file with the necessary content:
Some indications about version number and author.
A key NSCameraUsageDescription with the description on why your application needs the camera. The message you write here is displayed to the user, who has to accept it. If he doesn’t accept, the system terminates your application.
The procedure is to include a MacOSXBundleInfo.plist.in file, which is a template; some of the entries can be governed by properties in the CMakeLists.txt file, and others you can put yourself. The file is placed in src/res folder and has the following content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC
"-//Apple Computer//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
<key>CFBundleGetInfoString</key>
<string>${MACOSX_BUNDLE_INFO_STRING}</string>
<key>CFBundleIconFile</key>
<string>${MACOSX_BUNDLE_ICON_FILE}</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>
<key>CFBundleName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>NSCameraUsageDescription</key>
<string>This app requires to access your camera to retrieve images and perform the demo</string>
</dict>
</plist>
These are some of the resources I used to found out how to do bundles in Mac OS X:
An official documentation, quite old, about Bundles-And-Frameworks
The original Info.plist template.
After installing OpenCV following the previous instructions, you can link your application to it in CMake.
# src/CMakeLists.txt
cmake_minimum_required(VERSION 3.3 FATAL_ERROR)
# Project name and current version
project(rascam VERSION 0.1 LANGUAGES CXX)
# Enable general warnings
# See http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
# Use 2014 C++ standard.
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# Must use GNUInstallDirs to install libraries into correct locations on all platforms:
include(GNUInstallDirs)
# Pkg_config is used to locate header and files for dependency libraries:
find_package(PkgConfig)
# Defines variables GTKMM_INCLUDE_DIRS, GTKMM_LIBRARY_DIRS and GTKMM_LIBRARIES.
pkg_check_modules(GTKMM gtkmm-3.0)
link_directories( ${GTKMM_LIBRARY_DIRS} )
include_directories( ${GTKMM_INCLUDE_DIRS} )
# OpenCV can be linked in a more standard manner:
find_package( OpenCV REQUIRED )
# Compile files:
add_executable(rascapp
cpp/main.cpp
cpp/main-window.cpp
cpp/camera-drawing-area.cpp
)
# Add folder with all headers:
target_include_directories(rascapp PRIVATE hpp)
# Link files:
target_link_libraries(rascapp
${GTKMM_LIBRARIES}
${OpenCV_LIBS}
)
# Apple requires a bundle to add a Info.plist file that contains the required
# permissions to access some restricted resources like the camera:
if (APPLE)
set_target_properties(rascapp PROPERTIES
MACOSX_BUNDLE TRUE
MACOSX_FRAMEWORK_IDENTIFIER org.cmake.ExecutableTarget
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/res/MacOSXBundleInfo.plist.in
# This property is required:
MACOSX_BUNDLE_GUI_IDENTIFIER "rascapp-${PROJECT_VERSION}"
# Those properties are not required:
MACOSX_BUNDLE_INFO_STRING "rascapp ${PROJECT_VERSION}, by [email protected]"
MACOSX_BUNDLE_LONG_VERSION_STRING ${PROJECT_VERSION}
MACOSX_BUNDLE_BUNDLE_NAME "rascapp"
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION}
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
)
endif()
Gtk::DrawingArea is a widget that holds a graphic area to display custom drawings or bitmaps. We define a CameraDrawingArea that extends this widget, and copies the image captured from the camera into the graphic area:
#ifndef CAMERA_DRAWING_AREA_H#define CAMERA_DRAWING_AREA_H #include <gtkmm.h>#include <opencv2/highgui.hpp> class CameraDrawingArea : public Gtk::DrawingArea {public: CameraDrawingArea(); virtual ~CameraDrawingArea(); protected: bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override; void on_size_allocate(Gtk::Allocation& allocation) override; bool everyNowAndThen(); private: sigc::connection everyNowAndThenConnection; cv::VideoCapture videoCapture; cv::Mat webcam; cv::Mat output; int width, height;};#endif
We’re going to extend this class and override two of its methods:
void on_size_allocate(Gtk::Allocation& allocation) – This method is called every time the size of the widget changes. This happens the very first time it is displayed, and every time some action of the user or the system makes the size change.
bool on_draw(const Cairo::RefPtr& cr) – This method is called every time the area, or part of the area, contained in the widget has to be redrawn. It receives a reference to a Cairo context. The method can use it to render any drawing or graphic. In our case we’re going to use it to copy the image captured from the camera.
The cv::Mat is a class that contains a OpenCV image. We’re using two of those: one contains the image captured from the camera, and the other contains the image resized to the Widget current size.
The width and height contain the current Widget size.
VideoCapture is a OpenCV access to the video camera.
everyNowAndThenConnection is a way to call everyNowAndThen() method at regular time intervals, similarly as we set the response to the button click, in previous steps.
This is the
#include "opencv2/core.hpp"#include "opencv2/highgui.hpp"#include "opencv2/imgproc.hpp" #include "camera-drawing-area.hpp" CameraDrawingArea::CameraDrawingArea() : videoCapture(0){ // Lets refresh drawing area very now and then. everyNowAndThenConnection = Glib::signal_timeout().connect(sigc::mem_fun(*this, &CameraDrawingArea::everyNowAndThen), 100);} CameraDrawingArea::~CameraDrawingArea(){ everyNowAndThenConnection.disconnect();} /** * Every now and then, we invalidate the whole Widget rectangle, * forcing a complete refresh. */bool CameraDrawingArea::everyNowAndThen(){ auto win = get_window(); if (win) { Gdk::Rectangle r(0, 0, width, height); win->invalidate_rect(r, false); } // Don't stop calling me: return true;} /** * Called every time the widget has its allocation changed. */void CameraDrawingArea::on_size_allocate(Gtk::Allocation& allocation){ // Call the parent to do whatever needs to be done: DrawingArea::on_size_allocate(allocation); // Remember the new allocated size for resizing operation: width = allocation.get_width(); height = allocation.get_height();} /** * Called every time the widget needs to be redrawn. * This happens when the Widget got resized, or obscured by * another object, or every now and then. */bool CameraDrawingArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr){ // Prevent the drawing if size is 0: if (width == 0 || height == 0) { return true; } // Capture one image from camera: videoCapture.read(webcam); // Resize it to the allocated size of the Widget. resize(webcam, output, cv::Size(width, height), 0, 0, cv::INTER_LINEAR); // Initializes a pixbuf sharing the same data as the mat: Glib::RefPtr<Gdk::Pixbuf> pixbuf = Gdk::Pixbuf::create_from_data( (guint8*)output.data, Gdk::COLORSPACE_RGB, false, 8, output.cols, output.rows, (int)output.step); // Display Gdk::Cairo::set_source_pixbuf(cr, pixbuf); cr->paint(); // Don't stop calling me. return true;}
In the constructor we start by initialising videoConstructor to the default device. Then we set up a connection to call the everyNowAndThen method every 100ms (10 x per second). Later we call the connection to disconnect it during the destruction process.
The everyNowAndThen() method invalidates the whole area of the widget. This is an indirect way to provoke a call to on_draw.
on_size_allocate keeps track of the current size of the Widget. Just in case the parent class did implement something important in its own implementation, we call the parent method.
Everything we put in place before is so on_draw is called regularly, and we can use the reference to Cairo::Context to paste the image captured from the camera:
First we check that the current width and height are not zero. This may happen during startup phase. Calling resize with a 0 dimension would terminate instantly the application so we better avoid it.
videoCapture.read(webcam) copies the captured image into the provided cv::Mat, in this case webcam. If the provided material is not initialised, or it is not of the appropriate size, then the method will perform necessary tasks, and reserve needed memory.
resize copies the image from source (webcam) to destination (output), changing its size. If the destination is not initialised or not of the right size it performs necessary tasks and memory reservation. To keep the variable in scope, we also declared it as a class property: first call will initialise the variable, next calls can just reuse it.
Both webcam and output are class properties so they keep in scope as long as the class instance does. They will need to be initialised only during the first call to on_draw but will keep their values across the subsequent calls. This helps noticeably the performance.
create_from_data creates a new Gdk::Pixbuf object, which contains an image in a format compatible with Cairo. The long list of parameters are to be taken as a recipe to convert OpenCV‘s Material to Gtk‘s Pixbuf.
set_source_pixbuf sets the bitmap source to use for next call to paint
Finally, paint does the painting.
The last step is to place the widget we just created in the main window. We need to declare it in the MainWindow header:
#ifndef MAIN_WINDOW_H#define MAIN_WINDOW_H #include <gtkmm.h> #include "camera-drawing-area.hpp" class MainWindow : public Gtk::Window {public: MainWindow(int width, int height); virtual ~MainWindow() = default; protected: bool on_key_press_event(GdkEventKey* event) override; private: void buttonClick(); bool probablyInFullScreen; Gtk::Button m_button; Gtk::Box m_box; Gtk::Label m_label1; CameraDrawingArea cameraDrawingArea;}; #endif
And place it in the box, just the same as a label or a button:
#include <syslog.h>#include <unistd.h> #include "main-window.hpp" MainWindow::MainWindow(int width, int height) : probablyInFullScreen(false), m_button("Hello World"), m_box(Gtk::ORIENTATION_VERTICAL), m_label1("First Label"){ // Configure this window: this->set_default_size(width, height); // Connect the 'click' signal and make the button visible: m_button.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::buttonClick)); m_button.show(); // Make the first label visible: m_label1.show(); // Make the second label visible: cameraDrawingArea.show(); // Pack all elements in the box: m_box.pack_start(m_button, Gtk::PACK_SHRINK); m_box.pack_start(m_label1, Gtk::PACK_SHRINK); m_box.pack_start(cameraDrawingArea, Gtk::PACK_EXPAND_WIDGET); // Add the box in this window: add(m_box); // Make the box visible: m_box.show(); // Activate Key-Press events add_events(Gdk::KEY_PRESS_MASK);} void MainWindow::buttonClick(){ syslog(LOG_NOTICE, "User %d says 'Hello World'", getuid());} bool MainWindow::on_key_press_event(GdkEventKey* event){ switch (event->keyval) { // Ctrl + C: Ends the app: case GDK_KEY_C: case GDK_KEY_c: if ((event->state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK) { get_application()->quit(); } return true; // [F] toggles fullscreen mode: case GDK_KEY_F: case GDK_KEY_f: if (probablyInFullScreen) { unfullscreen(); probablyInFullScreen = false; } else { fullscreen(); probablyInFullScreen = true; } return true; // [esc] exits fullscreen mode: case GDK_KEY_Escape: unfullscreen(); probablyInFullScreen = false; return true; } return false;}
Last but not least, you need to install the project on a Raspberry Pi.
The easiest way is to do it from the desktop:
Raspberry –> PreferencesOpen Interfaces tab.Enable the CameraTo check that the camera works, type:$ raspistill -f -t 0
You should be able to see images from camera. Exit with Ctrl+C.Driver v4L2In Raspberry, the v4L2 driver offers the standard interface to the camera that OpenCV needs to capture images. The driver is installed by default, but not active. To activate it:$ sudo modprobe bcm2835-v4l2
$ ls /dev/video0
If the device /dev/vide0 is present, it means that the driver is active. To activate it by default when the Raspberry starts, edit file /etc/modules and add the following snippet at the bottom:bcm2835-v4l2
Install toolingTo be able to download and build the project, you need the same tooling as in your development platform: Git, Cmake, pkg-config and the libraries Gtk and OpenCV. To install them, follow the procedure for the Linux environment, in this same article.AutorunYou may want Raspberry Pi to launch your application at startup. The easiest way I found to auto-run a GUI application in Raspberry is to create a desktop file in the autostart directory. In a brand new installation, this directory doesn’t exist and you need to create it:$ mkdir ~/.config/autostart
$ vim ~/.config/autostart/rascapp.desktop
The content of “rascapp.desktop“ should be similar to:[Desktop Entry]
Name=raspberry-pi-camera-display
Exec=/home/pi/raspberry-cpp-gtk-opencv/build/rascapp
Path=/home/pi
Type=application
The Path key is the root folder for the application, when accessing files by a relative path.See more about syntax here: See original explanation here: Avoid console blankingConsole blanking affects you if you’re using ssh to execute commands. If for some time, you don’t type anythingin the console, it will close.To avoid it, edit file /boot/cmdline.txt and append the parameter consoleblank=0See original explanation here: https://www.raspberrypi.org/documentation/configuration/screensaver.mdAvoid idle screenDisplay-only applications, will typically have no user interaction, so screen may go idle leaving you in the dark. To prevent this, the simplest approach is to install a screen saver and then configure it to NOT run:$ sudo apt-get install xscreensaver
After this, screensaver application is in Preferences, in desktop menu. Use the appropriate options to prevent screen saver.Enabling composite video outIf you’re placing the Raspberry on board of some mobile device with a FPV transmitter, you probably want to use the Analog Video Out. Edit the /boot/config.txt file and modify the entries as following:...
sdtv_mode=2
...
hdmi_force_hotplug=0
...
When hdmi_force_hotplug is set to 1, the system assumes that there is a HDMI device present, soit never activates video composite output.When hdmi_force_hotplug is set to 0, the system will use composite video unless it detects HDMI device. So,Raspberry will still use the HDMI monitor if it is connected during boot sequence.See more about this:Original article: Force Raspberry Pi output to composite video instead of HDMIOfficial doc: Configure composite videoMore official: Configuring the Raspberry PiTroubleshootingI hope you don’t need this section.Gtk-ERROR **: GTK+ 2.x symbols detected.If you get this error message:Gtk-ERROR **: GTK+ 2.x symbols detected.
Using GTK+ 2.x and GTK+ 3 in the same process is not
supported
You may accidentally linked OpenCV with Gtk2. As this project uses Gtk3, there is a conflict. You need to be sure that OpenCV is linked with Gtk3.Start by uninstalling Gtk2 and ensuring Gtk3 is present:$ sudo apt-get remove libgtk2.0-dev
sudo apt-get install libgtk-3-dev
sudo apt-get auto-remove
sudo apt-get install libgtkmm-3.0-dev
Build again OpenCV:If you haven’t done this yet, then remove the build directory of OpenCV.Start again the building procedure as described above BUT...Before launching make, check the cmake log, and verify the Gtk version is linked with. Look for something like this:...
-- GUI:
-- GTK+: YES (ver 3.22.11)
-- GThread : YES (ver 2.50.3)
-- GtkGlExt: NO
-- VTK support: NO
...
ConclusionThis example is a working proof of concept on how write a cross-platform application based on two very popular libraries, OpenCV for processing computer vision and Gtk for user interface. However, there are a list of shortcomings that need to be addressed before you can use it as a base for the more complex application that you may have in mind:The more visible one is that the image is deformed to match the size of the window. This can be easily solved using a more sophisticated algorithm to calculate a size that would fit in the window but keep the original aspect ratio.A second one, very annoying if you plan a First Person View application is the perceptible lag between real life and the images stream. Lag seems variable depending on the camera and the light conditions. The reason is cameras having an image buffer; as we are retrieving one image every now and then, we’re always consuming the oldest image in the buffer. To solve this we should let the capture process drive the window refresh, instead of using a timer.Code has a general lack of decoupling that makes everything very dependent on everything else. This defect isn’t very present in such a simple application, but it will show as soon as we try to solve the lag problem. Also, part of the code should be a pure OpenCV process that you could copy/paste from some other blog, without needing to adapt it to the CameraDrawingArea that is dependent on both OpenCV and Gtk libraries.Finally, you should be able to unit test the OpenCV processing to increase the type-compile-debug cycle.My next article covers those topics.My Personal Notes
arrow_drop_upSave
Raspberry –> Preferences
Open Interfaces tab.
Enable the Camera
To check that the camera works, type:
$ raspistill -f -t 0
You should be able to see images from camera. Exit with Ctrl+C.
In Raspberry, the v4L2 driver offers the standard interface to the camera that OpenCV needs to capture images. The driver is installed by default, but not active. To activate it:
$ sudo modprobe bcm2835-v4l2
$ ls /dev/video0
If the device /dev/vide0 is present, it means that the driver is active. To activate it by default when the Raspberry starts, edit file /etc/modules and add the following snippet at the bottom:
bcm2835-v4l2
To be able to download and build the project, you need the same tooling as in your development platform: Git, Cmake, pkg-config and the libraries Gtk and OpenCV. To install them, follow the procedure for the Linux environment, in this same article.
You may want Raspberry Pi to launch your application at startup. The easiest way I found to auto-run a GUI application in Raspberry is to create a desktop file in the autostart directory. In a brand new installation, this directory doesn’t exist and you need to create it:
$ mkdir ~/.config/autostart
$ vim ~/.config/autostart/rascapp.desktop
The content of “rascapp.desktop“ should be similar to:
[Desktop Entry]
Name=raspberry-pi-camera-display
Exec=/home/pi/raspberry-cpp-gtk-opencv/build/rascapp
Path=/home/pi
Type=application
The Path key is the root folder for the application, when accessing files by a relative path.
See more about syntax here:
See original explanation here:
Console blanking affects you if you’re using ssh to execute commands. If for some time, you don’t type anythingin the console, it will close.
To avoid it, edit file /boot/cmdline.txt and append the parameter consoleblank=0
See original explanation here: https://www.raspberrypi.org/documentation/configuration/screensaver.md
Display-only applications, will typically have no user interaction, so screen may go idle leaving you in the dark. To prevent this, the simplest approach is to install a screen saver and then configure it to NOT run:
$ sudo apt-get install xscreensaver
After this, screensaver application is in Preferences, in desktop menu. Use the appropriate options to prevent screen saver.
If you’re placing the Raspberry on board of some mobile device with a FPV transmitter, you probably want to use the Analog Video Out. Edit the /boot/config.txt file and modify the entries as following:
...
sdtv_mode=2
...
hdmi_force_hotplug=0
...
When hdmi_force_hotplug is set to 1, the system assumes that there is a HDMI device present, soit never activates video composite output.
When hdmi_force_hotplug is set to 0, the system will use composite video unless it detects HDMI device. So,Raspberry will still use the HDMI monitor if it is connected during boot sequence.
See more about this:
Original article: Force Raspberry Pi output to composite video instead of HDMI
Official doc: Configure composite video
More official: Configuring the Raspberry Pi
I hope you don’t need this section.
If you get this error message:
Gtk-ERROR **: GTK+ 2.x symbols detected.
Using GTK+ 2.x and GTK+ 3 in the same process is not
supported
You may accidentally linked OpenCV with Gtk2. As this project uses Gtk3, there is a conflict. You need to be sure that OpenCV is linked with Gtk3.
Start by uninstalling Gtk2 and ensuring Gtk3 is present:
$ sudo apt-get remove libgtk2.0-dev
sudo apt-get install libgtk-3-dev
sudo apt-get auto-remove
sudo apt-get install libgtkmm-3.0-dev
Build again OpenCV:
If you haven’t done this yet, then remove the build directory of OpenCV.
Start again the building procedure as described above BUT...
Before launching make, check the cmake log, and verify the Gtk version is linked with. Look for something like this:
...
-- GUI:
-- GTK+: YES (ver 3.22.11)
-- GThread : YES (ver 2.50.3)
-- GtkGlExt: NO
-- VTK support: NO
...
This example is a working proof of concept on how write a cross-platform application based on two very popular libraries, OpenCV for processing computer vision and Gtk for user interface. However, there are a list of shortcomings that need to be addressed before you can use it as a base for the more complex application that you may have in mind:
The more visible one is that the image is deformed to match the size of the window. This can be easily solved using a more sophisticated algorithm to calculate a size that would fit in the window but keep the original aspect ratio.
A second one, very annoying if you plan a First Person View application is the perceptible lag between real life and the images stream. Lag seems variable depending on the camera and the light conditions. The reason is cameras having an image buffer; as we are retrieving one image every now and then, we’re always consuming the oldest image in the buffer. To solve this we should let the capture process drive the window refresh, instead of using a timer.
Code has a general lack of decoupling that makes everything very dependent on everything else. This defect isn’t very present in such a simple application, but it will show as soon as we try to solve the lag problem. Also, part of the code should be a pure OpenCV process that you could copy/paste from some other blog, without needing to adapt it to the CameraDrawingArea that is dependent on both OpenCV and Gtk libraries.
Finally, you should be able to unit test the OpenCV processing to increase the type-compile-debug cycle.
My next article covers those topics.
Akanksha_Rai
rkbhola5
Articles
C++
GBlog
Project
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 532,
"s": 28,
"text": "C++, OpenCV and Gtk are a nice triplet to build applications that run on a Raspberry PI, taking images from the camera, process them, display them and have an unlimited user interface. In this article, I will show you a naive path to display camera captures to a full-screen window. In a second article, I will amend some of the shortcomings of this too-simple method. I hope these two articles can help you through the boring problems you need to solve before reaching the place where you can have fun."
},
{
"code": null,
"e": 873,
"s": 532,
"text": "I assume that you know about coding but you are not familiar with C++, Gtk or OpenCV. It was my case when I started this little project, and I spent a huge amount of time discovering the specifics of this rich language and its dependencies. As this is not a C++ tutorial, I will only name the concepts and provide links to the explanations."
},
{
"code": null,
"e": 1167,
"s": 873,
"text": "Here you will find the project sources: https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv. The master branch shows only the very first step of this tutorial. Further steps are in branches Step1, Step2, etc. To have the full version, you can check out the last step, or the last release."
},
{
"code": null,
"e": 1478,
"s": 1167,
"text": "An important element is to be able to build and test your project in your preferred desktop computer or notebook. Raspberry Pi is meant to be an embedded system platform. It is an amazing one but has not the right keyboard, mouse, monitor or amount of memory required to be a comfortable as a development tool."
},
{
"code": null,
"e": 1519,
"s": 1478,
"text": "I’m using the following technical stack:"
},
{
"code": null,
"e": 1588,
"s": 1519,
"text": "Raspberry Pi – The ultimate goal is to launch the application on it."
},
{
"code": null,
"e": 1818,
"s": 1588,
"text": "CMake – This is the needed ingredient to make your code buildable on most of the platforms. It also exports your project to Xcode, VisualStudio, Eclipse and a long list of others, so you will be able to choose your preferred IDE."
},
{
"code": null,
"e": 1893,
"s": 1818,
"text": "Mac OS X, Ubuntu, Windows – Where you can write and test your application."
},
{
"code": null,
"e": 2053,
"s": 1893,
"text": "C++ – Python is fashionable, young, efficient and well supported by Raspberry folks. But I happen to like C++ more. If Python is your thing, then stop reading."
},
{
"code": null,
"e": 2152,
"s": 2053,
"text": "OpenCV – One very widely used open source (hence the Open) computer vision (hence the CV) library."
},
{
"code": null,
"e": 2446,
"s": 2152,
"text": "Gtkmm, which is the C++ oriented port of Gtk – Although OpenCV lets you display images on screen, it is somewhat limited when interacting with the user. Being easily compatible, Gtk / Gtkmm are a great complement to OpenCV for building real user interfaces around computer vision applications."
},
{
"code": null,
"e": 2611,
"s": 2446,
"text": "The first thing you need is a working development environment. I’ve tried the three majors, Mac OS X, Windows and Linux. Linux instructions also apply to Raspberry."
},
{
"code": null,
"e": 2701,
"s": 2611,
"text": "In Mac OS world, the default IDE is Xcode. The other packages are installed via Homebrew."
},
{
"code": null,
"e": 2903,
"s": 2701,
"text": "You have a Mac, so you’re entitled to use Xcode for free. I know that plenty of people who hate it, and they have their reasons. If you know better, then use the IDE you prefer. If not, then use Xcode:"
},
{
"code": null,
"e": 2934,
"s": 2903,
"text": "From your Mac, open App Store."
},
{
"code": null,
"e": 2958,
"s": 2934,
"text": "Browse or search Xcode."
},
{
"code": null,
"e": 2979,
"s": 2958,
"text": "Get it or update it."
},
{
"code": null,
"e": 3049,
"s": 2979,
"text": "At first launch, it will propose to install more things. Accept them."
},
{
"code": null,
"e": 3149,
"s": 3049,
"text": "It is a package manager for Mac OS X, and the easiest way to install the rest of packages you need."
},
{
"code": null,
"e": 3175,
"s": 3149,
"text": "Go visit https://brew.sh/"
},
{
"code": null,
"e": 3195,
"s": 3175,
"text": "Follow instructions"
},
{
"code": null,
"e": 3378,
"s": 3195,
"text": "If you have already an installed version of Homebrew, now it is a good moment to verify, update and fix all that is needed. The following command will give you plenty of suggestions:"
},
{
"code": null,
"e": 3407,
"s": 3378,
"text": "$ brew update\n$ brew doctor\n"
},
{
"code": null,
"e": 3526,
"s": 3407,
"text": "Follow instructions until you have all of them fixed (well, don’t get too paranoid in any case; fix all that you can)."
},
{
"code": null,
"e": 3629,
"s": 3526,
"text": "This package helps to link your project to the OpenCV and GtK libraries (see Wikipedia on pkg-config)."
},
{
"code": null,
"e": 3644,
"s": 3629,
"text": "To install it:"
},
{
"code": null,
"e": 3671,
"s": 3644,
"text": "$ brew install pkg-config\n"
},
{
"code": null,
"e": 3743,
"s": 3671,
"text": "When installation is finished, you can check if all is right by typing:"
},
{
"code": null,
"e": 4089,
"s": 3743,
"text": "$ pkg-config --version\n> 0.29.2\n$ pkg-config --list-all\n> zlib zlib - zlib compression library\n> ... etc...\n> ... etc...\n> ... etc...\n> harfbuzz-icu HarfBuzz text shaping library ICU integration\n"
},
{
"code": null,
"e": 4258,
"s": 4089,
"text": "We install OpenCV with third parties contributions. You won’t need them at the beginning, but they won’t bother you either. And we use Gtkmm3, which is the GtK for C++:"
},
{
"code": null,
"e": 4315,
"s": 4258,
"text": "brew install opencv3 --with-contrib\nbrew install gtkmm3\n"
},
{
"code": null,
"e": 4358,
"s": 4315,
"text": "To verify that libraries are now in place:"
},
{
"code": null,
"e": 4596,
"s": 4358,
"text": "$ pkg-config --list-all | grep opencv\n> opencv OpenCV - Open Source Computer Vision Library\n$ pkg-config --list-all | grep gtkmm\n> gtkmm-3.0 gtkmm - C++ binding for the GTK+ toolkit\n"
},
{
"code": null,
"e": 4694,
"s": 4596,
"text": "You probably had it installed when you ran brew doctor, and it required to execute the following:"
},
{
"code": null,
"e": 4720,
"s": 4694,
"text": "$ xcode-select --install\n"
},
{
"code": null,
"e": 4755,
"s": 4720,
"text": "To verify that you indeed have it:"
},
{
"code": null,
"e": 4807,
"s": 4755,
"text": "$ git --version\ngit version 2.17.2 (Apple Git-113)\n"
},
{
"code": null,
"e": 4812,
"s": 4807,
"text": "TODO"
},
{
"code": null,
"e": 5453,
"s": 4812,
"text": "To write this part, my initial intention after installing a fresh Ubuntu distribution was to set up any well known IDE and click around until I could compile, debug and run the project. Boy, was I not naive! Several days later, I have had discarded Clion because it is a paying application, I had unsuccessfully tried Code::Blocks, Eclipse, and lost my patience before trying Qt Builder — yet, I have not been able to find an acceptable IDE to just do the basic stuff with reasonable simplicity. And then I found this Stack Overflow question «C++ IDE for Linux?» where accepted and most voted answer states that «UNIX is an IDE. All of it»."
},
{
"code": null,
"e": 5583,
"s": 5453,
"text": "Let’s accept that in Linux we are not going to get a fancy IDE and content ourselves with a text editor. Two popular choices are:"
},
{
"code": null,
"e": 5596,
"s": 5583,
"text": "Sublime Text"
},
{
"code": null,
"e": 5648,
"s": 5596,
"text": "Real hardcore geeks can configure Vim to be an IDE."
},
{
"code": null,
"e": 5769,
"s": 5648,
"text": "The tool to debug code is gdb. It seems bleak, but you can actually do quite a job with it. Have a look on those videos:"
},
{
"code": null,
"e": 5827,
"s": 5769,
"text": "C Programming in Linux Tutorial #056 – GDB debugger (1/2)"
},
{
"code": null,
"e": 5846,
"s": 5827,
"text": "Quick Intro to gdb"
},
{
"code": null,
"e": 5921,
"s": 5846,
"text": "CppCon 2015: Greg Law ” Give me 15 minutes & I’ll change your view of GDB”"
},
{
"code": null,
"e": 5950,
"s": 5921,
"text": "Hitchhikers guide to the gdb"
},
{
"code": null,
"e": 6096,
"s": 5950,
"text": "In the first step, a little bit below, I will give short specific instructions for compiling with debug symbols, and debug the programs with gdb."
},
{
"code": null,
"e": 6252,
"s": 6096,
"text": "This is the official package manager of most Linux distribution. Most popular applications are distributed through it and it is most usually pre-installed."
},
{
"code": null,
"e": 6428,
"s": 6252,
"text": "In a Linux distribution, there is the highest chance that pkg-config is already installed. Anyway, you can give it a try; should it be already installed it will just tell you:"
},
{
"code": null,
"e": 6481,
"s": 6428,
"text": "sudo apt-get update\nsudo apt-get install pkg-config\n"
},
{
"code": null,
"e": 6547,
"s": 6481,
"text": "You will need it to compile OpenCV, so you better install it now:"
},
{
"code": null,
"e": 6577,
"s": 6547,
"text": "$ sudo apt-get install cmake\n"
},
{
"code": null,
"e": 6651,
"s": 6577,
"text": "As a prerequisite, you need to have the following libraries from apt-get:"
},
{
"code": null,
"e": 6939,
"s": 6651,
"text": "# required:\nsudo apt-get install \\\n libgtk-3-dev \\\n pkg-config \\\n libavcodec-dev \\\n libavformat-dev \\\n libswscale-dev \n# Optional:\nsudo apt-get install \\\n python-dev \\\n python-numpy \\\n libjpeg-dev \\\n libpng-dev \\\n libtiff-dev \\\n libjasper-dev \\\n libdc1394-22-dev\n"
},
{
"code": null,
"e": 7038,
"s": 6939,
"text": "Once you’ve installed all prerequisites, fetch the latest version of OpenCV sources, and unzip it:"
},
{
"code": null,
"e": 7115,
"s": 7038,
"text": "$ wget https://github.com/opencv/opencv/archive/3.4.1.zip\n$ unzip 3.4.1.zip\n"
},
{
"code": null,
"e": 7136,
"s": 7115,
"text": "Prepare and compile:"
},
{
"code": null,
"e": 7326,
"s": 7136,
"text": "$ cd opencv-3.4.1\n$ mkdir build\n$ cd build\n$ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local ..\n$ make -j4 # Number of processors. Don't use more that you computer has.\n"
},
{
"code": null,
"e": 7416,
"s": 7326,
"text": "Go for a walk; this takes ages. If process breaks, you can launch again by just retyping:"
},
{
"code": null,
"e": 7428,
"s": 7416,
"text": "$ make -j4\n"
},
{
"code": null,
"e": 7481,
"s": 7428,
"text": "When compilation is done, complete the installation:"
},
{
"code": null,
"e": 7518,
"s": 7481,
"text": "$ sudo make install\n$ sudo ldconfig\n"
},
{
"code": null,
"e": 7572,
"s": 7518,
"text": "To check if the library is available as a dependency:"
},
{
"code": null,
"e": 7689,
"s": 7572,
"text": "$ pkg-config --list-all | grep opencv\n> opencv OpenCV - Open Source Computer Vision Library\n"
},
{
"code": null,
"e": 7756,
"s": 7689,
"text": "You can now delete the sources folder; you don’t need it any more:"
},
{
"code": null,
"e": 7810,
"s": 7756,
"text": "$ cd ..\n$ cd ..\n$ rm -rf opencv-3.4.1\n$ rm 3.4.1.zip\n"
},
{
"code": null,
"e": 7836,
"s": 7810,
"text": "Gtkmm is the Gtk for C++:"
},
{
"code": null,
"e": 7877,
"s": 7836,
"text": "$ sudo apt-get install libgtkmm-3.0-dev\n"
},
{
"code": null,
"e": 7931,
"s": 7877,
"text": "To check if the library is available as a dependency:"
},
{
"code": null,
"e": 8041,
"s": 7931,
"text": "$ pkg-config --list-all | grep gtkmm\ngtkmm-3.0 gtkmm - C++ binding for the GTK+ toolkit\n"
},
{
"code": null,
"e": 8057,
"s": 8041,
"text": "To install Git:"
},
{
"code": null,
"e": 8085,
"s": 8057,
"text": "$ sudo apt-get install git\n"
},
{
"code": null,
"e": 8120,
"s": 8085,
"text": "And to verify that Git is present:"
},
{
"code": null,
"e": 8157,
"s": 8120,
"text": "$ git --version\n> git version 2.7.4\n"
},
{
"code": null,
"e": 8267,
"s": 8157,
"text": "There are several great articles that discuss about the best folder structure for a project built with CMake:"
},
{
"code": null,
"e": 8436,
"s": 8267,
"text": "https://arne-mertz.de/2018/06/cmake-project-structure/: I like this one because it discusses how to integrate those header-only libraries, and uses Catch as an example."
},
{
"code": null,
"e": 8720,
"s": 8436,
"text": "https://rix0r.nl/blog/2015/08/13/cmake-guide/: I like this one because it shows in detail how to configure CMake and why, and also acknowledges the difference between library (which is easily unit tested) and application (which is the user interface, and not very easy to unit test)."
},
{
"code": null,
"e": 9133,
"s": 8720,
"text": "In this first stage (there is more on the second part of the article), I’m proposing a simplified folder structure. Projects having multiple executables and libraries need one folder per module, and the structure is much more complex. In this case, as there will be one single executable, I’m just having one root folder, called src and, in it, one folder for each type of file – sources, headers, and resources."
},
{
"code": null,
"e": 9694,
"s": 9133,
"text": ".gitignore <-- Ignore xcode, codeb, build folders.\n/src <----- All sources are here\n CMakeList.txt <-- The CMake configuration file.\n /cpp <----- Contains the C++ source files.\n /hpp <----- Contains the C++ header files.\n /res <----- Contains resource files.\n/build <----- Contains the temporary build files. \n Not under version control\n/xcode <----- Contains the XCode project.\n Not under version control.\n/codeb <----- Contains the Code::Blocks project. \n Not under version control. \n"
},
{
"code": null,
"e": 9947,
"s": 9694,
"text": "In this first step we build a very simple single-window application using CMake to configure the project and Gtk to display windows. Source code is available as master branch at: https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv. To retrieve it:"
},
{
"code": null,
"e": 10003,
"s": 9947,
"text": "This is the CMakeLists.txt that goes on the src folder:"
},
{
"code": null,
"e": 11271,
"s": 10003,
"text": "# src/CMakeLists.txt\ncmake_minimum_required(VERSION 3.3 FATAL_ERROR)\n\n# Project name and current version\nproject(rascam VERSION 0.1 LANGUAGES CXX)\n\n# Enable general warnings\n# See http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -Wall\")\n\n# Use 2014 C++ standard.\nset(CMAKE_CXX_STANDARD 14)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\n# Must use GNUInstallDirs to install libraries into correct locations on all platforms:\ninclude(GNUInstallDirs)\n\n# Pkg_config is used to locate headers and files for dependency libraries:\nfind_package(PkgConfig)\n\n# Defines variables GTKMM_INCLUDE_DIRS, GTKMM_LIBRARY_DIRS and GTKMM_LIBRARIES.\npkg_check_modules(GTKMM gtkmm-3.0)\n\n# Adds GTKMM_INCLUDE_DIRS, GTKMM_LIBRARY_DIRS to the list of folders the\n# compiler and linker will use to look for dependencies:\nlink_directories( ${GTKMM_LIBRARY_DIRS} )\ninclude_directories( ${GTKMM_INCLUDE_DIRS} )\n\n# Declares a new executable target called rascapp\n# and lists the files to compile for it:\nadd_executable(rascapp\n cpp/main.cpp \n cpp/main-window.cpp\n)\n\n# Adds the folder with all headers:\ntarget_include_directories(rascapp PRIVATE hpp)\n\n# Link files:\ntarget_link_libraries(rascapp\n ${GTKMM_LIBRARIES} \n)\n"
},
{
"code": null,
"e": 11309,
"s": 11271,
"text": "Let’s review the commands one by one:"
},
{
"code": null,
"e": 11519,
"s": 11309,
"text": "cmake_minimum_required requires a minimum version of CMake. This allows you do confidently use the features existing in the specified version, or show an explicit error message if installed version is too old."
},
{
"code": null,
"e": 11813,
"s": 11519,
"text": "project declares the name of the global project, rascam, specifies the current version and list the languages that we are using, namely C++. Historically, the extension for C++ was *.c++, but in some context there are problems with «+», so they switched to cpp or cxx. In CMake, CXX means C++."
},
{
"code": null,
"e": 11885,
"s": 11813,
"text": "set(CMAKE_CXX...) sets a few flags that are appropriate for modern C++."
},
{
"code": null,
"e": 11969,
"s": 11885,
"text": "find_package(PkgConfig) links to the pkg-config command, so we can use it later on."
},
{
"code": null,
"e": 12304,
"s": 11969,
"text": "pkg_check_modules(GTKMM gtkmm-3.0) does the same as executing pkg-config gtkmm-3.0 in the terminal (try it, if you wish), and then copies each section of the answer into variables prefixed with the specified GTKMM. Therefore, after this command we have three variables named GTKMM_LIBRARY_DIRS, GTKMM_INCLUDE_DIRS and GTKMM_LIBRARIES."
},
{
"code": null,
"e": 12759,
"s": 12304,
"text": "Then we declare a target. One project can have multiple targets. In general, targets comprise executables or libraries which are defined by calling add_executable or add_library and which can have many properties set (see distinction between a “target” and a “command”). As this is a single target project, it is perfectly convenient to define the target directly in the main CMakeLists.txt file. We list the source files to compile to create the target."
},
{
"code": null,
"e": 12877,
"s": 12759,
"text": "target_include_directories sets the list of folders where to look for the files referred in sources as include \"...\"."
},
{
"code": null,
"e": 13003,
"s": 12877,
"text": "target_link_libraries sets the list of libraries the linker (see about what do linkers do) has to link to complete the build."
},
{
"code": null,
"e": 13058,
"s": 13003,
"text": "In case you want to read more about compilation steps:"
},
{
"code": null,
"e": 13099,
"s": 13058,
"text": "How C++ Works: Understanding Compilation"
},
{
"code": null,
"e": 13163,
"s": 13099,
"text": "Stack Overflow – How does the compilation/linking process work?"
},
{
"code": null,
"e": 13371,
"s": 13163,
"text": "All C++ executables need a main method as entry point. To launch a GtK application, you need to specify a main window, which will act as a base for all other user interaction, including to open more windows."
},
{
"code": "#include \"main-window.hpp\" int main(int argc, char* argv[]){ auto app = Gtk::Application::create(argc, argv, \"raspberry-cpp-gtk-opencv\"); MainWindow mainWindow(300, 300); return app->run(mainWindow);}",
"e": 13659,
"s": 13371,
"text": null
},
{
"code": null,
"e": 13834,
"s": 13659,
"text": "Declaring a variable as auto specifies that the type of the variable that is being declared will be automatically deduced from its initialiser. This is called type inference."
},
{
"code": null,
"e": 14155,
"s": 13834,
"text": "The call to Gtk::Application::create initialises a new GtK execution context, passes the Program Arguments, and sets the application id (that can be anything, but convention says that it should contain your domain name in reverse, followed by its name, like in ch.agl-developpement.cpp-tutorial.raspberry-cpp-gtk-opencv)"
},
{
"code": null,
"e": 14429,
"s": 14155,
"text": "Once you have a context ready you can use it to open a window. The window that can be an instance of any class that extends Gtk::Window. In this case our main window is called quite explicitly mainWindow and it is an instance of class MainWindow, that we will define later."
},
{
"code": null,
"e": 15050,
"s": 14429,
"text": "The way we define (see the difference between define and declare) the mainWindow variable makes it an automatic variable (not same as auto type inference modifier seen before). Automatic variables are initialised and allocated in memory at the point of definition, and uninitialised and deallocated automatically when their scope is ended (read more about scope). On a local variable, this happens at the closing ‘}’ of their code block. We don’t need to care about deleting automatic variables (see, in contrast, Dynamic memory allocation with new and delete, or also dynamic memory allocation here at geeks for geeks)."
},
{
"code": null,
"e": 15305,
"s": 15050,
"text": "Whenever the type of variable is a class (as opposed to a basic type like int), the class constructor is called with the construction arguments and returns the initialised instance. In this case, construction arguments are the initial size of the window."
},
{
"code": null,
"e": 15446,
"s": 15305,
"text": "The call to run will return when the user closes the window. This gives to Gtk execution context the opportunity to control the exit status."
},
{
"code": null,
"e": 15590,
"s": 15446,
"text": "In Gtk, all buttons, labels, checkboxes and elements that displays or interacts with the user are called Widgets. Here is a gallery of Widgets."
},
{
"code": null,
"e": 15622,
"s": 15590,
"text": "Then, gtkmm adds its own sauce:"
},
{
"code": null,
"e": 16066,
"s": 15622,
"text": "gtkmm arranges widgets hierarchically, using containers. A Container widget contains other widgets. Most gtkmm widgets are containers. Windows, Notebook tabs, and Buttons are all container widgets. There are two flavors of containers: single-child containers, which are all descendants of Gtk::Bin, and multiple-child containers, which are descendants of Gtk::Container. Most widgets in gtkmm are descendants of Gtk::Bin, including Gtk::Window"
},
{
"code": null,
"e": 16100,
"s": 16066,
"text": "See Gtkmm official documentation."
},
{
"code": null,
"e": 16600,
"s": 16100,
"text": "class MainWindow : public Gtk::Window declares MainWindow as a class, and as descendant of, or inheriting from, Gtk::Window. The public modifier makes all public members of the ancestor to be also public members of the descendant. Public inheritance is the most usual way of extending a class (in contrast to private inheritance). We are providing MainWindow to the Gtk execution context, which is expecting all functionalities of a Gtk::Window to be available, so we avoid restricting their access."
},
{
"code": null,
"e": 17177,
"s": 16600,
"text": "As a descendant of Gtk::Window, MainWindow is a single-child container that can only contain one Gtk::Widget. I choose it to be a Gtk::Box, which is a Gtk::Container so, in turn, it is able to contain several widgets. In this occasion I want them to be one Gtk::Button and two Gtk::Label, to illustrate the Packing mechanism that GtK uses to stack together a bunch of controls. For MainWindow to respond to clicks on the button, we declare a buttonClick method (could be any other name, but keep them meaningful) — I’m explaining later how to connect the ‘click’ signal to it."
},
{
"code": "#ifndef MAIN_WINDOW_H#define MAIN_WINDOW_H #include <gtkmm.h> class MainWindow : public Gtk::Window {public: MainWindow(int width, int height); virtual ~MainWindow() = default; private: void buttonClick(); Gtk::Button m_button; Gtk::Box m_box; Gtk::Label m_label1, m_label2;}; #endif",
"e": 17483,
"s": 17177,
"text": null
},
{
"code": null,
"e": 17716,
"s": 17483,
"text": "The two first methods are the constructor and the destructor. As said before, a constructor is called every time we declare a new instance of this class. This constructor accepts initial width and height of the window as parameters."
},
{
"code": null,
"e": 17865,
"s": 17716,
"text": "Whenever an instance is destroyed, the class destructor is called to perform all needed clean up tasks. This destructor has two important modifiers:"
},
{
"code": null,
"e": 18100,
"s": 17865,
"text": "virtual means that, in case of inheritance, the method called will be that of the dynamic type. Read more about what is dynamic type of object, virtual functions, and why most of the time it is a good idea to have virtual destructors."
},
{
"code": null,
"e": 18509,
"s": 18100,
"text": "default means that we define this destructor to have a default implementation. The default implementation of a destructor is able to deallocate all defined members of the class, which are m_box, m_button, m_label1 and m_label2 (code>buttonClick is a method therefore it does not need allocation or deallocation). By specifying the default implementation, we spare ourselves the need to define the destructor."
},
{
"code": null,
"e": 18726,
"s": 18509,
"text": "The memory model of C++ has no garbage collector. Reserving and freeing memory is relies on the presence of class constructors and destructors and on a strategy called Resource Acquisition Is Initialisation, or RAII."
},
{
"code": null,
"e": 18855,
"s": 18726,
"text": "Declaration of MainWindow requires two further definitions – the class constructor and the buttonClick method. Here is the code:"
},
{
"code": "#include \"main-window.hpp\"#include <iostream> MainWindow::MainWindow(int witdh, int height) : m_button(\"Hello World\"), m_box(Gtk::ORIENTATION_VERTICAL), m_label1(\"First Label\"), m_label2(\"Second Label\"){ // Configure this window: this->set_default_size(witdh, height); // Connect the 'click' signal and make the button visible: m_button.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::buttonClick)); m_button.show(); // Make the first label visible: m_label1.show(); // Make the second label visible: m_label2.show(); // Pack all elements in the box: m_box.pack_start(m_button, Gtk::PACK_SHRINK); m_box.pack_start(m_label1, Gtk::PACK_SHRINK); m_box.pack_start(m_label2, Gtk::PACK_EXPAND_WIDGET); // Add the box in this window: add(m_box); // Make the box visible: m_box.show();} void MainWindow::buttonClick(){ std::cout << \"Hello World\" << std::endl;}",
"e": 19798,
"s": 18855,
"text": null
},
{
"code": null,
"e": 20156,
"s": 19798,
"text": "The full name of the constructor is MainWindow::MainWindow, meaning it is the function called MainWindow (the name of the constructor is the same as the class) that belongs to the class MainWindow. It takes width and height as parameters, and starts by calling the constructors of all declared members (read more about constructor member initialiser lists)."
},
{
"code": null,
"e": 20600,
"s": 20156,
"text": "Then we set the window’s default size by calling this->set_default_size. The this is a pointer to the current class instance. As it is a pointer, we use -> to access its members. As class MainWindow extends Gtk::Window, this instance contain all public or protected members of this class and those of the the parent class. This is called inheritance. The use of this pointer is actually optional, and the following snippet would also be valid:"
},
{
"code": null,
"e": 20602,
"s": 20600,
"text": "."
},
{
"code": null,
"e": 20688,
"s": 20602,
"text": "// Configure this window (now, without the 'this'):\nset_default_size(witdh, height);\n"
},
{
"code": null,
"e": 21165,
"s": 20688,
"text": "Next we want to react to the m_button being clicked. One way to achieve this is to connect a function to the click signal of the m_button instance (to see all available signals of a widget, you can check the official documentation, for example, the Gtk::Button has only the clicked signal). Connecting functions to widget’s signals allows to process the event from anywhere in the code, as long as you have access to the widget and you can provide the address of the function."
},
{
"code": null,
"e": 21234,
"s": 21165,
"text": "m_button.signal_clicked().connect([address of the method to call]);\n"
},
{
"code": null,
"e": 21632,
"s": 21234,
"text": "The address of the function could be as simple as placing the function’s name (see about the address of a function). Our case is more complex because the function we want to specify is a member of a class. Member functions need to be provided with the this pointer, so it can access other members of the same instance. To build the pointer to a method of a specific instance, we use sigc::mem_fun:"
},
{
"code": null,
"e": 21844,
"s": 21632,
"text": "sigc::mem_fun( // Convert member function to function pointer.\n *this, // The address of the instance.\n &MainWindow::buttonClick // The address of the method.\n);\n"
},
{
"code": null,
"e": 21992,
"s": 21844,
"text": "By default, widgets are not visible. We need to set their visibility explicitly by calling show(). We do this for all widgets, including the m_box."
},
{
"code": null,
"e": 22509,
"s": 21992,
"text": "Next, we pack all elements in the box. During initialisation we already set the box to Gtk::ORIENTATION_VERTICAL, which means that widgets will be positioned one below the other, using all available horizontal space. pack_start adds a new widget to the box, Gtk::PACK_SHRINK specifies that the widget’s vertical size should be as small as possible (Gtk::ORIENTATION_VERTICAL already specifies that all widgets in the box should have a width as big as possible, so the result will be widgets very wide and very flat.)"
},
{
"code": null,
"e": 22701,
"s": 22509,
"text": "In contrast, Gtk::PACK_EXPAND_WIDGET specifies that the widget should take all available space. This makes the m_label2 to expand when the user expands the window (you can test this shortly)."
},
{
"code": null,
"e": 22752,
"s": 22701,
"text": "The last step is to make the m_box itself visible."
},
{
"code": null,
"e": 22833,
"s": 22752,
"text": "As for the buttonClick method, we just display a message to the standard output."
},
{
"code": null,
"e": 23073,
"s": 22833,
"text": "Start by checking out the source code in some folder where you want place the project. Enter the checked out folder and create a xcode folder that will contain all working data for Xcode. Enter the working folder, create the Xcode project:"
},
{
"code": null,
"e": 23264,
"s": 23073,
"text": "$ cd go-to-your-working-folder\n$ git clone https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv.git\n$ cd raspberry-cpp-gtk-opencv\n$ mkdir xcode\n$ cd xcode\n$ cmake -G Xcode ../src\n$ make\n"
},
{
"code": null,
"e": 24006,
"s": 23264,
"text": "Now open Xcode, from the menu, do a File and Open and navigate for the xcode folder, and open one file called rascam.xcodeproj (notice that rascam is the name of the project specified in Cmake. The navigator shall open, showing one folder per target. Some of the targets, like ALL_BUILD and ZERO_CHECK are Xcode internals. There should be one target called rascapp, which is the name of the executable target in Cmake. You will find there your sources and headers. Open any one that you fancy, and place a break point. Then select the rascapp target in the non-descript drop list in the tool bar and, finally, play. If all is right, the application should execute. It is possible that the windows is not on top, so you don’t see it directly."
},
{
"code": null,
"e": 24080,
"s": 24006,
"text": "Clone the example project, configure it with debug symbols, and build it:"
},
{
"code": null,
"e": 24287,
"s": 24080,
"text": "$ cd go-to-your-working-folder\n$ git clone https://github.com/cpp-tutorial/raspberry-cpp-gtk-opencv.git\n$ cd raspberry-cpp-gtk-opencv\n$ mkdir build\n$ cd build\n$ cmake -DCMAKE_BUILD_TYPE=Debug ../src\n$ make\n"
},
{
"code": null,
"e": 24350,
"s": 24287,
"text": "To debug with gdb, assuming that you’re still in build folder:"
},
{
"code": null,
"e": 24843,
"s": 24350,
"text": "$ gdb ./rascapp\n[Now you're in gdb]\nb main-window.cpp:10 # Place a break-point on line 10 of this file.\nrun # Run the program. It will stop at the breakpoint.\nwhere # It will show the stack trace\nlist # It will show some context.\nprint width # Displays the value of this variable\nn # Step over\ns # Step into\nc # To continue the program\nq # Quit gdb \n"
},
{
"code": null,
"e": 25426,
"s": 24843,
"text": "This second step adds a couple of small improvements to the application. First one is to react to key events. As the application will be on the Raspberry Pi, and not always easily accessible via a mouse, it may be handy to have some keyboard shortcuts, in particular, to toggle full-size window or close application. The second improvement is to log events in the system log. Applications that run from command line can cout messages that are directly visible. However, if you launch your window application from a user desktop, you will not see the console, nor the result of cout."
},
{
"code": null,
"e": 25665,
"s": 25426,
"text": "As window application are usually launched from the desktop, the content produced via cout is not easily visible. Instead, you can submit syslog messages (see also a syslog example). It is quite easy to do, and works across all platforms."
},
{
"code": null,
"e": 25828,
"s": 25665,
"text": "In Linux (Ubuntu), you can see the system logs via the System Log application. In Mac OS X it is the Console application. In Windows you can use the Event viewer."
},
{
"code": null,
"e": 26094,
"s": 25828,
"text": "Another way to react to events is to override a specific function in the Widget, that is called whenever that event happens. For example, to react to keyboard events in the MainWindow we have to override the on_key_press_event method. To override a function in C++:"
},
{
"code": null,
"e": 26175,
"s": 26094,
"text": "The function has to be declared as virtual in one of the ancestors of our class."
},
{
"code": null,
"e": 26267,
"s": 26175,
"text": "We need to declare it again, in our class, with the exact same signature and accessibility."
},
{
"code": null,
"e": 26516,
"s": 26267,
"text": "We may add the override keyword on the function declaration, to acknowledge the fact that we’re overriding an existing method from a parent class. The compiler shows an error when we use override on a method that doesn’t exist or it is not virtual."
},
{
"code": null,
"e": 26580,
"s": 26516,
"text": "on_key_press_event is declared in class Gtk::Widget as follows:"
},
{
"code": null,
"e": 26709,
"s": 26580,
"text": "/// This is a default handler for the signal signal_key_press_event().\nvirtual bool on_key_press_event(GdkEventKey* key_event);\n"
},
{
"code": null,
"e": 26761,
"s": 26709,
"text": "In consequence, we have to re-declare it our class."
},
{
"code": "#ifndef MAIN_WINDOW_H#define MAIN_WINDOW_H #include <gtkmm.h> #include \"camera-drawing-area.hpp\" class MainWindow : public Gtk::Window {public: MainWindow(int width, int height); virtual ~MainWindow() = default; protected: bool on_key_press_event(GdkEventKey* event) override; private: void buttonClick(); bool probablyInFullScreen; Gtk::Button m_button; Gtk::Box m_box; Gtk::Label m_label1; CameraDrawingArea cameraDrawingArea;}; #endif",
"e": 27232,
"s": 26761,
"text": null
},
{
"code": null,
"e": 27831,
"s": 27232,
"text": "The Widget where the event is originated is the first to receive it on its on_xx_xxx_event() event handler. If it returns true, the event is considered handled and nothing more is done about it. On the contrary, if the handler cannot do anything about the event, it returns false making the event to be offered to the same handler of its parent widget, and parent’s parent, and so on (see about event propagation in the official documentation). The default implementation of handlers like on_key_press_event is to do nothing but returning false, so events are propagated unless otherwise specified."
},
{
"code": null,
"e": 27942,
"s": 27831,
"text": "[Ctrl] + [C] exits the application, [F] or [f] toggle the full screen mode, and [esc] turns the full mode off:"
},
{
"code": "#include \"main-window.hpp\"#include <syslog.h> MainWindow::MainWindow(int witdh, int height) : probablyInFullScreen(false), m_button(\"Hello World\"), m_box(Gtk::ORIENTATION_VERTICAL), m_label1(\"First Label\"){ // Configure this window: this->set_default_size(witdh, height); // Connect the 'click' signal and make the button visible: m_button.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::buttonClick)); m_button.show(); // Make the first label visible: m_label1.show(); // Make the second label visible: cameraDrawingArea.show(); // Pack all elements in the box: m_box.pack_start(m_button, Gtk::PACK_SHRINK); m_box.pack_start(m_label1, Gtk::PACK_SHRINK); m_box.pack_start(cameraDrawingArea, Gtk::PACK_EXPAND_WIDGET); // Add the box in this window: add(m_box); // Make the box visible: m_box.show(); // Activate Key-Press events add_events(Gdk::KEY_PRESS_MASK);} void MainWindow::buttonClick(){ syslog(LOG_NOTICE, \"Hello world!\");} bool MainWindow::on_key_press_event(GdkEventKey* event){ switch (event->keyval) { // Ctrl + C: Ends the app: case GDK_KEY_C: case GDK_KEY_c: if ((event->state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK) { get_application()->quit(); } return true; // [F] toggles fullscreen mode: case GDK_KEY_F: case GDK_KEY_f: if (probablyInFullScreen) { unfullscreen(); probablyInFullScreen = false; } else { fullscreen(); probablyInFullScreen = true; } return true; // [esc] exits fullscreen mode: case GDK_KEY_Escape: unfullscreen(); probablyInFullScreen = false; return true; } return false;}",
"e": 29721,
"s": 27942,
"text": null
},
{
"code": null,
"e": 29836,
"s": 29721,
"text": "By default, the events are not captured. add_events(Gdk::KEY_PRESS_MASK) activates the capture of keyboard events."
},
{
"code": null,
"e": 30351,
"s": 29836,
"text": "The functions to toggle full screen are fullscreen() and unfullscreen(), both belong to the Gtk::Window class (here we’re omitting the this pointer). The documentation warns that you shouldn’t assume the window is definitely full screen afterward, because other entities (e.g. the user or window manager) could toggle it on or off again, and not all window managers honor those requests. That’s why we have added a probablyInFullScreen status, that conveys the possibility that window is not in the expected state."
},
{
"code": null,
"e": 30589,
"s": 30351,
"text": "To exit the application we are not directly calling exit(), instead we use get_application()->quit() to tell the Gtk execution context to call exit. It will, eventually, but first it is going to close all windows and open devices for us."
},
{
"code": null,
"e": 30837,
"s": 30589,
"text": "To capture images we’re using OpenCV. If you just want to capture an image from the camera, you could use other libraries, but the final objective is to apply computer vision algorithms to the captured image. Hence, OpenCV is the best alternative."
},
{
"code": null,
"e": 31025,
"s": 30837,
"text": "For security reasons, Mac OS X forces applications to request user’s permission before using the camera. The procedure for this is to include a Info.plist file with the necessary content:"
},
{
"code": null,
"e": 31075,
"s": 31025,
"text": "Some indications about version number and author."
},
{
"code": null,
"e": 31306,
"s": 31075,
"text": "A key NSCameraUsageDescription with the description on why your application needs the camera. The message you write here is displayed to the user, who has to accept it. If he doesn’t accept, the system terminates your application."
},
{
"code": null,
"e": 31568,
"s": 31306,
"text": "The procedure is to include a MacOSXBundleInfo.plist.in file, which is a template; some of the entries can be governed by properties in the CMakeLists.txt file, and others you can put yourself. The file is placed in src/res folder and has the following content:"
},
{
"code": null,
"e": 33018,
"s": 31568,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \n \"-//Apple Computer//DTD PLIST 1.0//EN\" \n \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>CFBundleDevelopmentRegion</key>\n <string>English</string>\n <key>CFBundleExecutable</key>\n <string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>\n <key>CFBundleGetInfoString</key>\n <string>${MACOSX_BUNDLE_INFO_STRING}</string>\n <key>CFBundleIconFile</key>\n <string>${MACOSX_BUNDLE_ICON_FILE}</string>\n <key>CFBundleIdentifier</key>\n <string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>\n <key>CFBundleInfoDictionaryVersion</key>\n <string>6.0</string>\n <key>CFBundleLongVersionString</key>\n <string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>\n <key>CFBundleName</key>\n <string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>\n <key>CFBundlePackageType</key>\n <string>APPL</string>\n <key>CFBundleShortVersionString</key>\n <string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>\n <key>CFBundleSignature</key>\n <string>????</string>\n <key>CFBundleVersion</key>\n <string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>\n <key>CSResourcesFileMapped</key>\n <true/>\n <key>NSHumanReadableCopyright</key>\n <string>${MACOSX_BUNDLE_COPYRIGHT}</string>\n <key>NSCameraUsageDescription</key>\n <string>This app requires to access your camera to retrieve images and perform the demo</string>\n</dict>\n</plist>\n"
},
{
"code": null,
"e": 33101,
"s": 33018,
"text": "These are some of the resources I used to found out how to do bundles in Mac OS X:"
},
{
"code": null,
"e": 33168,
"s": 33101,
"text": "An official documentation, quite old, about Bundles-And-Frameworks"
},
{
"code": null,
"e": 33202,
"s": 33168,
"text": "The original Info.plist template."
},
{
"code": null,
"e": 33309,
"s": 33202,
"text": "After installing OpenCV following the previous instructions, you can link your application to it in CMake."
},
{
"code": null,
"e": 35370,
"s": 33309,
"text": "# src/CMakeLists.txt\ncmake_minimum_required(VERSION 3.3 FATAL_ERROR)\n\n# Project name and current version\nproject(rascam VERSION 0.1 LANGUAGES CXX)\n\n# Enable general warnings\n# See http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -Wall\")\n\n# Use 2014 C++ standard.\nset(CMAKE_CXX_STANDARD 14)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\n# Must use GNUInstallDirs to install libraries into correct locations on all platforms:\ninclude(GNUInstallDirs)\n\n# Pkg_config is used to locate header and files for dependency libraries:\nfind_package(PkgConfig)\n\n# Defines variables GTKMM_INCLUDE_DIRS, GTKMM_LIBRARY_DIRS and GTKMM_LIBRARIES.\npkg_check_modules(GTKMM gtkmm-3.0) \nlink_directories( ${GTKMM_LIBRARY_DIRS} )\ninclude_directories( ${GTKMM_INCLUDE_DIRS} )\n\n# OpenCV can be linked in a more standard manner:\nfind_package( OpenCV REQUIRED )\n\n# Compile files:\nadd_executable(rascapp\n cpp/main.cpp\n cpp/main-window.cpp\n cpp/camera-drawing-area.cpp\n)\n\n# Add folder with all headers:\ntarget_include_directories(rascapp PRIVATE hpp)\n\n# Link files:\ntarget_link_libraries(rascapp\n ${GTKMM_LIBRARIES}\n ${OpenCV_LIBS}\n)\n\n# Apple requires a bundle to add a Info.plist file that contains the required\n# permissions to access some restricted resources like the camera:\nif (APPLE)\n set_target_properties(rascapp PROPERTIES\n MACOSX_BUNDLE TRUE\n MACOSX_FRAMEWORK_IDENTIFIER org.cmake.ExecutableTarget\n MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/res/MacOSXBundleInfo.plist.in\n \n # This property is required:\n MACOSX_BUNDLE_GUI_IDENTIFIER \"rascapp-${PROJECT_VERSION}\"\n \n # Those properties are not required:\n MACOSX_BUNDLE_INFO_STRING \"rascapp ${PROJECT_VERSION}, by [email protected]\"\n MACOSX_BUNDLE_LONG_VERSION_STRING ${PROJECT_VERSION}\n MACOSX_BUNDLE_BUNDLE_NAME \"rascapp\"\n MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION}\n MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}\n )\nendif()\n"
},
{
"code": null,
"e": 35589,
"s": 35370,
"text": "Gtk::DrawingArea is a widget that holds a graphic area to display custom drawings or bitmaps. We define a CameraDrawingArea that extends this widget, and copies the image captured from the camera into the graphic area:"
},
{
"code": "#ifndef CAMERA_DRAWING_AREA_H#define CAMERA_DRAWING_AREA_H #include <gtkmm.h>#include <opencv2/highgui.hpp> class CameraDrawingArea : public Gtk::DrawingArea {public: CameraDrawingArea(); virtual ~CameraDrawingArea(); protected: bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override; void on_size_allocate(Gtk::Allocation& allocation) override; bool everyNowAndThen(); private: sigc::connection everyNowAndThenConnection; cv::VideoCapture videoCapture; cv::Mat webcam; cv::Mat output; int width, height;};#endif",
"e": 36146,
"s": 35589,
"text": null
},
{
"code": null,
"e": 36212,
"s": 36146,
"text": "We’re going to extend this class and override two of its methods:"
},
{
"code": null,
"e": 36456,
"s": 36212,
"text": "void on_size_allocate(Gtk::Allocation& allocation) – This method is called every time the size of the widget changes. This happens the very first time it is displayed, and every time some action of the user or the system makes the size change."
},
{
"code": null,
"e": 36781,
"s": 36456,
"text": "bool on_draw(const Cairo::RefPtr& cr) – This method is called every time the area, or part of the area, contained in the widget has to be redrawn. It receives a reference to a Cairo context. The method can use it to render any drawing or graphic. In our case we’re going to use it to copy the image captured from the camera."
},
{
"code": null,
"e": 36978,
"s": 36781,
"text": "The cv::Mat is a class that contains a OpenCV image. We’re using two of those: one contains the image captured from the camera, and the other contains the image resized to the Widget current size."
},
{
"code": null,
"e": 37032,
"s": 36978,
"text": "The width and height contain the current Widget size."
},
{
"code": null,
"e": 37085,
"s": 37032,
"text": "VideoCapture is a OpenCV access to the video camera."
},
{
"code": null,
"e": 37253,
"s": 37085,
"text": "everyNowAndThenConnection is a way to call everyNowAndThen() method at regular time intervals, similarly as we set the response to the button click, in previous steps."
},
{
"code": null,
"e": 37265,
"s": 37253,
"text": "This is the"
},
{
"code": "#include \"opencv2/core.hpp\"#include \"opencv2/highgui.hpp\"#include \"opencv2/imgproc.hpp\" #include \"camera-drawing-area.hpp\" CameraDrawingArea::CameraDrawingArea() : videoCapture(0){ // Lets refresh drawing area very now and then. everyNowAndThenConnection = Glib::signal_timeout().connect(sigc::mem_fun(*this, &CameraDrawingArea::everyNowAndThen), 100);} CameraDrawingArea::~CameraDrawingArea(){ everyNowAndThenConnection.disconnect();} /** * Every now and then, we invalidate the whole Widget rectangle, * forcing a complete refresh. */bool CameraDrawingArea::everyNowAndThen(){ auto win = get_window(); if (win) { Gdk::Rectangle r(0, 0, width, height); win->invalidate_rect(r, false); } // Don't stop calling me: return true;} /** * Called every time the widget has its allocation changed. */void CameraDrawingArea::on_size_allocate(Gtk::Allocation& allocation){ // Call the parent to do whatever needs to be done: DrawingArea::on_size_allocate(allocation); // Remember the new allocated size for resizing operation: width = allocation.get_width(); height = allocation.get_height();} /** * Called every time the widget needs to be redrawn. * This happens when the Widget got resized, or obscured by * another object, or every now and then. */bool CameraDrawingArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr){ // Prevent the drawing if size is 0: if (width == 0 || height == 0) { return true; } // Capture one image from camera: videoCapture.read(webcam); // Resize it to the allocated size of the Widget. resize(webcam, output, cv::Size(width, height), 0, 0, cv::INTER_LINEAR); // Initializes a pixbuf sharing the same data as the mat: Glib::RefPtr<Gdk::Pixbuf> pixbuf = Gdk::Pixbuf::create_from_data( (guint8*)output.data, Gdk::COLORSPACE_RGB, false, 8, output.cols, output.rows, (int)output.step); // Display Gdk::Cairo::set_source_pixbuf(cr, pixbuf); cr->paint(); // Don't stop calling me. return true;}",
"e": 39356,
"s": 37265,
"text": null
},
{
"code": null,
"e": 39612,
"s": 39356,
"text": "In the constructor we start by initialising videoConstructor to the default device. Then we set up a connection to call the everyNowAndThen method every 100ms (10 x per second). Later we call the connection to disconnect it during the destruction process."
},
{
"code": null,
"e": 39737,
"s": 39612,
"text": "The everyNowAndThen() method invalidates the whole area of the widget. This is an indirect way to provoke a call to on_draw."
},
{
"code": null,
"e": 39919,
"s": 39737,
"text": "on_size_allocate keeps track of the current size of the Widget. Just in case the parent class did implement something important in its own implementation, we call the parent method."
},
{
"code": null,
"e": 40080,
"s": 39919,
"text": "Everything we put in place before is so on_draw is called regularly, and we can use the reference to Cairo::Context to paste the image captured from the camera:"
},
{
"code": null,
"e": 40280,
"s": 40080,
"text": "First we check that the current width and height are not zero. This may happen during startup phase. Calling resize with a 0 dimension would terminate instantly the application so we better avoid it."
},
{
"code": null,
"e": 40536,
"s": 40280,
"text": "videoCapture.read(webcam) copies the captured image into the provided cv::Mat, in this case webcam. If the provided material is not initialised, or it is not of the appropriate size, then the method will perform necessary tasks, and reserve needed memory."
},
{
"code": null,
"e": 40883,
"s": 40536,
"text": "resize copies the image from source (webcam) to destination (output), changing its size. If the destination is not initialised or not of the right size it performs necessary tasks and memory reservation. To keep the variable in scope, we also declared it as a class property: first call will initialise the variable, next calls can just reuse it."
},
{
"code": null,
"e": 41151,
"s": 40883,
"text": "Both webcam and output are class properties so they keep in scope as long as the class instance does. They will need to be initialised only during the first call to on_draw but will keep their values across the subsequent calls. This helps noticeably the performance."
},
{
"code": null,
"e": 41363,
"s": 41151,
"text": "create_from_data creates a new Gdk::Pixbuf object, which contains an image in a format compatible with Cairo. The long list of parameters are to be taken as a recipe to convert OpenCV‘s Material to Gtk‘s Pixbuf."
},
{
"code": null,
"e": 41434,
"s": 41363,
"text": "set_source_pixbuf sets the bitmap source to use for next call to paint"
},
{
"code": null,
"e": 41468,
"s": 41434,
"text": "Finally, paint does the painting."
},
{
"code": null,
"e": 41589,
"s": 41468,
"text": "The last step is to place the widget we just created in the main window. We need to declare it in the MainWindow header:"
},
{
"code": "#ifndef MAIN_WINDOW_H#define MAIN_WINDOW_H #include <gtkmm.h> #include \"camera-drawing-area.hpp\" class MainWindow : public Gtk::Window {public: MainWindow(int width, int height); virtual ~MainWindow() = default; protected: bool on_key_press_event(GdkEventKey* event) override; private: void buttonClick(); bool probablyInFullScreen; Gtk::Button m_button; Gtk::Box m_box; Gtk::Label m_label1; CameraDrawingArea cameraDrawingArea;}; #endif",
"e": 42060,
"s": 41589,
"text": null
},
{
"code": null,
"e": 42123,
"s": 42060,
"text": "And place it in the box, just the same as a label or a button:"
},
{
"code": "#include <syslog.h>#include <unistd.h> #include \"main-window.hpp\" MainWindow::MainWindow(int width, int height) : probablyInFullScreen(false), m_button(\"Hello World\"), m_box(Gtk::ORIENTATION_VERTICAL), m_label1(\"First Label\"){ // Configure this window: this->set_default_size(width, height); // Connect the 'click' signal and make the button visible: m_button.signal_clicked().connect( sigc::mem_fun(*this, &MainWindow::buttonClick)); m_button.show(); // Make the first label visible: m_label1.show(); // Make the second label visible: cameraDrawingArea.show(); // Pack all elements in the box: m_box.pack_start(m_button, Gtk::PACK_SHRINK); m_box.pack_start(m_label1, Gtk::PACK_SHRINK); m_box.pack_start(cameraDrawingArea, Gtk::PACK_EXPAND_WIDGET); // Add the box in this window: add(m_box); // Make the box visible: m_box.show(); // Activate Key-Press events add_events(Gdk::KEY_PRESS_MASK);} void MainWindow::buttonClick(){ syslog(LOG_NOTICE, \"User %d says 'Hello World'\", getuid());} bool MainWindow::on_key_press_event(GdkEventKey* event){ switch (event->keyval) { // Ctrl + C: Ends the app: case GDK_KEY_C: case GDK_KEY_c: if ((event->state & GDK_CONTROL_MASK) == GDK_CONTROL_MASK) { get_application()->quit(); } return true; // [F] toggles fullscreen mode: case GDK_KEY_F: case GDK_KEY_f: if (probablyInFullScreen) { unfullscreen(); probablyInFullScreen = false; } else { fullscreen(); probablyInFullScreen = true; } return true; // [esc] exits fullscreen mode: case GDK_KEY_Escape: unfullscreen(); probablyInFullScreen = false; return true; } return false;}",
"e": 43947,
"s": 42123,
"text": null
},
{
"code": null,
"e": 44018,
"s": 43947,
"text": "Last but not least, you need to install the project on a Raspberry Pi."
},
{
"code": null,
"e": 44064,
"s": 44018,
"text": "The easiest way is to do it from the desktop:"
},
{
"code": null,
"e": 49831,
"s": 44064,
"text": "Raspberry –> PreferencesOpen Interfaces tab.Enable the CameraTo check that the camera works, type:$ raspistill -f -t 0\nYou should be able to see images from camera. Exit with Ctrl+C.Driver v4L2In Raspberry, the v4L2 driver offers the standard interface to the camera that OpenCV needs to capture images. The driver is installed by default, but not active. To activate it:$ sudo modprobe bcm2835-v4l2\n$ ls /dev/video0\nIf the device /dev/vide0 is present, it means that the driver is active. To activate it by default when the Raspberry starts, edit file /etc/modules and add the following snippet at the bottom:bcm2835-v4l2\nInstall toolingTo be able to download and build the project, you need the same tooling as in your development platform: Git, Cmake, pkg-config and the libraries Gtk and OpenCV. To install them, follow the procedure for the Linux environment, in this same article.AutorunYou may want Raspberry Pi to launch your application at startup. The easiest way I found to auto-run a GUI application in Raspberry is to create a desktop file in the autostart directory. In a brand new installation, this directory doesn’t exist and you need to create it:$ mkdir ~/.config/autostart\n$ vim ~/.config/autostart/rascapp.desktop\nThe content of “rascapp.desktop“ should be similar to:[Desktop Entry]\nName=raspberry-pi-camera-display\nExec=/home/pi/raspberry-cpp-gtk-opencv/build/rascapp\nPath=/home/pi\nType=application\nThe Path key is the root folder for the application, when accessing files by a relative path.See more about syntax here: See original explanation here: Avoid console blankingConsole blanking affects you if you’re using ssh to execute commands. If for some time, you don’t type anythingin the console, it will close.To avoid it, edit file /boot/cmdline.txt and append the parameter consoleblank=0See original explanation here: https://www.raspberrypi.org/documentation/configuration/screensaver.mdAvoid idle screenDisplay-only applications, will typically have no user interaction, so screen may go idle leaving you in the dark. To prevent this, the simplest approach is to install a screen saver and then configure it to NOT run:$ sudo apt-get install xscreensaver\nAfter this, screensaver application is in Preferences, in desktop menu. Use the appropriate options to prevent screen saver.Enabling composite video outIf you’re placing the Raspberry on board of some mobile device with a FPV transmitter, you probably want to use the Analog Video Out. Edit the /boot/config.txt file and modify the entries as following:...\nsdtv_mode=2\n...\nhdmi_force_hotplug=0\n...\nWhen hdmi_force_hotplug is set to 1, the system assumes that there is a HDMI device present, soit never activates video composite output.When hdmi_force_hotplug is set to 0, the system will use composite video unless it detects HDMI device. So,Raspberry will still use the HDMI monitor if it is connected during boot sequence.See more about this:Original article: Force Raspberry Pi output to composite video instead of HDMIOfficial doc: Configure composite videoMore official: Configuring the Raspberry PiTroubleshootingI hope you don’t need this section.Gtk-ERROR **: GTK+ 2.x symbols detected.If you get this error message:Gtk-ERROR **: GTK+ 2.x symbols detected. \nUsing GTK+ 2.x and GTK+ 3 in the same process is not \nsupported\nYou may accidentally linked OpenCV with Gtk2. As this project uses Gtk3, there is a conflict. You need to be sure that OpenCV is linked with Gtk3.Start by uninstalling Gtk2 and ensuring Gtk3 is present:$ sudo apt-get remove libgtk2.0-dev\nsudo apt-get install libgtk-3-dev\nsudo apt-get auto-remove\nsudo apt-get install libgtkmm-3.0-dev\nBuild again OpenCV:If you haven’t done this yet, then remove the build directory of OpenCV.Start again the building procedure as described above BUT...Before launching make, check the cmake log, and verify the Gtk version is linked with. Look for something like this:...\n-- GUI: \n-- GTK+: YES (ver 3.22.11)\n-- GThread : YES (ver 2.50.3)\n-- GtkGlExt: NO\n-- VTK support: NO\n...\nConclusionThis example is a working proof of concept on how write a cross-platform application based on two very popular libraries, OpenCV for processing computer vision and Gtk for user interface. However, there are a list of shortcomings that need to be addressed before you can use it as a base for the more complex application that you may have in mind:The more visible one is that the image is deformed to match the size of the window. This can be easily solved using a more sophisticated algorithm to calculate a size that would fit in the window but keep the original aspect ratio.A second one, very annoying if you plan a First Person View application is the perceptible lag between real life and the images stream. Lag seems variable depending on the camera and the light conditions. The reason is cameras having an image buffer; as we are retrieving one image every now and then, we’re always consuming the oldest image in the buffer. To solve this we should let the capture process drive the window refresh, instead of using a timer.Code has a general lack of decoupling that makes everything very dependent on everything else. This defect isn’t very present in such a simple application, but it will show as soon as we try to solve the lag problem. Also, part of the code should be a pure OpenCV process that you could copy/paste from some other blog, without needing to adapt it to the CameraDrawingArea that is dependent on both OpenCV and Gtk libraries.Finally, you should be able to unit test the OpenCV processing to increase the type-compile-debug cycle.My next article covers those topics.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 49856,
"s": 49831,
"text": "Raspberry –> Preferences"
},
{
"code": null,
"e": 49877,
"s": 49856,
"text": "Open Interfaces tab."
},
{
"code": null,
"e": 49895,
"s": 49877,
"text": "Enable the Camera"
},
{
"code": null,
"e": 49933,
"s": 49895,
"text": "To check that the camera works, type:"
},
{
"code": null,
"e": 49955,
"s": 49933,
"text": "$ raspistill -f -t 0\n"
},
{
"code": null,
"e": 50019,
"s": 49955,
"text": "You should be able to see images from camera. Exit with Ctrl+C."
},
{
"code": null,
"e": 50198,
"s": 50019,
"text": "In Raspberry, the v4L2 driver offers the standard interface to the camera that OpenCV needs to capture images. The driver is installed by default, but not active. To activate it:"
},
{
"code": null,
"e": 50245,
"s": 50198,
"text": "$ sudo modprobe bcm2835-v4l2\n$ ls /dev/video0\n"
},
{
"code": null,
"e": 50439,
"s": 50245,
"text": "If the device /dev/vide0 is present, it means that the driver is active. To activate it by default when the Raspberry starts, edit file /etc/modules and add the following snippet at the bottom:"
},
{
"code": null,
"e": 50453,
"s": 50439,
"text": "bcm2835-v4l2\n"
},
{
"code": null,
"e": 50702,
"s": 50453,
"text": "To be able to download and build the project, you need the same tooling as in your development platform: Git, Cmake, pkg-config and the libraries Gtk and OpenCV. To install them, follow the procedure for the Linux environment, in this same article."
},
{
"code": null,
"e": 50975,
"s": 50702,
"text": "You may want Raspberry Pi to launch your application at startup. The easiest way I found to auto-run a GUI application in Raspberry is to create a desktop file in the autostart directory. In a brand new installation, this directory doesn’t exist and you need to create it:"
},
{
"code": null,
"e": 51046,
"s": 50975,
"text": "$ mkdir ~/.config/autostart\n$ vim ~/.config/autostart/rascapp.desktop\n"
},
{
"code": null,
"e": 51101,
"s": 51046,
"text": "The content of “rascapp.desktop“ should be similar to:"
},
{
"code": null,
"e": 51235,
"s": 51101,
"text": "[Desktop Entry]\nName=raspberry-pi-camera-display\nExec=/home/pi/raspberry-cpp-gtk-opencv/build/rascapp\nPath=/home/pi\nType=application\n"
},
{
"code": null,
"e": 51329,
"s": 51235,
"text": "The Path key is the root folder for the application, when accessing files by a relative path."
},
{
"code": null,
"e": 51358,
"s": 51329,
"text": "See more about syntax here: "
},
{
"code": null,
"e": 51390,
"s": 51358,
"text": "See original explanation here: "
},
{
"code": null,
"e": 51532,
"s": 51390,
"text": "Console blanking affects you if you’re using ssh to execute commands. If for some time, you don’t type anythingin the console, it will close."
},
{
"code": null,
"e": 51613,
"s": 51532,
"text": "To avoid it, edit file /boot/cmdline.txt and append the parameter consoleblank=0"
},
{
"code": null,
"e": 51715,
"s": 51613,
"text": "See original explanation here: https://www.raspberrypi.org/documentation/configuration/screensaver.md"
},
{
"code": null,
"e": 51932,
"s": 51715,
"text": "Display-only applications, will typically have no user interaction, so screen may go idle leaving you in the dark. To prevent this, the simplest approach is to install a screen saver and then configure it to NOT run:"
},
{
"code": null,
"e": 51969,
"s": 51932,
"text": "$ sudo apt-get install xscreensaver\n"
},
{
"code": null,
"e": 52094,
"s": 51969,
"text": "After this, screensaver application is in Preferences, in desktop menu. Use the appropriate options to prevent screen saver."
},
{
"code": null,
"e": 52296,
"s": 52094,
"text": "If you’re placing the Raspberry on board of some mobile device with a FPV transmitter, you probably want to use the Analog Video Out. Edit the /boot/config.txt file and modify the entries as following:"
},
{
"code": null,
"e": 52342,
"s": 52296,
"text": "...\nsdtv_mode=2\n...\nhdmi_force_hotplug=0\n...\n"
},
{
"code": null,
"e": 52480,
"s": 52342,
"text": "When hdmi_force_hotplug is set to 1, the system assumes that there is a HDMI device present, soit never activates video composite output."
},
{
"code": null,
"e": 52670,
"s": 52480,
"text": "When hdmi_force_hotplug is set to 0, the system will use composite video unless it detects HDMI device. So,Raspberry will still use the HDMI monitor if it is connected during boot sequence."
},
{
"code": null,
"e": 52691,
"s": 52670,
"text": "See more about this:"
},
{
"code": null,
"e": 52770,
"s": 52691,
"text": "Original article: Force Raspberry Pi output to composite video instead of HDMI"
},
{
"code": null,
"e": 52810,
"s": 52770,
"text": "Official doc: Configure composite video"
},
{
"code": null,
"e": 52854,
"s": 52810,
"text": "More official: Configuring the Raspberry Pi"
},
{
"code": null,
"e": 52890,
"s": 52854,
"text": "I hope you don’t need this section."
},
{
"code": null,
"e": 52921,
"s": 52890,
"text": "If you get this error message:"
},
{
"code": null,
"e": 53028,
"s": 52921,
"text": "Gtk-ERROR **: GTK+ 2.x symbols detected. \nUsing GTK+ 2.x and GTK+ 3 in the same process is not \nsupported\n"
},
{
"code": null,
"e": 53175,
"s": 53028,
"text": "You may accidentally linked OpenCV with Gtk2. As this project uses Gtk3, there is a conflict. You need to be sure that OpenCV is linked with Gtk3."
},
{
"code": null,
"e": 53232,
"s": 53175,
"text": "Start by uninstalling Gtk2 and ensuring Gtk3 is present:"
},
{
"code": null,
"e": 53366,
"s": 53232,
"text": "$ sudo apt-get remove libgtk2.0-dev\nsudo apt-get install libgtk-3-dev\nsudo apt-get auto-remove\nsudo apt-get install libgtkmm-3.0-dev\n"
},
{
"code": null,
"e": 53386,
"s": 53366,
"text": "Build again OpenCV:"
},
{
"code": null,
"e": 53459,
"s": 53386,
"text": "If you haven’t done this yet, then remove the build directory of OpenCV."
},
{
"code": null,
"e": 53520,
"s": 53459,
"text": "Start again the building procedure as described above BUT..."
},
{
"code": null,
"e": 53637,
"s": 53520,
"text": "Before launching make, check the cmake log, and verify the Gtk version is linked with. Look for something like this:"
},
{
"code": null,
"e": 53842,
"s": 53637,
"text": "...\n-- GUI: \n-- GTK+: YES (ver 3.22.11)\n-- GThread : YES (ver 2.50.3)\n-- GtkGlExt: NO\n-- VTK support: NO\n...\n"
},
{
"code": null,
"e": 54190,
"s": 53842,
"text": "This example is a working proof of concept on how write a cross-platform application based on two very popular libraries, OpenCV for processing computer vision and Gtk for user interface. However, there are a list of shortcomings that need to be addressed before you can use it as a base for the more complex application that you may have in mind:"
},
{
"code": null,
"e": 54422,
"s": 54190,
"text": "The more visible one is that the image is deformed to match the size of the window. This can be easily solved using a more sophisticated algorithm to calculate a size that would fit in the window but keep the original aspect ratio."
},
{
"code": null,
"e": 54879,
"s": 54422,
"text": "A second one, very annoying if you plan a First Person View application is the perceptible lag between real life and the images stream. Lag seems variable depending on the camera and the light conditions. The reason is cameras having an image buffer; as we are retrieving one image every now and then, we’re always consuming the oldest image in the buffer. To solve this we should let the capture process drive the window refresh, instead of using a timer."
},
{
"code": null,
"e": 55304,
"s": 54879,
"text": "Code has a general lack of decoupling that makes everything very dependent on everything else. This defect isn’t very present in such a simple application, but it will show as soon as we try to solve the lag problem. Also, part of the code should be a pure OpenCV process that you could copy/paste from some other blog, without needing to adapt it to the CameraDrawingArea that is dependent on both OpenCV and Gtk libraries."
},
{
"code": null,
"e": 55409,
"s": 55304,
"text": "Finally, you should be able to unit test the OpenCV processing to increase the type-compile-debug cycle."
},
{
"code": null,
"e": 55446,
"s": 55409,
"text": "My next article covers those topics."
},
{
"code": null,
"e": 55459,
"s": 55446,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 55468,
"s": 55459,
"text": "rkbhola5"
},
{
"code": null,
"e": 55477,
"s": 55468,
"text": "Articles"
},
{
"code": null,
"e": 55481,
"s": 55477,
"text": "C++"
},
{
"code": null,
"e": 55487,
"s": 55481,
"text": "GBlog"
},
{
"code": null,
"e": 55495,
"s": 55487,
"text": "Project"
},
{
"code": null,
"e": 55499,
"s": 55495,
"text": "CPP"
}
]
|
Python | Pandas series.str.get() | 20 Nov, 2019
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 str.get() method is used to get element at the passed position. This method works for string, numeric values and even lists throughout the series. .str has to be prefixed every time to differentiate it from Python’s default get() method.
Syntax: Series.str.get(i)
Parameters:i : Position of element to be extracted, Integer values only.
Return type: Series with element/character at passed position
To download the CSV used in code, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Getting character from string value
In this example, str.get() method is used to get a single character from the Name column. The null values have been removed using dropna() method and the series is converted to string type series using .astype() before applying this method. This method can be used to get one character instead of whole string. For example, getting M from Male and F from Female since there can be two inputs only, so doing this can save data.
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # converting to string seriesdata["Name"]= data["Name"].astype(str) # creating new column with element at 0th position in data["Team"]data["New"]= data["Name"].str.get(0) data# display
Output:As shown in the output image, the New column is having first letter of the string in Name column. Example #2: Getting elements from series of List
In this example, the Team column has been split at every occurrence of ” ” (Whitespace), into a list using str.split() method. Then the same column is overwritten with it. After that str.get() method is used to get elements in list at passed index.
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # converting to string seriesdata["Team"]= data["Team"].astype(str) # splitting at occurrence of whitespacedata["Team"]= data["Team"].str.split(" ", 1) # displaying first element from listdata["Team"].str.get(0) # displaying second element from listdata["Team"].str.get(1)
Output:As shown in the output images, The first image is of Elements at 0th position in series and the second image is of elements at 1st position in the series.
Output 1: data["Team"].str.get(0) Output 2: data["Team"].str.get(1)
nidhi_biet
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Nov, 2019"
},
{
"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": 511,
"s": 266,
"text": "Pandas str.get() method is used to get element at the passed position. This method works for string, numeric values and even lists throughout the series. .str has to be prefixed every time to differentiate it from Python’s default get() method."
},
{
"code": null,
"e": 537,
"s": 511,
"text": "Syntax: Series.str.get(i)"
},
{
"code": null,
"e": 610,
"s": 537,
"text": "Parameters:i : Position of element to be extracted, Integer values only."
},
{
"code": null,
"e": 672,
"s": 610,
"text": "Return type: Series with element/character at passed position"
},
{
"code": null,
"e": 718,
"s": 672,
"text": "To download the CSV used in code, click here."
},
{
"code": null,
"e": 865,
"s": 718,
"text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below."
},
{
"code": null,
"e": 913,
"s": 865,
"text": "Example #1: Getting character from string value"
},
{
"code": null,
"e": 1340,
"s": 913,
"text": "In this example, str.get() method is used to get a single character from the Name column. The null values have been removed using dropna() method and the series is converted to string type series using .astype() before applying this method. This method can be used to get one character instead of whole string. For example, getting M from Male and F from Female since there can be two inputs only, so doing this can save data."
},
{
"code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # converting to string seriesdata[\"Name\"]= data[\"Name\"].astype(str) # creating new column with element at 0th position in data[\"Team\"]data[\"New\"]= data[\"Name\"].str.get(0) data# display",
"e": 1759,
"s": 1340,
"text": null
},
{
"code": null,
"e": 1913,
"s": 1759,
"text": "Output:As shown in the output image, the New column is having first letter of the string in Name column. Example #2: Getting elements from series of List"
},
{
"code": null,
"e": 2162,
"s": 1913,
"text": "In this example, the Team column has been split at every occurrence of ” ” (Whitespace), into a list using str.split() method. Then the same column is overwritten with it. After that str.get() method is used to get elements in list at passed index."
},
{
"code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # converting to string seriesdata[\"Team\"]= data[\"Team\"].astype(str) # splitting at occurrence of whitespacedata[\"Team\"]= data[\"Team\"].str.split(\" \", 1) # displaying first element from listdata[\"Team\"].str.get(0) # displaying second element from listdata[\"Team\"].str.get(1)",
"e": 2670,
"s": 2162,
"text": null
},
{
"code": null,
"e": 2832,
"s": 2670,
"text": "Output:As shown in the output images, The first image is of Elements at 0th position in series and the second image is of elements at 1st position in the series."
},
{
"code": null,
"e": 2900,
"s": 2832,
"text": "Output 1: data[\"Team\"].str.get(0) Output 2: data[\"Team\"].str.get(1)"
},
{
"code": null,
"e": 2911,
"s": 2900,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2932,
"s": 2911,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2961,
"s": 2932,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2975,
"s": 2961,
"text": "Python-pandas"
},
{
"code": null,
"e": 2982,
"s": 2975,
"text": "Python"
},
{
"code": null,
"e": 3080,
"s": 2982,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3112,
"s": 3080,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3139,
"s": 3112,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3160,
"s": 3139,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3183,
"s": 3160,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3214,
"s": 3183,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3270,
"s": 3214,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3312,
"s": 3270,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3354,
"s": 3312,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3393,
"s": 3354,
"text": "Python | Get unique values from a list"
}
]
|
Word Wrap | Practice | GeeksforGeeks | Given an array nums[] of size n, where nums[i] denotes the number of characters in one word. Let K be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.
Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line except the last one.
You have to minimize the following total cost where total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)2.
Example 1:
Input: nums = {3,2,2,5}, k = 6
Output: 10
Explanation: Given a line can have 6
characters,
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 3
Line number 3: From word no. 4 to 4
So total cost = (6-3)2 + (6-2-2-1)2 = 32+12 = 10.
As in the first line word length = 3 thus
extra spaces = 6 - 3 = 3 and in the second line
there are two word of length 2 and there already
1 space between two word thus extra spaces
= 6 - 2 -2 -1 = 1. As mentioned in the problem
description there will be no extra spaces in
the last line. Placing first and second word
in first line and third word on second line
would take a cost of 02 + 42 = 16 (zero spaces
on first line and 6-2 = 4 spaces on second),
which isn't the minimum possible cost.
Example 2:
Input: nums = {3,2,2}, k = 4
Output: 5
Explanation: Given a line can have 4
characters,
Line number 1: From word no. 1 to 1
Line number 2: From word no. 2 to 2
Line number 3: From word no. 3 to 3
Same explaination as above total cost
= (4 - 3)2 + (4 - 2)2 = 5.
Your Task:
You don't need to read or print anyhting. Your task is to complete the function solveWordWrap() which takes nums and k as input paramater and returns the minimized total cost.
Expected Time Complexity: O(n2)
Expected Space Complexity: O(n)
Constraints:
1 ≤ n ≤ 500
1 ≤ nums[i] ≤ 1000
max(nums[i]) ≤ k ≤ 2000
+1
jindalpraval7912 days ago
int dp[505][2005];
int solve(int index, int remaining, vector<int> &nums, int &k)
{
//Base Case: at last we will ignore the spaces so here we pay 0 cost
if(index == nums.size()) return 0;
// if we already had calculated then simply return it
if(dp[index][remaining] != -1) return dp[index][remaining];
int ans;
// when we don't have choices bcoz if we fill nums[index] here then
// it will disobey the limit so we here we seperate line and go to new line
if(nums[index] > remaining)
{
// our 'remaining' exclude a space seperator but
// if this is last then we have to count that space in 'remaining' as well
ans = (remaining + 1) * (remaining + 1) ;
// k - nums[index] -1 = 'remaining',
// when we fill next line by nums[index] and a space
ans += solve(index + 1, k - nums[index] - 1, nums, k);
}
// Otherwise we have 2 choices
else
{
// either we fill next word into new line
int choice1 = (remaining + 1) * (remaining + 1) + solve(index + 1, k - nums[index] - 1, nums, k);
// or we fill in same line
int choice2 = solve(index + 1, remaining - nums[index] - 1, nums, k);
// we have to minimize the answer
ans = min(choice1,choice2);
}
dp[index][remaining] = ans;
return dp[index][remaining] ;
}
public:
int solveWordWrap(vector<int>nums, int k)
{
// Code here
memset(dp,-1,sizeof dp);
return solve(0,k, nums , k);
}
0
sushovansaha3 days ago
Memoization and Tabulation:
#include <bits/stdc++.h>
using namespace std;
int square(int n)
{
return n * n;
}
int solve(vector<int> words, int n, int k, int idx, int remL, vector<vector<int>> &dp)
{
// base case for last word
if (idx == n - 1)
{
return words[idx] < remL ? 0 : square(remL);
}
if (dp[idx][remL] != -1)
{
return dp[idx][remL];
}
int cur = words[idx];
// if word can fit in the remaining line
if (cur < remL)
{
int len = (remL == k) ? (remL - cur) : (remL - cur - 1);
return dp[idx][remL] = min(solve(words, n, k, idx + 1, len, dp), square(remL) + solve(words, n, k, idx + 1, k - cur, dp));
}
else
{
// if word is kept on next line
return dp[idx][remL] = square(remL) + solve(words, n, k, idx + 1, k - cur, dp);
}
}
int solveWordWrap(vector<int> nums, int k)
{
int n = nums.size();
vector<vector<int>> dp(n + 1, vector<int>(k + 1, -1));
return solve(nums, n, k, 0, k, dp);
}
int solveWordWrap(vector<int> nums, int k)
{
int n = nums.size();
vector<vector<int>> dp(n + 1, vector<int>(k + 1, 0));
for (int i = n; i >= 0; i--)
{
for (int j = 0; j <= k; j++)
{
if (i == n)
{
dp[i][j] = nums[i - 1] < j ? 0 : square(j);
}
else
{
int cur = nums[i - 1];
// if word can fit in the remaining line
if (cur < j)
{
int len = (j == k) ? (j - cur) : (j - cur - 1);
dp[i][j] = min(dp[i + 1][len], square(j) + dp[i + 1][k - cur]);
}
else
{
// if word is kept on next line
dp[i][j] = square(j) + dp[i + 1][k - cur];
}
}
}
}
return dp[0][k];
}
+1
ruchitchudasama1236 days ago
public:
int dp[505][2005];
int solve(int ind,int rem,vector<int> &nums,int k){
if(ind==nums.size())return 0;
if(dp[ind][rem]!=-1)return dp[ind][rem];
// int cost;
if(nums[ind]>rem){
return dp[ind][rem]=pow(rem+1,2)+solve(ind+1,k-nums[ind]-1,nums,k);
}
int choice1=solve(ind+1,rem-nums[ind]-1,nums,k);
int choice2=pow(rem+1,2)+solve(ind+1,k-nums[ind]-1,nums,k);
return dp[ind][rem]=min(choice1,choice2);
}
int solveWordWrap(vector<int>nums, int k)
{
int n=nums.size();
memset(dp,-1,sizeof dp);
return solve(0,k,nums,k);
}
0
aakashyadav101ay6 days ago
int solve(int ind, int rem, vector<int>& nums, int k, vector<vector<int>> &dp){ if(ind == nums.size()){ return 0; } if(dp[ind][rem] != -1){ return dp[ind][rem]; } int cost = pow(rem, 2); // if there is not enough space for 2nd word
if(rem <= nums[ind]){ // adding the cost bz putting the 2nd word in next line
return dp[ind][rem] = cost + solve(ind+1, k-nums[ind], nums, k, dp); } // there is space left for next word // either putting the word in the same line or in the next to reduce cost
return dp[ind][rem] = min(cost+ solve(ind+1, k-nums[ind],nums, k, dp ), solve(ind+1, rem-nums[ind]-1, nums, k, dp)); } int solveWordWrap(vector<int>nums, int k) { vector<vector<int>> dp(nums.size(), vector<int> (k+1, -1)); return solve(1, k-nums[0],nums, k, dp); }
+1
msa27041 week ago
class Solution {
int help(vector<int>& nums, int i, int left, int k, vector<vector<int>>& memo){
if(i==nums.size()){
return 0;
}
if(memo[i][left]!=-1) return memo[i][left];
int cost=pow(left,2);
if(left<=nums[i]) return memo[i][left]=cost+help(nums,i+1,k-nums[i],k,memo);
return memo[i][left]=min(cost+help(nums,i+1,k-nums[i],k,memo),help(nums,i+1,left-nums[i]-1,k,memo));
}
public:
int solveWordWrap(vector<int>nums, int k)
{
// Code here
vector<vector<int>> memo(nums.size(),vector<int>(k+1,-1));
return help(nums,1,k-nums[0],k,memo);
}
0
mrunaldeoles971 week ago
Need help in figuring out bug.
This it the solution I came up with.
class Solution
{
public int solveWordWrap (int[] nums, int k)
{
return solveWordWrap(0,nums,k);
}
private int solveWordWrap(int startIndx, int[] nums, int k){
if(startIndx >= nums.length-1)
return 0;
int min = Integer.MAX_VALUE;
int charCount = 0;
int words = 0;
for(int i = startIndx; i < nums.length; i++){
charCount = charCount + nums[i];
words++;
if(charCount+words-1 <= k)
min = Math.min( (int)Math.pow(k - (charCount+ words-1),2) + solveWordWrap(i+1,nums,k),min);
else
break;
}
return min;
}
}
For the input
nums = {10,6,5,3,1,10,8,2}
k = 12
The correct solution is 45, but my code is outputting 46.
0
rahulmahotra2 weeks ago
CODE ERROR OR PLATFORM ERROR?
If i declare my dp array globally then answer code is giving correct output but if i pass it by reference, 0 is being printed.
Can someone tell what is wrong.
int f(vector<int>& nums, int k, int i, int rem, vector<vector<int>>& dp){
if(i == nums.size()) return 0;
if(dp[i][rem] != -1) return dp[i][rem];
if(nums[i] > rem){
return dp[i][rem] = pow(rem+1, 2) +
f(nums, k, i+1, k-nums[i]-1, dp);
}
int ch1 = pow(rem+1, 2) + f(nums, k, i+1, k-nums[i]-1, dp);
int ch2 = f(nums, k, i+1, rem-nums[i]-1, dp);
return dp[i][rem] = min(ch1, ch2);
}
int solveWordWrap(vector<int> nums, int k)
{
vector<vector<int>> dp(nums.size()+1, vector<int>(k+1, -1));
return f(nums, k, 0, k, dp);
}
Globally, giving correct output
int dp[505][2005];
int f(vector<int>& nums, int k, int i, int rem){
if(i == nums.size()) return 0;
if(dp[i][rem] != -1) return dp[i][rem];
if(nums[i] > rem){
return dp[i][rem] = pow(rem+1, 2) +
f(nums, k, i+1, k-nums[i]-1);
}
int ch1 = pow(rem+1, 2) + f(nums, k, i+1, k-nums[i]-1);
int ch2 = f(nums, k, i+1, rem-nums[i]-1);
return dp[i][rem] = min(ch1, ch2);
}
int solveWordWrap(vector<int> nums, int k)
{
memset(dp, -1, sizeof dp);
return f(nums, k, 0, k);
}
0
shashankpal1909
This comment was deleted.
0
ksheeragrawal3 weeks ago
class Solution {public: int solveWordWrap(vector<int>nums, int k) { int n=nums.size(); int dp[n+1]; dp[n]=0; dp[n-1]=0; if(n==1){return 0;} for(int i=n-2;i>=0;i=i-1) { int curr=nums[i]; dp[i]=dp[i+1]+(k-nums[i])*(k-nums[i]); int aja=1; while(aja<n-i) { curr=curr+nums[i+aja]+1; if(curr<=k) { if(i+aja==n-1){dp[i]=0;} else{dp[i]=min(dp[i],(k-curr)*(k-curr)+dp[i+aja+1]);} } else{break;} aja=aja+1; } } return dp[0]; } };
0
sidheshwarsaravanan3 weeks ago
Python solution [DP]
Top down recursive DP
class Solution:
def solveWordWrap(self, nums, k):
n = len(nums)
dp = [[-1] * (k+1) for _ in range(n+1)]
def recurse(index, cur_limit):
if index == n:
return 0
if dp[index][cur_limit] != -1:
return dp[index][cur_limit]
if nums[index] <= cur_limit:
take = recurse(index + 1, cur_limit - nums[index] - 1)
not_take = (cur_limit + 1) * (cur_limit + 1) + recurse(index + 1, k - nums[index] - 1)
dp[index][cur_limit] = min(take, not_take)
else:
not_take = (cur_limit + 1) * (cur_limit + 1) + recurse(index + 1, k - nums[index] - 1)
dp[index][cur_limit] = not_take
return dp[index][cur_limit]
return recurse(0, k)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 746,
"s": 238,
"text": "Given an array nums[] of size n, where nums[i] denotes the number of characters in one word. Let K be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly.\nAssume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line. The extra spaces include spaces put at the end of every line except the last one. "
},
{
"code": null,
"e": 900,
"s": 746,
"text": "You have to minimize the following total cost where total cost = Sum of cost of all lines, where cost of line is = (Number of extra spaces in the line)2."
},
{
"code": null,
"e": 911,
"s": 900,
"text": "Example 1:"
},
{
"code": null,
"e": 1655,
"s": 911,
"text": "Input: nums = {3,2,2,5}, k = 6\nOutput: 10\nExplanation: Given a line can have 6\ncharacters,\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 3\nLine number 3: From word no. 4 to 4\nSo total cost = (6-3)2 + (6-2-2-1)2 = 32+12 = 10.\nAs in the first line word length = 3 thus\nextra spaces = 6 - 3 = 3 and in the second line\nthere are two word of length 2 and there already\n1 space between two word thus extra spaces\n= 6 - 2 -2 -1 = 1. As mentioned in the problem\ndescription there will be no extra spaces in\nthe last line. Placing first and second word\nin first line and third word on second line\nwould take a cost of 02 + 42 = 16 (zero spaces\non first line and 6-2 = 4 spaces on second),\nwhich isn't the minimum possible cost.\n"
},
{
"code": null,
"e": 1666,
"s": 1655,
"text": "Example 2:"
},
{
"code": null,
"e": 1929,
"s": 1666,
"text": "Input: nums = {3,2,2}, k = 4\nOutput: 5\nExplanation: Given a line can have 4 \ncharacters,\nLine number 1: From word no. 1 to 1\nLine number 2: From word no. 2 to 2\nLine number 3: From word no. 3 to 3\nSame explaination as above total cost\n= (4 - 3)2 + (4 - 2)2 = 5.\n"
},
{
"code": null,
"e": 2119,
"s": 1929,
"text": "\nYour Task:\nYou don't need to read or print anyhting. Your task is to complete the function solveWordWrap() which takes nums and k as input paramater and returns the minimized total cost.\n "
},
{
"code": null,
"e": 2185,
"s": 2119,
"text": "Expected Time Complexity: O(n2)\nExpected Space Complexity: O(n)\n "
},
{
"code": null,
"e": 2253,
"s": 2185,
"text": "Constraints:\n1 ≤ n ≤ 500\n1 ≤ nums[i] ≤ 1000\nmax(nums[i]) ≤ k ≤ 2000"
},
{
"code": null,
"e": 2256,
"s": 2253,
"text": "+1"
},
{
"code": null,
"e": 2282,
"s": 2256,
"text": "jindalpraval7912 days ago"
},
{
"code": null,
"e": 3936,
"s": 2282,
"text": "int dp[505][2005];\n int solve(int index, int remaining, vector<int> &nums, int &k)\n {\n //Base Case: at last we will ignore the spaces so here we pay 0 cost\n if(index == nums.size()) return 0;\n // if we already had calculated then simply return it\n if(dp[index][remaining] != -1) return dp[index][remaining];\n \n int ans;\n // when we don't have choices bcoz if we fill nums[index] here then \n // it will disobey the limit so we here we seperate line and go to new line\n if(nums[index] > remaining)\n {\n // our 'remaining' exclude a space seperator but \n // if this is last then we have to count that space in 'remaining' as well\n ans = (remaining + 1) * (remaining + 1) ;\n // k - nums[index] -1 = 'remaining',\n // when we fill next line by nums[index] and a space\n ans += solve(index + 1, k - nums[index] - 1, nums, k);\n }\n // Otherwise we have 2 choices\n else\n {\n // either we fill next word into new line\n int choice1 = (remaining + 1) * (remaining + 1) + solve(index + 1, k - nums[index] - 1, nums, k); \n // or we fill in same line\n int choice2 = solve(index + 1, remaining - nums[index] - 1, nums, k);\n // we have to minimize the answer\n ans = min(choice1,choice2);\n }\n dp[index][remaining] = ans;\n return dp[index][remaining] ;\n }\npublic:\n int solveWordWrap(vector<int>nums, int k) \n { \n // Code here\n memset(dp,-1,sizeof dp);\n return solve(0,k, nums , k);\n } "
},
{
"code": null,
"e": 3938,
"s": 3936,
"text": "0"
},
{
"code": null,
"e": 3961,
"s": 3938,
"text": "sushovansaha3 days ago"
},
{
"code": null,
"e": 3989,
"s": 3961,
"text": "Memoization and Tabulation:"
},
{
"code": null,
"e": 5881,
"s": 3989,
"text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint square(int n)\n{\n return n * n;\n}\n\nint solve(vector<int> words, int n, int k, int idx, int remL, vector<vector<int>> &dp)\n{\n // base case for last word\n if (idx == n - 1)\n {\n return words[idx] < remL ? 0 : square(remL);\n }\n\n if (dp[idx][remL] != -1)\n {\n return dp[idx][remL];\n }\n\n int cur = words[idx];\n // if word can fit in the remaining line\n if (cur < remL)\n {\n int len = (remL == k) ? (remL - cur) : (remL - cur - 1);\n return dp[idx][remL] = min(solve(words, n, k, idx + 1, len, dp), square(remL) + solve(words, n, k, idx + 1, k - cur, dp));\n }\n else\n {\n // if word is kept on next line\n return dp[idx][remL] = square(remL) + solve(words, n, k, idx + 1, k - cur, dp);\n }\n}\n\nint solveWordWrap(vector<int> nums, int k)\n{\n int n = nums.size();\n\n vector<vector<int>> dp(n + 1, vector<int>(k + 1, -1));\n\n return solve(nums, n, k, 0, k, dp);\n}\n\nint solveWordWrap(vector<int> nums, int k)\n{\n int n = nums.size();\n\n vector<vector<int>> dp(n + 1, vector<int>(k + 1, 0));\n\n for (int i = n; i >= 0; i--)\n {\n for (int j = 0; j <= k; j++)\n {\n if (i == n)\n {\n dp[i][j] = nums[i - 1] < j ? 0 : square(j);\n }\n else\n {\n int cur = nums[i - 1];\n // if word can fit in the remaining line\n if (cur < j)\n {\n int len = (j == k) ? (j - cur) : (j - cur - 1);\n dp[i][j] = min(dp[i + 1][len], square(j) + dp[i + 1][k - cur]);\n }\n else\n {\n // if word is kept on next line\n dp[i][j] = square(j) + dp[i + 1][k - cur];\n }\n }\n }\n }\n\n return dp[0][k];\n}"
},
{
"code": null,
"e": 5884,
"s": 5881,
"text": "+1"
},
{
"code": null,
"e": 5913,
"s": 5884,
"text": "ruchitchudasama1236 days ago"
},
{
"code": null,
"e": 6610,
"s": 5913,
"text": "public:\nint dp[505][2005];\n int solve(int ind,int rem,vector<int> &nums,int k){\n if(ind==nums.size())return 0;\n \n if(dp[ind][rem]!=-1)return dp[ind][rem];\n \n // int cost;\n if(nums[ind]>rem){\n return dp[ind][rem]=pow(rem+1,2)+solve(ind+1,k-nums[ind]-1,nums,k);\n }\n \n \n int choice1=solve(ind+1,rem-nums[ind]-1,nums,k);\n \n int choice2=pow(rem+1,2)+solve(ind+1,k-nums[ind]-1,nums,k);\n \n return dp[ind][rem]=min(choice1,choice2);\n }\n int solveWordWrap(vector<int>nums, int k) \n { \n int n=nums.size();\n memset(dp,-1,sizeof dp);\n return solve(0,k,nums,k);\n }"
},
{
"code": null,
"e": 6612,
"s": 6610,
"text": "0"
},
{
"code": null,
"e": 6639,
"s": 6612,
"text": "aakashyadav101ay6 days ago"
},
{
"code": null,
"e": 6934,
"s": 6639,
"text": "int solve(int ind, int rem, vector<int>& nums, int k, vector<vector<int>> &dp){ if(ind == nums.size()){ return 0; } if(dp[ind][rem] != -1){ return dp[ind][rem]; } int cost = pow(rem, 2); // if there is not enough space for 2nd word"
},
{
"code": null,
"e": 7030,
"s": 6934,
"text": " if(rem <= nums[ind]){ // adding the cost bz putting the 2nd word in next line "
},
{
"code": null,
"e": 7245,
"s": 7030,
"text": " return dp[ind][rem] = cost + solve(ind+1, k-nums[ind], nums, k, dp); } // there is space left for next word // either putting the word in the same line or in the next to reduce cost"
},
{
"code": null,
"e": 7584,
"s": 7245,
"text": " return dp[ind][rem] = min(cost+ solve(ind+1, k-nums[ind],nums, k, dp ), solve(ind+1, rem-nums[ind]-1, nums, k, dp)); } int solveWordWrap(vector<int>nums, int k) { vector<vector<int>> dp(nums.size(), vector<int> (k+1, -1)); return solve(1, k-nums[0],nums, k, dp); }"
},
{
"code": null,
"e": 7587,
"s": 7584,
"text": "+1"
},
{
"code": null,
"e": 7605,
"s": 7587,
"text": "msa27041 week ago"
},
{
"code": null,
"e": 8253,
"s": 7605,
"text": "class Solution {\n int help(vector<int>& nums, int i, int left, int k, vector<vector<int>>& memo){\n if(i==nums.size()){\n return 0;\n }\n if(memo[i][left]!=-1) return \t\tmemo[i][left];\n int cost=pow(left,2);\n if(left<=nums[i]) return memo[i][left]=cost+help(nums,i+1,k-nums[i],k,memo);\n return memo[i][left]=min(cost+help(nums,i+1,k-nums[i],k,memo),help(nums,i+1,left-nums[i]-1,k,memo));\n }\npublic:\n int solveWordWrap(vector<int>nums, int k) \n { \n // Code here\n vector<vector<int>> memo(nums.size(),vector<int>(k+1,-1));\n return help(nums,1,k-nums[0],k,memo);\n } "
},
{
"code": null,
"e": 8255,
"s": 8253,
"text": "0"
},
{
"code": null,
"e": 8280,
"s": 8255,
"text": "mrunaldeoles971 week ago"
},
{
"code": null,
"e": 8311,
"s": 8280,
"text": "Need help in figuring out bug."
},
{
"code": null,
"e": 8350,
"s": 8313,
"text": "This it the solution I came up with."
},
{
"code": null,
"e": 9068,
"s": 8350,
"text": "class Solution\n{\n public int solveWordWrap (int[] nums, int k)\n {\n return solveWordWrap(0,nums,k);\n }\n \n private int solveWordWrap(int startIndx, int[] nums, int k){\n \n if(startIndx >= nums.length-1)\n return 0;\n \n int min = Integer.MAX_VALUE;\n \n int charCount = 0;\n int words = 0;\n for(int i = startIndx; i < nums.length; i++){\n charCount = charCount + nums[i];\n words++;\n if(charCount+words-1 <= k)\n min = Math.min( (int)Math.pow(k - (charCount+ words-1),2) + solveWordWrap(i+1,nums,k),min);\n else\n break;\n }\n \n return min;\n }\n}\n"
},
{
"code": null,
"e": 9082,
"s": 9068,
"text": "For the input"
},
{
"code": null,
"e": 9116,
"s": 9082,
"text": "nums = {10,6,5,3,1,10,8,2}\nk = 12"
},
{
"code": null,
"e": 9174,
"s": 9116,
"text": "The correct solution is 45, but my code is outputting 46."
},
{
"code": null,
"e": 9176,
"s": 9174,
"text": "0"
},
{
"code": null,
"e": 9200,
"s": 9176,
"text": "rahulmahotra2 weeks ago"
},
{
"code": null,
"e": 9230,
"s": 9200,
"text": "CODE ERROR OR PLATFORM ERROR?"
},
{
"code": null,
"e": 9357,
"s": 9230,
"text": "If i declare my dp array globally then answer code is giving correct output but if i pass it by reference, 0 is being printed."
},
{
"code": null,
"e": 9389,
"s": 9357,
"text": "Can someone tell what is wrong."
},
{
"code": null,
"e": 10133,
"s": 9389,
"text": "\n int f(vector<int>& nums, int k, int i, int rem, vector<vector<int>>& dp){\n \n if(i == nums.size()) return 0;\n \n if(dp[i][rem] != -1) return dp[i][rem];\n \n if(nums[i] > rem){\n \n return dp[i][rem] = pow(rem+1, 2) + \n f(nums, k, i+1, k-nums[i]-1, dp);\n \n }\n \n int ch1 = pow(rem+1, 2) + f(nums, k, i+1, k-nums[i]-1, dp);\n int ch2 = f(nums, k, i+1, rem-nums[i]-1, dp);\n \n return dp[i][rem] = min(ch1, ch2);\n \n }\n \n int solveWordWrap(vector<int> nums, int k) \n { \n vector<vector<int>> dp(nums.size()+1, vector<int>(k+1, -1));\n return f(nums, k, 0, k, dp);\n } \n"
},
{
"code": null,
"e": 10165,
"s": 10133,
"text": "Globally, giving correct output"
},
{
"code": null,
"e": 10851,
"s": 10165,
"text": "\nint dp[505][2005];\n int f(vector<int>& nums, int k, int i, int rem){\n \n if(i == nums.size()) return 0;\n \n if(dp[i][rem] != -1) return dp[i][rem];\n \n if(nums[i] > rem){\n \n return dp[i][rem] = pow(rem+1, 2) + \n f(nums, k, i+1, k-nums[i]-1);\n \n }\n \n int ch1 = pow(rem+1, 2) + f(nums, k, i+1, k-nums[i]-1);\n int ch2 = f(nums, k, i+1, rem-nums[i]-1);\n \n return dp[i][rem] = min(ch1, ch2);\n \n }\n \n int solveWordWrap(vector<int> nums, int k) \n {\n memset(dp, -1, sizeof dp);\n return f(nums, k, 0, k);\n } "
},
{
"code": null,
"e": 10853,
"s": 10851,
"text": "0"
},
{
"code": null,
"e": 10869,
"s": 10853,
"text": "shashankpal1909"
},
{
"code": null,
"e": 10895,
"s": 10869,
"text": "This comment was deleted."
},
{
"code": null,
"e": 10897,
"s": 10895,
"text": "0"
},
{
"code": null,
"e": 10922,
"s": 10897,
"text": "ksheeragrawal3 weeks ago"
},
{
"code": null,
"e": 11551,
"s": 10922,
"text": "class Solution {public: int solveWordWrap(vector<int>nums, int k) { int n=nums.size(); int dp[n+1]; dp[n]=0; dp[n-1]=0; if(n==1){return 0;} for(int i=n-2;i>=0;i=i-1) { int curr=nums[i]; dp[i]=dp[i+1]+(k-nums[i])*(k-nums[i]); int aja=1; while(aja<n-i) { curr=curr+nums[i+aja]+1; if(curr<=k) { if(i+aja==n-1){dp[i]=0;} else{dp[i]=min(dp[i],(k-curr)*(k-curr)+dp[i+aja+1]);} } else{break;} aja=aja+1; } } return dp[0]; } };"
},
{
"code": null,
"e": 11553,
"s": 11551,
"text": "0"
},
{
"code": null,
"e": 11584,
"s": 11553,
"text": "sidheshwarsaravanan3 weeks ago"
},
{
"code": null,
"e": 11605,
"s": 11584,
"text": "Python solution [DP]"
},
{
"code": null,
"e": 11628,
"s": 11605,
"text": "Top down recursive DP "
},
{
"code": null,
"e": 12422,
"s": 11628,
"text": "class Solution:\ndef solveWordWrap(self, nums, k):\n n = len(nums)\n dp = [[-1] * (k+1) for _ in range(n+1)]\n def recurse(index, cur_limit):\n if index == n:\n return 0\n if dp[index][cur_limit] != -1:\n return dp[index][cur_limit]\n if nums[index] <= cur_limit:\n take = recurse(index + 1, cur_limit - nums[index] - 1)\n not_take = (cur_limit + 1) * (cur_limit + 1) + recurse(index + 1, k - nums[index] - 1)\n dp[index][cur_limit] = min(take, not_take)\n else:\n not_take = (cur_limit + 1) * (cur_limit + 1) + recurse(index + 1, k - nums[index] - 1)\n dp[index][cur_limit] = not_take\n return dp[index][cur_limit]\n return recurse(0, k)"
},
{
"code": null,
"e": 12574,
"s": 12428,
"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": 12610,
"s": 12574,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 12620,
"s": 12610,
"text": "\nProblem\n"
},
{
"code": null,
"e": 12630,
"s": 12620,
"text": "\nContest\n"
},
{
"code": null,
"e": 12693,
"s": 12630,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 12878,
"s": 12693,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 13162,
"s": 12878,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 13308,
"s": 13162,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 13385,
"s": 13308,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 13426,
"s": 13385,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 13454,
"s": 13426,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 13525,
"s": 13454,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 13712,
"s": 13525,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
]
|
HTML DOM createObjectURL() method | 14 Jul, 2020
The createObjectURL() method creates a DOMString containing a URL representing the object given in the parameter of the method. The new object URL represents the specified File object or Blob object.
Note: The URL lifetime is tied to the document in which it was created.
Syntax:
const url = URL.createObjectURL(object);
Parameters:
object: A File, image, or any other MediaSource object for which object URL is to be created.
Return value: A DOMString containing an object URL of that object.
Example: In this example, we will create an object URL for the image object using this method.
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>URL.createObjectURL example</title></head><body> <h1>GeeksforGeeks</h1> <input type="file"> <img> <p class="p">The URL of this image is : </p></body><script> var Element = document.querySelector('input'); var img = document.querySelector('img'); Element.addEventListener('change', function() { var url = URL.createObjectURL(Element.files[0]); img.src = url; console.log(url); var d=document.querySelector(".p"); d.textContent+=url;});</script></html>
Output: we will select an image from local storage and then the URL of that object will be created.
Before Choosing Image:
After Choosing Image:
Checking the created URL in a new tab:
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
HTML-DOM
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
HTTP headers | Content-Type
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 254,
"s": 54,
"text": "The createObjectURL() method creates a DOMString containing a URL representing the object given in the parameter of the method. The new object URL represents the specified File object or Blob object."
},
{
"code": null,
"e": 326,
"s": 254,
"text": "Note: The URL lifetime is tied to the document in which it was created."
},
{
"code": null,
"e": 334,
"s": 326,
"text": "Syntax:"
},
{
"code": null,
"e": 375,
"s": 334,
"text": "const url = URL.createObjectURL(object);"
},
{
"code": null,
"e": 387,
"s": 375,
"text": "Parameters:"
},
{
"code": null,
"e": 481,
"s": 387,
"text": "object: A File, image, or any other MediaSource object for which object URL is to be created."
},
{
"code": null,
"e": 548,
"s": 481,
"text": "Return value: A DOMString containing an object URL of that object."
},
{
"code": null,
"e": 643,
"s": 548,
"text": "Example: In this example, we will create an object URL for the image object using this method."
},
{
"code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <title>URL.createObjectURL example</title></head><body> <h1>GeeksforGeeks</h1> <input type=\"file\"> <img> <p class=\"p\">The URL of this image is : </p></body><script> var Element = document.querySelector('input'); var img = document.querySelector('img'); Element.addEventListener('change', function() { var url = URL.createObjectURL(Element.files[0]); img.src = url; console.log(url); var d=document.querySelector(\".p\"); d.textContent+=url;});</script></html>",
"e": 1192,
"s": 643,
"text": null
},
{
"code": null,
"e": 1292,
"s": 1192,
"text": "Output: we will select an image from local storage and then the URL of that object will be created."
},
{
"code": null,
"e": 1315,
"s": 1292,
"text": "Before Choosing Image:"
},
{
"code": null,
"e": 1337,
"s": 1315,
"text": "After Choosing Image:"
},
{
"code": null,
"e": 1376,
"s": 1337,
"text": "Checking the created URL in a new tab:"
},
{
"code": null,
"e": 1396,
"s": 1376,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 1410,
"s": 1396,
"text": "Google Chrome"
},
{
"code": null,
"e": 1415,
"s": 1410,
"text": "Edge"
},
{
"code": null,
"e": 1423,
"s": 1415,
"text": "Firefox"
},
{
"code": null,
"e": 1430,
"s": 1423,
"text": "Safari"
},
{
"code": null,
"e": 1436,
"s": 1430,
"text": "Opera"
},
{
"code": null,
"e": 1445,
"s": 1436,
"text": "HTML-DOM"
},
{
"code": null,
"e": 1450,
"s": 1445,
"text": "HTML"
},
{
"code": null,
"e": 1461,
"s": 1450,
"text": "JavaScript"
},
{
"code": null,
"e": 1478,
"s": 1461,
"text": "Web Technologies"
},
{
"code": null,
"e": 1483,
"s": 1478,
"text": "HTML"
},
{
"code": null,
"e": 1581,
"s": 1483,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1605,
"s": 1581,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1644,
"s": 1605,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1681,
"s": 1644,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1731,
"s": 1681,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1759,
"s": 1731,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1820,
"s": 1759,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1892,
"s": 1820,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1932,
"s": 1892,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1984,
"s": 1932,
"text": "How to append HTML code to a div using JavaScript ?"
}
]
|
How to convert a float number to the whole number in JavaScript? | 15 Apr, 2019
There are various methods to convert float number to the whole number in JavaScript.
Math.floor (floating argument): Round off the number passed as parameter to its nearest integer in Downward direction.Syntax:Math.floor(value)<script> //float value is 4.59; var x = 4.59; var z = Math.floor(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 4
Math.ceil (floating argument): Return the smallest integer greater than or equal to a given number.Syntax:Math.ceil(value)<script> //float value is 4.59; var x = 4.59; var z = Math.ceil(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 5
Math.round (floating argument): Round a number to its nearest integer.Syntax:Math.round(var);<script> //float value is 4.59; var x = 4.59; var z = Math.round(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 5
Math.trunc (floating argument): Return the integer part of a floating-point number by removing the fractional digits.Syntax:Math.trunc(value)<script> //float value is 4.59; var x = 4.59; var z = Math.trunc(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 4
parseInt (floating argument): Accept the string and convert it into an integer.Syntax:parseInt(Value, radix)
<script> //float value is 3.54; var x = 3.54; var z = parseInt(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 3.54 is 3
double bitwise not (~~) operator: Round a number to towards zero. If the operand is a number and it’s not NaN or Infinity.Syntax:~~value<script> //float value is 4.59; var x = 4.59; var z = ~~x; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 4
bitwise OR (|) operator: Round a number to towards zero.Syntax:var = value | 0;<script> //float value is 5.67; var x = 5.67; var z = x | 0; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.67 is 5
Using shift (>>) operator: Round a number to towards zero.Syntax:var = value >> 0;<script> //float value is 5.63; var x = 5.63; var z = x >> 0; //it is same as we are dividing the value by 1. document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.63 is 5
Using unsigned shift (>>>) operator Round a number to towards zero.Syntax:var = value >>> 0;<script> //float value is 5.68; var x = 5.68; //it is same as we are dividing the value by 1. var z = x >>> 0; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.68 is 5
By subtracting the fractional partSyntax:var = val - val%1;<script> //float value is 5.48; var x = 5.48; var z = x - x%1; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.48 is 5
Using XOR (^) operatorSyntax:var = value ^ 0;<script> //float value is 5.49; var x = 5.49; var z = x ^ 0; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.49 is 5
Math.floor (floating argument): Round off the number passed as parameter to its nearest integer in Downward direction.Syntax:Math.floor(value)<script> //float value is 4.59; var x = 4.59; var z = Math.floor(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 4
Math.floor(value)
<script> //float value is 4.59; var x = 4.59; var z = Math.floor(x); document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 4.59 is 4
Math.ceil (floating argument): Return the smallest integer greater than or equal to a given number.Syntax:Math.ceil(value)<script> //float value is 4.59; var x = 4.59; var z = Math.ceil(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 5
Math.ceil(value)
<script> //float value is 4.59; var x = 4.59; var z = Math.ceil(x); document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 4.59 is 5
Math.round (floating argument): Round a number to its nearest integer.Syntax:Math.round(var);<script> //float value is 4.59; var x = 4.59; var z = Math.round(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 5
Math.round(var);
<script> //float value is 4.59; var x = 4.59; var z = Math.round(x); document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 4.59 is 5
Math.trunc (floating argument): Return the integer part of a floating-point number by removing the fractional digits.Syntax:Math.trunc(value)<script> //float value is 4.59; var x = 4.59; var z = Math.trunc(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 4
Math.trunc(value)
<script> //float value is 4.59; var x = 4.59; var z = Math.trunc(x); document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 4.59 is 4
parseInt (floating argument): Accept the string and convert it into an integer.Syntax:parseInt(Value, radix)
<script> //float value is 3.54; var x = 3.54; var z = parseInt(x); document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 3.54 is 3
parseInt(Value, radix)
<script> //float value is 3.54; var x = 3.54; var z = parseInt(x); document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 3.54 is 3
double bitwise not (~~) operator: Round a number to towards zero. If the operand is a number and it’s not NaN or Infinity.Syntax:~~value<script> //float value is 4.59; var x = 4.59; var z = ~~x; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 4.59 is 4
~~value
<script> //float value is 4.59; var x = 4.59; var z = ~~x; document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 4.59 is 4
bitwise OR (|) operator: Round a number to towards zero.Syntax:var = value | 0;<script> //float value is 5.67; var x = 5.67; var z = x | 0; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.67 is 5
var = value | 0;
<script> //float value is 5.67; var x = 5.67; var z = x | 0; document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 5.67 is 5
Using shift (>>) operator: Round a number to towards zero.Syntax:var = value >> 0;<script> //float value is 5.63; var x = 5.63; var z = x >> 0; //it is same as we are dividing the value by 1. document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.63 is 5
var = value >> 0;
<script> //float value is 5.63; var x = 5.63; var z = x >> 0; //it is same as we are dividing the value by 1. document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 5.63 is 5
Using unsigned shift (>>>) operator Round a number to towards zero.Syntax:var = value >>> 0;<script> //float value is 5.68; var x = 5.68; //it is same as we are dividing the value by 1. var z = x >>> 0; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.68 is 5
var = value >>> 0;
<script> //float value is 5.68; var x = 5.68; //it is same as we are dividing the value by 1. var z = x >>> 0; document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 5.68 is 5
By subtracting the fractional partSyntax:var = val - val%1;<script> //float value is 5.48; var x = 5.48; var z = x - x%1; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.48 is 5
var = val - val%1;
<script> //float value is 5.48; var x = 5.48; var z = x - x%1; document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 5.48 is 5
Using XOR (^) operatorSyntax:var = value ^ 0;<script> //float value is 5.49; var x = 5.49; var z = x ^ 0; document.write("Converted value of " + x + " is " + z);</script>Output :Converted value of 5.49 is 5
var = value ^ 0;
<script> //float value is 5.49; var x = 5.49; var z = x ^ 0; document.write("Converted value of " + x + " is " + z);</script>
Output :
Converted value of 5.49 is 5
javascript-functions
javascript-math
JavaScript-Misc
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 113,
"s": 28,
"text": "There are various methods to convert float number to the whole number in JavaScript."
},
{
"code": null,
"e": 3215,
"s": 113,
"text": "Math.floor (floating argument): Round off the number passed as parameter to its nearest integer in Downward direction.Syntax:Math.floor(value)<script> //float value is 4.59; var x = 4.59; var z = Math.floor(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 4\nMath.ceil (floating argument): Return the smallest integer greater than or equal to a given number.Syntax:Math.ceil(value)<script> //float value is 4.59; var x = 4.59; var z = Math.ceil(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 5\nMath.round (floating argument): Round a number to its nearest integer.Syntax:Math.round(var);<script> //float value is 4.59; var x = 4.59; var z = Math.round(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 5\nMath.trunc (floating argument): Return the integer part of a floating-point number by removing the fractional digits.Syntax:Math.trunc(value)<script> //float value is 4.59; var x = 4.59; var z = Math.trunc(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 4\nparseInt (floating argument): Accept the string and convert it into an integer.Syntax:parseInt(Value, radix)\n<script> //float value is 3.54; var x = 3.54; var z = parseInt(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 3.54 is 3\ndouble bitwise not (~~) operator: Round a number to towards zero. If the operand is a number and it’s not NaN or Infinity.Syntax:~~value<script> //float value is 4.59; var x = 4.59; var z = ~~x; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 4\nbitwise OR (|) operator: Round a number to towards zero.Syntax:var = value | 0;<script> //float value is 5.67; var x = 5.67; var z = x | 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.67 is 5\nUsing shift (>>) operator: Round a number to towards zero.Syntax:var = value >> 0;<script> //float value is 5.63; var x = 5.63; var z = x >> 0; //it is same as we are dividing the value by 1. document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.63 is 5\nUsing unsigned shift (>>>) operator Round a number to towards zero.Syntax:var = value >>> 0;<script> //float value is 5.68; var x = 5.68; //it is same as we are dividing the value by 1. var z = x >>> 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.68 is 5\nBy subtracting the fractional partSyntax:var = val - val%1;<script> //float value is 5.48; var x = 5.48; var z = x - x%1; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.48 is 5\nUsing XOR (^) operatorSyntax:var = value ^ 0;<script> //float value is 5.49; var x = 5.49; var z = x ^ 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.49 is 5\n"
},
{
"code": null,
"e": 3535,
"s": 3215,
"text": "Math.floor (floating argument): Round off the number passed as parameter to its nearest integer in Downward direction.Syntax:Math.floor(value)<script> //float value is 4.59; var x = 4.59; var z = Math.floor(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 4\n"
},
{
"code": null,
"e": 3553,
"s": 3535,
"text": "Math.floor(value)"
},
{
"code": "<script> //float value is 4.59; var x = 4.59; var z = Math.floor(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 3694,
"s": 3553,
"text": null
},
{
"code": null,
"e": 3703,
"s": 3694,
"text": "Output :"
},
{
"code": null,
"e": 3733,
"s": 3703,
"text": "Converted value of 4.59 is 4\n"
},
{
"code": null,
"e": 4032,
"s": 3733,
"text": "Math.ceil (floating argument): Return the smallest integer greater than or equal to a given number.Syntax:Math.ceil(value)<script> //float value is 4.59; var x = 4.59; var z = Math.ceil(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 5\n"
},
{
"code": null,
"e": 4049,
"s": 4032,
"text": "Math.ceil(value)"
},
{
"code": "<script> //float value is 4.59; var x = 4.59; var z = Math.ceil(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 4189,
"s": 4049,
"text": null
},
{
"code": null,
"e": 4198,
"s": 4189,
"text": "Output :"
},
{
"code": null,
"e": 4228,
"s": 4198,
"text": "Converted value of 4.59 is 5\n"
},
{
"code": null,
"e": 4499,
"s": 4228,
"text": "Math.round (floating argument): Round a number to its nearest integer.Syntax:Math.round(var);<script> //float value is 4.59; var x = 4.59; var z = Math.round(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 5\n"
},
{
"code": null,
"e": 4516,
"s": 4499,
"text": "Math.round(var);"
},
{
"code": "<script> //float value is 4.59; var x = 4.59; var z = Math.round(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 4657,
"s": 4516,
"text": null
},
{
"code": null,
"e": 4666,
"s": 4657,
"text": "Output :"
},
{
"code": null,
"e": 4696,
"s": 4666,
"text": "Converted value of 4.59 is 5\n"
},
{
"code": null,
"e": 5015,
"s": 4696,
"text": "Math.trunc (floating argument): Return the integer part of a floating-point number by removing the fractional digits.Syntax:Math.trunc(value)<script> //float value is 4.59; var x = 4.59; var z = Math.trunc(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 4\n"
},
{
"code": null,
"e": 5033,
"s": 5015,
"text": "Math.trunc(value)"
},
{
"code": "<script> //float value is 4.59; var x = 4.59; var z = Math.trunc(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 5174,
"s": 5033,
"text": null
},
{
"code": null,
"e": 5183,
"s": 5174,
"text": "Output :"
},
{
"code": null,
"e": 5213,
"s": 5183,
"text": "Converted value of 4.59 is 4\n"
},
{
"code": null,
"e": 5498,
"s": 5213,
"text": "parseInt (floating argument): Accept the string and convert it into an integer.Syntax:parseInt(Value, radix)\n<script> //float value is 3.54; var x = 3.54; var z = parseInt(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 3.54 is 3\n"
},
{
"code": null,
"e": 5522,
"s": 5498,
"text": "parseInt(Value, radix)\n"
},
{
"code": "<script> //float value is 3.54; var x = 3.54; var z = parseInt(x); document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 5661,
"s": 5522,
"text": null
},
{
"code": null,
"e": 5670,
"s": 5661,
"text": "Output :"
},
{
"code": null,
"e": 5700,
"s": 5670,
"text": "Converted value of 3.54 is 3\n"
},
{
"code": null,
"e": 6004,
"s": 5700,
"text": "double bitwise not (~~) operator: Round a number to towards zero. If the operand is a number and it’s not NaN or Infinity.Syntax:~~value<script> //float value is 4.59; var x = 4.59; var z = ~~x; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 4.59 is 4\n"
},
{
"code": null,
"e": 6012,
"s": 6004,
"text": "~~value"
},
{
"code": "<script> //float value is 4.59; var x = 4.59; var z = ~~x; document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 6143,
"s": 6012,
"text": null
},
{
"code": null,
"e": 6152,
"s": 6143,
"text": "Output :"
},
{
"code": null,
"e": 6182,
"s": 6152,
"text": "Converted value of 4.59 is 4\n"
},
{
"code": null,
"e": 6431,
"s": 6182,
"text": "bitwise OR (|) operator: Round a number to towards zero.Syntax:var = value | 0;<script> //float value is 5.67; var x = 5.67; var z = x | 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.67 is 5\n"
},
{
"code": null,
"e": 6448,
"s": 6431,
"text": "var = value | 0;"
},
{
"code": "<script> //float value is 5.67; var x = 5.67; var z = x | 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 6581,
"s": 6448,
"text": null
},
{
"code": null,
"e": 6590,
"s": 6581,
"text": "Output :"
},
{
"code": null,
"e": 6620,
"s": 6590,
"text": "Converted value of 5.67 is 5\n"
},
{
"code": null,
"e": 6924,
"s": 6620,
"text": "Using shift (>>) operator: Round a number to towards zero.Syntax:var = value >> 0;<script> //float value is 5.63; var x = 5.63; var z = x >> 0; //it is same as we are dividing the value by 1. document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.63 is 5\n"
},
{
"code": null,
"e": 6942,
"s": 6924,
"text": "var = value >> 0;"
},
{
"code": "<script> //float value is 5.63; var x = 5.63; var z = x >> 0; //it is same as we are dividing the value by 1. document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 7127,
"s": 6942,
"text": null
},
{
"code": null,
"e": 7136,
"s": 7127,
"text": "Output :"
},
{
"code": null,
"e": 7166,
"s": 7136,
"text": "Converted value of 5.63 is 5\n"
},
{
"code": null,
"e": 7481,
"s": 7166,
"text": "Using unsigned shift (>>>) operator Round a number to towards zero.Syntax:var = value >>> 0;<script> //float value is 5.68; var x = 5.68; //it is same as we are dividing the value by 1. var z = x >>> 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.68 is 5\n"
},
{
"code": null,
"e": 7500,
"s": 7481,
"text": "var = value >>> 0;"
},
{
"code": "<script> //float value is 5.68; var x = 5.68; //it is same as we are dividing the value by 1. var z = x >>> 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 7686,
"s": 7500,
"text": null
},
{
"code": null,
"e": 7695,
"s": 7686,
"text": "Output :"
},
{
"code": null,
"e": 7725,
"s": 7695,
"text": "Converted value of 5.68 is 5\n"
},
{
"code": null,
"e": 7956,
"s": 7725,
"text": "By subtracting the fractional partSyntax:var = val - val%1;<script> //float value is 5.48; var x = 5.48; var z = x - x%1; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.48 is 5\n"
},
{
"code": null,
"e": 7975,
"s": 7956,
"text": "var = val - val%1;"
},
{
"code": "<script> //float value is 5.48; var x = 5.48; var z = x - x%1; document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 8110,
"s": 7975,
"text": null
},
{
"code": null,
"e": 8119,
"s": 8110,
"text": "Output :"
},
{
"code": null,
"e": 8149,
"s": 8119,
"text": "Converted value of 5.48 is 5\n"
},
{
"code": null,
"e": 8364,
"s": 8149,
"text": "Using XOR (^) operatorSyntax:var = value ^ 0;<script> //float value is 5.49; var x = 5.49; var z = x ^ 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>Output :Converted value of 5.49 is 5\n"
},
{
"code": null,
"e": 8381,
"s": 8364,
"text": "var = value ^ 0;"
},
{
"code": "<script> //float value is 5.49; var x = 5.49; var z = x ^ 0; document.write(\"Converted value of \" + x + \" is \" + z);</script>",
"e": 8514,
"s": 8381,
"text": null
},
{
"code": null,
"e": 8523,
"s": 8514,
"text": "Output :"
},
{
"code": null,
"e": 8553,
"s": 8523,
"text": "Converted value of 5.49 is 5\n"
},
{
"code": null,
"e": 8574,
"s": 8553,
"text": "javascript-functions"
},
{
"code": null,
"e": 8590,
"s": 8574,
"text": "javascript-math"
},
{
"code": null,
"e": 8606,
"s": 8590,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 8613,
"s": 8606,
"text": "Picked"
},
{
"code": null,
"e": 8624,
"s": 8613,
"text": "JavaScript"
}
]
|
Maximum GCD of all subarrays of length at least 2 - GeeksforGeeks | 21 Nov, 2021
Given an array arr[] of N numbers. The task is to find the maximum GCD of all subarrays of size greater than 1. Examples:
Input: arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 } Output: 9 Explanation: GCD of the subarray {18, 9, 9} is maximum which is 9.Input: arr[] = { 4, 8, 12, 16, 20, 24 } Output: 4 Explanation: GCD of the subarray {4, 18, 12, 16, 20, 24} is maximum which is 4.
Naive Approach: The idea is to generate all the subarray of size greater than 1 and then find the maximum of gcd of all subarray formed. Time complexity: O(N2) Efficient Approach: Let GCD of two numbers be g. Now if we take gcd of g with any third number say c then, gcd will decrease or remain same, but it will never increase. The idea is to find gcd of every consecutive pair in the arr[] and the maximum of gcd of all the pairs formed is the desired result.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find GCDint gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b);} void findMaxGCD(int arr[], int n){ // To store the maximum GCD int maxGCD = 0; // Traverse the array for (int i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element int val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD cout << maxGCD << endl;} // Driver Codeint main(){ int arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call findMaxGCD(arr, n); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find GCDstatic int gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b);} static void findMaxGCD(int arr[], int n){ // To store the maximum GCD int maxGCD = 0; // Traverse the array for(int i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element int val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD System.out.print(maxGCD + "\n");} // Driver Codepublic static void main(String[] args){ int arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 }; int n = arr.length; // Function call findMaxGCD(arr, n);}} // This code is contributed by amal kumar choubey
# Python3 program for the above approach # Function to find GCDdef gcd(a, b): if (b == 0): return a; return gcd(b, a % b); def findMaxGCD(arr, n): # To store the maximum GCD maxGCD = 0; # Traverse the array for i in range(0, n - 1): # Find GCD of the consecutive # element val = gcd(arr[i], arr[i + 1]); # If calculated GCD > maxGCD # then update it if (val > maxGCD): maxGCD = val; # Print the maximum GCD print(maxGCD); # Driver Codeif __name__ == '__main__': arr = [ 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 ]; n = len(arr); # Function call findMaxGCD(arr, n); # This code is contributed by 29AjayKumar
// C# program for the above approachusing System; class GFG{ // Function to find GCDstatic int gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b);} static void findMaxGCD(int []arr, int n){ // To store the maximum GCD int maxGCD = 0; // Traverse the array for(int i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element int val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD Console.Write(maxGCD + "\n");} // Driver Codepublic static void Main(){ int []arr = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 }; int n = arr.Length; // Function call findMaxGCD(arr, n);}} // This code is contributed by Code_Mech
<script> // Javascript program for the above approach // Function to find GCDfunction gcd(a, b){ if (b == 0) { return a; } return gcd(b, a % b);} function findMaxGCD(arr, n){ // To store the maximum GCD let maxGCD = 0; // Traverse the array for (let i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element let val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD document.write(maxGCD + "<br>");} // Driver Code let arr = [ 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 ]; let n = arr.length; // Function Call findMaxGCD(arr, n); // This code is contributed by Mayank Tyagi </script>
9
Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(log(max(a, b)))
Amal Kumar Choubey
Code_Mech
29AjayKumar
mayanktyagi1709
rishavmahato348
GCD-LCM
subarray
Aptitude
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Puzzle | How much money did the man have before entering the bank?
7 Best Tips to Prepare for Aptitude Test For Campus Placements
Puzzle | Splitting a Cake with a Missing Piece in two equal portion
Geometry and Co-ordinates
Program to find the last two digits of x^y
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews | [
{
"code": null,
"e": 24830,
"s": 24802,
"text": "\n21 Nov, 2021"
},
{
"code": null,
"e": 24954,
"s": 24830,
"text": "Given an array arr[] of N numbers. The task is to find the maximum GCD of all subarrays of size greater than 1. Examples: "
},
{
"code": null,
"e": 25212,
"s": 24954,
"text": "Input: arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 } Output: 9 Explanation: GCD of the subarray {18, 9, 9} is maximum which is 9.Input: arr[] = { 4, 8, 12, 16, 20, 24 } Output: 4 Explanation: GCD of the subarray {4, 18, 12, 16, 20, 24} is maximum which is 4. "
},
{
"code": null,
"e": 25728,
"s": 25214,
"text": "Naive Approach: The idea is to generate all the subarray of size greater than 1 and then find the maximum of gcd of all subarray formed. Time complexity: O(N2) Efficient Approach: Let GCD of two numbers be g. Now if we take gcd of g with any third number say c then, gcd will decrease or remain same, but it will never increase. The idea is to find gcd of every consecutive pair in the arr[] and the maximum of gcd of all the pairs formed is the desired result.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25732,
"s": 25728,
"text": "C++"
},
{
"code": null,
"e": 25737,
"s": 25732,
"text": "Java"
},
{
"code": null,
"e": 25745,
"s": 25737,
"text": "Python3"
},
{
"code": null,
"e": 25748,
"s": 25745,
"text": "C#"
},
{
"code": null,
"e": 25759,
"s": 25748,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find GCDint gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b);} void findMaxGCD(int arr[], int n){ // To store the maximum GCD int maxGCD = 0; // Traverse the array for (int i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element int val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD cout << maxGCD << endl;} // Driver Codeint main(){ int arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call findMaxGCD(arr, n); return 0;}",
"e": 26581,
"s": 25759,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find GCDstatic int gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b);} static void findMaxGCD(int arr[], int n){ // To store the maximum GCD int maxGCD = 0; // Traverse the array for(int i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element int val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD System.out.print(maxGCD + \"\\n\");} // Driver Codepublic static void main(String[] args){ int arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 }; int n = arr.length; // Function call findMaxGCD(arr, n);}} // This code is contributed by amal kumar choubey",
"e": 27477,
"s": 26581,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find GCDdef gcd(a, b): if (b == 0): return a; return gcd(b, a % b); def findMaxGCD(arr, n): # To store the maximum GCD maxGCD = 0; # Traverse the array for i in range(0, n - 1): # Find GCD of the consecutive # element val = gcd(arr[i], arr[i + 1]); # If calculated GCD > maxGCD # then update it if (val > maxGCD): maxGCD = val; # Print the maximum GCD print(maxGCD); # Driver Codeif __name__ == '__main__': arr = [ 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 ]; n = len(arr); # Function call findMaxGCD(arr, n); # This code is contributed by 29AjayKumar",
"e": 28200,
"s": 27477,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find GCDstatic int gcd(int a, int b){ if (b == 0) { return a; } return gcd(b, a % b);} static void findMaxGCD(int []arr, int n){ // To store the maximum GCD int maxGCD = 0; // Traverse the array for(int i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element int val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD Console.Write(maxGCD + \"\\n\");} // Driver Codepublic static void Main(){ int []arr = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 }; int n = arr.Length; // Function call findMaxGCD(arr, n);}} // This code is contributed by Code_Mech",
"e": 29076,
"s": 28200,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find GCDfunction gcd(a, b){ if (b == 0) { return a; } return gcd(b, a % b);} function findMaxGCD(arr, n){ // To store the maximum GCD let maxGCD = 0; // Traverse the array for (let i = 0; i < n - 1; i++) { // Find GCD of the consecutive // element let val = gcd(arr[i], arr[i + 1]); // If calculated GCD > maxGCD // then update it if (val > maxGCD) { maxGCD = val; } } // Print the maximum GCD document.write(maxGCD + \"<br>\");} // Driver Code let arr = [ 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 ]; let n = arr.length; // Function Call findMaxGCD(arr, n); // This code is contributed by Mayank Tyagi </script>",
"e": 29878,
"s": 29076,
"text": null
},
{
"code": null,
"e": 29880,
"s": 29878,
"text": "9"
},
{
"code": null,
"e": 29941,
"s": 29882,
"text": "Time Complexity: O(N), where N is the length of the array."
},
{
"code": null,
"e": 29977,
"s": 29941,
"text": "Auxiliary Space: O(log(max(a, b))) "
},
{
"code": null,
"e": 29996,
"s": 29977,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 30006,
"s": 29996,
"text": "Code_Mech"
},
{
"code": null,
"e": 30018,
"s": 30006,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30034,
"s": 30018,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 30050,
"s": 30034,
"text": "rishavmahato348"
},
{
"code": null,
"e": 30058,
"s": 30050,
"text": "GCD-LCM"
},
{
"code": null,
"e": 30067,
"s": 30058,
"text": "subarray"
},
{
"code": null,
"e": 30076,
"s": 30067,
"text": "Aptitude"
},
{
"code": null,
"e": 30083,
"s": 30076,
"text": "Arrays"
},
{
"code": null,
"e": 30096,
"s": 30083,
"text": "Mathematical"
},
{
"code": null,
"e": 30103,
"s": 30096,
"text": "Arrays"
},
{
"code": null,
"e": 30116,
"s": 30103,
"text": "Mathematical"
},
{
"code": null,
"e": 30214,
"s": 30116,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30223,
"s": 30214,
"text": "Comments"
},
{
"code": null,
"e": 30236,
"s": 30223,
"text": "Old Comments"
},
{
"code": null,
"e": 30303,
"s": 30236,
"text": "Puzzle | How much money did the man have before entering the bank?"
},
{
"code": null,
"e": 30366,
"s": 30303,
"text": "7 Best Tips to Prepare for Aptitude Test For Campus Placements"
},
{
"code": null,
"e": 30434,
"s": 30366,
"text": "Puzzle | Splitting a Cake with a Missing Piece in two equal portion"
},
{
"code": null,
"e": 30460,
"s": 30434,
"text": "Geometry and Co-ordinates"
},
{
"code": null,
"e": 30503,
"s": 30460,
"text": "Program to find the last two digits of x^y"
},
{
"code": null,
"e": 30518,
"s": 30503,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30534,
"s": 30518,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30561,
"s": 30534,
"text": "Program for array rotation"
},
{
"code": null,
"e": 30609,
"s": 30561,
"text": "Stack Data Structure (Introduction and Program)"
}
]
|
Checking if a key exists in HTML5 Local Storage | The getitem(key) takes value for one parameter and returns the value associated with the key. The given key is present in the list associated with the object.
if(localStorage.getItem("user")===null) {
//...
}
But if the key is not present in the list then it passes null value by using the below-given code
You can also follow the below-given procedure −
if("user" in localStorage){
alert('yes');
} else {
alert('no');
} | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "The getitem(key) takes value for one parameter and returns the value associated with the key. The given key is present in the list associated with the object."
},
{
"code": null,
"e": 1274,
"s": 1221,
"text": "if(localStorage.getItem(\"user\")===null) {\n //...\n}"
},
{
"code": null,
"e": 1372,
"s": 1274,
"text": "But if the key is not present in the list then it passes null value by using the below-given code"
},
{
"code": null,
"e": 1420,
"s": 1372,
"text": "You can also follow the below-given procedure −"
},
{
"code": null,
"e": 1492,
"s": 1420,
"text": "if(\"user\" in localStorage){\n alert('yes');\n} else {\n alert('no');\n}"
}
]
|
How to Map Ports in Docker? - GeeksforGeeks | 22 Jun, 2021
In docker, all the application in the container runs on particular ports when you run a container. If you want to access the particular application with the help of port number you need to map the port number of the container with the port number of the docker host.
In the implementation, we are going to download a Jenkins container from the docker hub and map the Jenkins container port number with the docker host port number.
Sign-up to your docker hub repository.
Sign-up in docker hub
Search for the Jenkins image and use the docker pull command to download the Jenkins image on your local server.
Download Jenkins’s image using the below command:
sudo docker pull jenkins
To see the ports exposed by the Jenkins container type docker inspect command.
docker inspect Container/image
In this step, we run Jenkins and map the port by changing the docker run command by adding the p option which specifies the port mapping.
sudo docker run -p 8080:8080 50000:500000 jenkins
On the left-hand side, it is the Docker host port number and on the right-hand side Docker container number.
These are all the steps required to map the port number of the container to the port number of the docker host.
rajeev0719singh
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
ML | Underfitting and Overfitting
Clustering in Machine Learning
Getting started with Machine Learning | [
{
"code": null,
"e": 25753,
"s": 25725,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 26020,
"s": 25753,
"text": "In docker, all the application in the container runs on particular ports when you run a container. If you want to access the particular application with the help of port number you need to map the port number of the container with the port number of the docker host."
},
{
"code": null,
"e": 26184,
"s": 26020,
"text": "In the implementation, we are going to download a Jenkins container from the docker hub and map the Jenkins container port number with the docker host port number."
},
{
"code": null,
"e": 26223,
"s": 26184,
"text": "Sign-up to your docker hub repository."
},
{
"code": null,
"e": 26245,
"s": 26223,
"text": "Sign-up in docker hub"
},
{
"code": null,
"e": 26358,
"s": 26245,
"text": "Search for the Jenkins image and use the docker pull command to download the Jenkins image on your local server."
},
{
"code": null,
"e": 26408,
"s": 26358,
"text": "Download Jenkins’s image using the below command:"
},
{
"code": null,
"e": 26433,
"s": 26408,
"text": "sudo docker pull jenkins"
},
{
"code": null,
"e": 26512,
"s": 26433,
"text": "To see the ports exposed by the Jenkins container type docker inspect command."
},
{
"code": null,
"e": 26543,
"s": 26512,
"text": "docker inspect Container/image"
},
{
"code": null,
"e": 26681,
"s": 26543,
"text": "In this step, we run Jenkins and map the port by changing the docker run command by adding the p option which specifies the port mapping."
},
{
"code": null,
"e": 26731,
"s": 26681,
"text": "sudo docker run -p 8080:8080 50000:500000 jenkins"
},
{
"code": null,
"e": 26840,
"s": 26731,
"text": "On the left-hand side, it is the Docker host port number and on the right-hand side Docker container number."
},
{
"code": null,
"e": 26953,
"s": 26840,
"text": "These are all the steps required to map the port number of the container to the port number of the docker host. "
},
{
"code": null,
"e": 26969,
"s": 26953,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 26995,
"s": 26969,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27093,
"s": 26995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27116,
"s": 27093,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 27130,
"s": 27116,
"text": "Decision Tree"
},
{
"code": null,
"e": 27153,
"s": 27130,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 27193,
"s": 27153,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 27237,
"s": 27193,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27260,
"s": 27237,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 27298,
"s": 27260,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 27332,
"s": 27298,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 27363,
"s": 27332,
"text": "Clustering in Machine Learning"
}
]
|
C program to print a string without any quote (single or double) in the program - GeeksforGeeks | 31 Jan, 2022
Print a string without using quotes anywhere in the program using C or C++. Note : should not read input from the console.
The idea is to use macro processor in C (Refer point 6 of this article). A token passed to macro can be converted to a string literal by using # before it.
C
// C program to print a string without// quote in the program#include <stdio.h>#define get(x) #xint main(){ printf(get(vignesh)); return 0;}
Output:
vignesh
This article is contributed by Vignesh. 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.
germanshephered48
C-Macro & Preprocessor
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Converting Strings to Numbers in C/C++
Substring in C++
rand() and srand() in C/C++
std::string class in C++
Enumeration (or enum) in C
TCP Server-Client implementation in C | [
{
"code": null,
"e": 24496,
"s": 24468,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 24619,
"s": 24496,
"text": "Print a string without using quotes anywhere in the program using C or C++. Note : should not read input from the console."
},
{
"code": null,
"e": 24779,
"s": 24621,
"text": "The idea is to use macro processor in C (Refer point 6 of this article). A token passed to macro can be converted to a string literal by using # before it. "
},
{
"code": null,
"e": 24781,
"s": 24779,
"text": "C"
},
{
"code": "// C program to print a string without// quote in the program#include <stdio.h>#define get(x) #xint main(){ printf(get(vignesh)); return 0;}",
"e": 24928,
"s": 24781,
"text": null
},
{
"code": null,
"e": 24938,
"s": 24928,
"text": "Output: "
},
{
"code": null,
"e": 24946,
"s": 24938,
"text": "vignesh"
},
{
"code": null,
"e": 25362,
"s": 24946,
"text": "This article is contributed by Vignesh. 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": 25380,
"s": 25362,
"text": "germanshephered48"
},
{
"code": null,
"e": 25403,
"s": 25380,
"text": "C-Macro & Preprocessor"
},
{
"code": null,
"e": 25412,
"s": 25403,
"text": "c-puzzle"
},
{
"code": null,
"e": 25423,
"s": 25412,
"text": "C Language"
},
{
"code": null,
"e": 25521,
"s": 25423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25556,
"s": 25521,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25602,
"s": 25556,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25614,
"s": 25602,
"text": "fork() in C"
},
{
"code": null,
"e": 25654,
"s": 25614,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25693,
"s": 25654,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 25710,
"s": 25693,
"text": "Substring in C++"
},
{
"code": null,
"e": 25738,
"s": 25710,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25763,
"s": 25738,
"text": "std::string class in C++"
},
{
"code": null,
"e": 25790,
"s": 25763,
"text": "Enumeration (or enum) in C"
}
]
|
How to view array of a structure in JavaScript ? - GeeksforGeeks | 10 Oct, 2021
The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and string should be enclosed between either “double quotes” or ‘single quotes’. You can get the structure of by using JSON.stringify() or not, here you will see the use of JSON.stringify(). For other procedure you can check this link.Syntax:
JSON.stringify(value, replacer, space)
The Functionality of the alert() is to first give information to the user before gets proceeding further. So, in the below code, the button on click function(Alert()) has two alerts (alert()), after displaying all the alerts it gets further with the webpage. By clicking ‘ok’ in the alert box it displays the next alert until all are done.Let’s check the type of alerts can be applied:
alert(JSON.stringify(guardians)): It displays as it is array structure.
alert(JSON.stringify(guardians, 9, 1)): It displays the customized structure, where the 9 acts a replacer, makes array elements gets print in vertically and 1 acts as space number and provides one space between elements.
alert(JSON.stringify(guardians, “”, 5)): It displays, the customized structure, where the “” acts a replacer, makes array elements gets print in vertically and 5 acts as space number and provides five space between elements.
Example 1:
javascript
<!DOCTYPE html><html> <head> <title> How to view array of a structure in JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:Green;"> GeeksforGeeks </h1> <h3> Getting array structure JSON.stringify </h3> <p id="d1"></p> <input type="button" onclick="Alert()" value="Click Here" /> <script> function Alert() { // Array structure var guardians = ["Quill", "Gamora", "Groot", "Rocket", "Drax", 21]; // Prints the array elements with a comma // separated but not the structure document.getElementById("d1").innerHTML = "Guardians = " + guardians; // Alerts the window with the array alert(JSON.stringify(guardians)) // Alerts the window with a customized array alert(JSON.stringify(guardians, 9, 1)) } </script></body> </html>
Output:
Before clicking button:
After clicking button:
After clicking ok:
Final printed result:
Example 2: You can also get the structure of an Associate array easily.
html
<!DOCTYPE html><html> <head> <title> How to view array of a structure in JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:Green;"> GeeksforGeeks </h1> <h3> Getting associate array structure JSON.stringify </h3> <p id="d1"></p> <input type="button" onclick="Alert()" value="Click Here" /> <script> function Alert() { // Array structure var guardians = { "Newton": "Gravity", "Albert": "Energy", "Edison": "Bulb", "Tesla": "AC" }; // Alerts the window with the array alert(JSON.stringify(guardians)) // Alerts the window with a // customized array alert(JSON.stringify(guardians, 9, 1)) // Alerts the window with a // customized array alert(JSON.stringify(guardians,"",5)) } </script></body> </html>
Output:
Before clicking button:
After clicking button:
After clicking ok:
After clicking 2nd ok:
sweetyty
adnanirshad158
JavaScript-Misc
Picked
Web technologies
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 26921,
"s": 26545,
"text": "The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and string should be enclosed between either “double quotes” or ‘single quotes’. You can get the structure of by using JSON.stringify() or not, here you will see the use of JSON.stringify(). For other procedure you can check this link.Syntax: "
},
{
"code": null,
"e": 26960,
"s": 26921,
"text": "JSON.stringify(value, replacer, space)"
},
{
"code": null,
"e": 27348,
"s": 26960,
"text": "The Functionality of the alert() is to first give information to the user before gets proceeding further. So, in the below code, the button on click function(Alert()) has two alerts (alert()), after displaying all the alerts it gets further with the webpage. By clicking ‘ok’ in the alert box it displays the next alert until all are done.Let’s check the type of alerts can be applied: "
},
{
"code": null,
"e": 27420,
"s": 27348,
"text": "alert(JSON.stringify(guardians)): It displays as it is array structure."
},
{
"code": null,
"e": 27641,
"s": 27420,
"text": "alert(JSON.stringify(guardians, 9, 1)): It displays the customized structure, where the 9 acts a replacer, makes array elements gets print in vertically and 1 acts as space number and provides one space between elements."
},
{
"code": null,
"e": 27866,
"s": 27641,
"text": "alert(JSON.stringify(guardians, “”, 5)): It displays, the customized structure, where the “” acts a replacer, makes array elements gets print in vertically and 5 acts as space number and provides five space between elements."
},
{
"code": null,
"e": 27879,
"s": 27866,
"text": "Example 1: "
},
{
"code": null,
"e": 27890,
"s": 27879,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to view array of a structure in JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:Green;\"> GeeksforGeeks </h1> <h3> Getting array structure JSON.stringify </h3> <p id=\"d1\"></p> <input type=\"button\" onclick=\"Alert()\" value=\"Click Here\" /> <script> function Alert() { // Array structure var guardians = [\"Quill\", \"Gamora\", \"Groot\", \"Rocket\", \"Drax\", 21]; // Prints the array elements with a comma // separated but not the structure document.getElementById(\"d1\").innerHTML = \"Guardians = \" + guardians; // Alerts the window with the array alert(JSON.stringify(guardians)) // Alerts the window with a customized array alert(JSON.stringify(guardians, 9, 1)) } </script></body> </html>",
"e": 28927,
"s": 27890,
"text": null
},
{
"code": null,
"e": 28937,
"s": 28927,
"text": "Output: "
},
{
"code": null,
"e": 28963,
"s": 28937,
"text": "Before clicking button: "
},
{
"code": null,
"e": 28988,
"s": 28963,
"text": "After clicking button: "
},
{
"code": null,
"e": 29009,
"s": 28988,
"text": "After clicking ok: "
},
{
"code": null,
"e": 29033,
"s": 29009,
"text": "Final printed result: "
},
{
"code": null,
"e": 29107,
"s": 29033,
"text": "Example 2: You can also get the structure of an Associate array easily. "
},
{
"code": null,
"e": 29112,
"s": 29107,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to view array of a structure in JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:Green;\"> GeeksforGeeks </h1> <h3> Getting associate array structure JSON.stringify </h3> <p id=\"d1\"></p> <input type=\"button\" onclick=\"Alert()\" value=\"Click Here\" /> <script> function Alert() { // Array structure var guardians = { \"Newton\": \"Gravity\", \"Albert\": \"Energy\", \"Edison\": \"Bulb\", \"Tesla\": \"AC\" }; // Alerts the window with the array alert(JSON.stringify(guardians)) // Alerts the window with a // customized array alert(JSON.stringify(guardians, 9, 1)) // Alerts the window with a // customized array alert(JSON.stringify(guardians,\"\",5)) } </script></body> </html> ",
"e": 30188,
"s": 29112,
"text": null
},
{
"code": null,
"e": 30198,
"s": 30188,
"text": "Output: "
},
{
"code": null,
"e": 30224,
"s": 30198,
"text": "Before clicking button: "
},
{
"code": null,
"e": 30249,
"s": 30224,
"text": "After clicking button: "
},
{
"code": null,
"e": 30270,
"s": 30249,
"text": "After clicking ok: "
},
{
"code": null,
"e": 30295,
"s": 30270,
"text": "After clicking 2nd ok: "
},
{
"code": null,
"e": 30306,
"s": 30297,
"text": "sweetyty"
},
{
"code": null,
"e": 30321,
"s": 30306,
"text": "adnanirshad158"
},
{
"code": null,
"e": 30337,
"s": 30321,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30344,
"s": 30337,
"text": "Picked"
},
{
"code": null,
"e": 30361,
"s": 30344,
"text": "Web technologies"
},
{
"code": null,
"e": 30372,
"s": 30361,
"text": "JavaScript"
},
{
"code": null,
"e": 30391,
"s": 30372,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30408,
"s": 30391,
"text": "Web Technologies"
},
{
"code": null,
"e": 30435,
"s": 30408,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30533,
"s": 30435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30573,
"s": 30533,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30634,
"s": 30573,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30675,
"s": 30634,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30697,
"s": 30675,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30751,
"s": 30697,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30791,
"s": 30751,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30824,
"s": 30791,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30867,
"s": 30824,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30917,
"s": 30867,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Probability of Knight | Practice | GeeksforGeeks | Given an NxN chessboard and a Knight at position (x, y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. Find the probability that the Knight remains in the chessboard after taking K steps, with the condition that it cant enter the board again once it leaves it.
Example 1:
Input : N = 8, x = 0, y = 0, K = 3
Output: 0.125000
Example 2:
Input: N = 4, x = 1, y = 2, k = 4
Output: 0.024414
Your Task:
You don't need to read or print anything. Your task is to complete the function findProb() which takes N, x, y and K as input parameter and returns the probability.
Expected Time Complexity : O(N 3)
Expected Space Complexity: O(N3)
Constraints:
1 <= N <= 100
0 <= x, y <= N
0 <= K <= N
+2
pritamkr2123 days ago
ALL FOUR SOLUTION -→RECURSIVE, MEMOZAITION,TABULATION, SPACE OPTIMAZTION (THANKS STRIVER FOR BEST DP PLAYLIST)
1→ RECURSIVE=>
class Solution
{
static boolean isSafe(int x,int y,int N){
if(x>=0 && x<N && y>=0 && y<N)return true;
return false;
}
private static double solver(int x,int y,int step,int N){
double count=0;
if(isSafe(x,y,N)){
if(step==0)return 1;
count+= solver(x-2, y+1, step-1,N);
count+= solver(x-2, y-1, step-1,N);
count+= solver(x-1, y+2, step-1,N);
count+= solver(x-1, y-2, step-1,N);
count+= solver(x+1, y+2, step-1,N);
count+= solver(x+1, y-2, step-1,N);
count+= solver(x+2, y+1, step-1,N);
count+= solver(x+2, y-1, step-1,N);
}
return count;
}
public double findProb(int N, int start_x, int start_y, int step)
{
// recursion solution
double count =solver(start_x,start_y,step,N);
return count/Math.pow(8,step);
}
}
2-→ MEMOZATION =>
class Solution
{
static Double[][][]dp;
static boolean isSafe(int x,int y,int N){
if(x>=0 && x<N && y>=0 && y<N)return true;
return false;
}
private static double solver(int x,int y,int step,int N){
double count=0;
if(isSafe(x,y,N)){
if(step==0)return 1;
if(dp[x][y][step]!=null)return dp[x][y][step];
count+= solver(x-2, y+1, step-1,N);
count+= solver(x-2, y-1, step-1,N);
count+= solver(x-1, y+2, step-1,N);
count+= solver(x-1, y-2, step-1,N);
count+= solver(x+1, y+2, step-1,N);
count+= solver(x+1, y-2, step-1,N);
count+= solver(x+2, y+1, step-1,N);
count+= solver(x+2, y-1, step-1,N);
dp[x][y][step]=count;
}
return count;
}
public double findProb(int N, int start_x, int start_y, int step)
{
// memoziation solution
dp=new Double[N][N][step+1];
double count =solver(start_x,start_y,step,N);
return count/Math.pow(8,step);
}
}
3-→ TABULATION=>
class Solution
{
static boolean isSafe(int x,int y,int N){
if(x>=0 && x<N && y>=0 && y<N)return true;
return false;
}
int[][] dirs = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
public double findProb(int n, int start_x, int start_y, int step)
{
// Tabulation solution
double[][][] dp=new double[step+1][n][n];
dp[0][start_x][start_y]=1;
for(int k=1;k<=step;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int[]dir:dirs){
int x=i+dir[0];
int y=j+dir[1];
if(isSafe(x,y,n)){
dp[k][i][j]+=dp[k-1][x][y]/8.0;
}
}
}
}
}
double res=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
res+=dp[step][i][j];
}
}
return res;
}
}
4-→ SPACE OPTIMAZATION=>
class Solution
{
static boolean isSafe(int x,int y,int N){
if(x>=0 && x<N && y>=0 && y<N)return true;
return false;
}
int[][] dirs = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
public double findProb(int n, int start_x, int start_y, int step)
{
// space optimization solution
double[][] prev=new double[n][n];
prev[start_x][start_y]=1;
for(int k=1;k<=step;k++){
double[][]curr=new double[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int[]dir:dirs){
int x=i+dir[0];
int y=j+dir[1];
if(isSafe(x,y,n)){
curr[i][j]+=prev[x][y]/8.0;
}
}
}
}
prev=curr;
}
double res=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
res+=prev[i][j];
}
}
return res;
}
}
0
eren08Premium3 days ago
bool isValid(int ni, int nj, int n)
{
return ni >= 0 && ni < n && nj >= 0 && nj < n;
}
double findProb(int N, int start_x, int start_y, int steps)
{
vector<vector<double>> curr(N, vector<double>(N, 0.0)), next(N, vector<double>(N, 0.0));
double ans = 0.0;
curr[start_x][start_y] = 1.0;
for (int m = 1; m <= steps; m++)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (curr[i][j] != 0.0)
{
int ni = 0, nj = 0;
ni = i - 2;
nj = j + 1;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
ni = i - 1;
nj = j + 2;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
ni = i + 1;
nj = j + 2;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
ni = i + 2;
nj = j + 1;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
ni = i - 1;
nj = j - 2;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
ni = i + 1;
nj = j - 2;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
ni = i + 2;
nj = j - 1;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
ni = i - 2;
nj = j - 1;
if (isValid(ni, nj, N))
next[ni][nj] += curr[i][j] * 0.125;
}
}
}
curr = next;
next = vector<vector<double>>(N, vector<double>(N, 0.0));
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
ans += curr[i][j];
}
}
return ans;
}
+2
kunshmanghwani3 days ago
Easy to understand , using Lru_cache for memoization
from functools import lru_cache
class Solution:
def findProb(self, n, r, c, k):
dir = [(-1,-2),(-2,-1),(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2)]
@lru_cache(None)
def solve(x,y,t):
if not (0<=x<n and 0<=y<n):
return 0
if t==0:
return 1
ans=0
for i,j in dir :
ans+=solve(x+i,y+j,t-1)
return ans
return solve(r,c,k)/8**k
+3
greatwhite3 days ago
C++ solution
class Solution{
public:
double findProb(int N, int x, int y, int steps) {
vector<vector<double>> dp(N, vector<double>(N, 0.0));
dp[x][y] = 1.0;
int X[] = {1, 1, -1, -1, 2, 2, -2, -2};
int Y[] = {2, -2, 2, -2, 1, -1, 1, -1};
while(steps--) {
vector<vector<double>> ndp(N, vector<double>(N, 0.0));
for(int x = 0; x < N; x++) for(int y = 0; y < N; y++) {
for(int k = 0; k < 8; k++) {
int nx = x + X[k];
int ny = y + Y[k];
if(nx >= 0 && ny >= 0 && nx < N && ny < N)
ndp[nx][ny] += dp[x][y] / 8;
}
}
dp = ndp;
}
double ans = 0.0;
for(auto it: dp) ans += accumulate(it.begin(), it.end(), 0.0);
return ans;
}
};
+1
sourav1919sharma3 days ago
class Solution{
public:
bool isValid(int r, int c, int n){
return (r >= 0 and r < n and c >= 0 and c < n);
}
double findProb(int N,int start_x, int start_y, int steps){
vector<vector<double>>curr(N, vector<double>(N, 0.0));
curr[start_x][start_y] = 1.0;
vector<vector<int>>direction = {{2, 1}, {-2, 1}, {2, -1},
{-2, -1}, {1, 2}, {1, -2},
{-1, 2}, {-1, -2}};
for(int step = 1; step <= steps; step++){
vector<vector<double>>next(N, vector<double>(N, 0.0));
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
if(curr[i][j] != 0){
for(auto it: direction){
int nextRow = i + it[0];
int nextCol = j + it[1];
if(isValid(nextRow, nextCol, N)){
next[nextRow][nextCol] +=
curr[i][j] / 8.0;
}
}
}
}
}
curr = next;
}
double prob = 0.0;
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
prob += curr[i][j];
}
}
return prob;
}
};
+2
rajshaurya9883 days ago
C++ Solution. 0.08 secSolution explained visually in YouTube video
double findInBoardCount(int N,int x, int y, int K, vector<vector<vector<double>>>& lookup)
{
double count = 0;
if (x >= 0 && x < N && y >= 0 && y < N) //Inside board
{
if (lookup[x][y][K] != -1)
return lookup[x][y][K];
if (K == 0)
return 1;
//1
count += findInBoardCount(N, x-2, y-1, K-1, lookup);
//2
count += findInBoardCount(N, x-2, y+1, K-1, lookup);
//3
count += findInBoardCount(N, x+2, y-1, K-1, lookup);
//4
count += findInBoardCount(N, x+2, y+1, K-1, lookup);
//5
count += findInBoardCount(N, x-1, y-2, K-1, lookup);
//6
count += findInBoardCount(N, x-1, y+2, K-1, lookup);
//7
count += findInBoardCount(N, x+1, y-2, K-1, lookup);
//8
count += findInBoardCount(N, x+1, y+2, K-1, lookup);
lookup[x][y][K] = count;
}
return count;
}
0
patildhiren443 days ago
JAVA - 0.23 - Tabulation
boolean isValid(int r, int c, int n) {
if (r < 0 || r >= n || c < 0 || c >= n) {
return false;
}
return true;
}
int[][] direction = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
public double findProb(int n, int r, int c, int k)
{
// Code here
double[][][]dp = new double[k+1][n][n];
dp[0][r][c] = 1;
for(int step=1; step<=k; step++){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
for(int[]dir : direction){
int oldrow = i + dir[0];
int oldcol = j + dir[1];
if(isValid(oldrow, oldcol, n)){
dp[step][i][j] += dp[step-1][oldrow][oldcol]/8.0;
}
}
}
}
}
double res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
res += dp[k][i][j];
}
}
return res;
}
0
neeshumaini553 days ago
from functools import lru_cache
class Solution:
def findProb(self, n, r, c, k):
@lru_cache(None)
def helper(x,y,total):
if not (0<=x<n and 0<=y<n): return 0
if total==0: return 1
res=0
for addX,addY in [(-1,-2),(-2,-1),(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2)]:
res+=helper(x+addX,y+addY,total-1)
return res
return helper(r,c,k)/8**k
0
neeshumaini553 days ago
#f[r][c][steps]= ∑f[r+dr][c+dc][steps−1]/8.0
def findProb(self, N, r, c, K):
dp = [[0] * N for _ in range(N)]
dp[r][c] = 1
for _ in range(K):
dp2 = [[0] * N for _ in range(N)]
for r, row in enumerate(dp):
for c, val in enumerate(row):
for dr, dc in ((2,1),(2,-1),(-2,1),(-2,-1),
(1,2),(1,-2),(-1,2),(-1,-2)):
if 0 <= r + dr < N and 0 <= c + dc < N:
dp2[r+dr][c+dc] += val / 8.0
dp = dp2
return sum(map(sum, dp))
+1
sskanojiya165Premium3 days ago
My C++ Solution:
bool isSafe(int x, int y, int n) {
if(x >= 0 && x < n && y >= 0 && y < n) return true;
else return false;
}
double solve(int i , int j, int n, int k, vector<vector<vector<double>>> &dp) {
pair<int,int> dir[] = {{-2,-1}, {-2,1}, {-1,-2}, {1, -2}, {2,-1}, {2,1}, {1,2}, {-1,2}};
if(k == 0){
return 1;
}
if(dp[i][j][k] != -1)
return dp[i][j][k];
double ans = 0;
for(int d = 0; d < 8; d++) {
int p = i + dir[d].first;
int q = j + dir[d].second;
if(isSafe(p,q,n)) {
ans += (solve(p,q,n,k-1,dp)/8);
}
}
dp[i][j][k] = (double)ans;
return (double)dp[i][j][k];
}
double findProb(int n,int x, int y, int steps)
{
vector<vector<vector<double>>>
dp(n, vector<vector<double>>(n, vector<double>(steps+1, -1)));
return solve(x, y, n, steps, dp);
}
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": 570,
"s": 238,
"text": "Given an NxN chessboard and a Knight at position (x, y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. Find the probability that the Knight remains in the chessboard after taking K steps, with the condition that it cant enter the board again once it leaves it.\n "
},
{
"code": null,
"e": 581,
"s": 570,
"text": "Example 1:"
},
{
"code": null,
"e": 634,
"s": 581,
"text": "Input : N = 8, x = 0, y = 0, K = 3\nOutput: 0.125000\n"
},
{
"code": null,
"e": 645,
"s": 634,
"text": "Example 2:"
},
{
"code": null,
"e": 697,
"s": 645,
"text": "Input: N = 4, x = 1, y = 2, k = 4\nOutput: 0.024414\n"
},
{
"code": null,
"e": 878,
"s": 699,
"text": "Your Task: \nYou don't need to read or print anything. Your task is to complete the function findProb() which takes N, x, y and K as input parameter and returns the probability.\n "
},
{
"code": null,
"e": 947,
"s": 878,
"text": "Expected Time Complexity : O(N 3)\nExpected Space Complexity: O(N3)\n "
},
{
"code": null,
"e": 989,
"s": 947,
"text": "Constraints:\n1 <= N <= 100\n0 <= x, y <= N"
},
{
"code": null,
"e": 1001,
"s": 989,
"text": "0 <= K <= N"
},
{
"code": null,
"e": 1004,
"s": 1001,
"text": "+2"
},
{
"code": null,
"e": 1026,
"s": 1004,
"text": "pritamkr2123 days ago"
},
{
"code": null,
"e": 1137,
"s": 1026,
"text": "ALL FOUR SOLUTION -→RECURSIVE, MEMOZAITION,TABULATION, SPACE OPTIMAZTION (THANKS STRIVER FOR BEST DP PLAYLIST)"
},
{
"code": null,
"e": 1153,
"s": 1137,
"text": " 1→ RECURSIVE=>"
},
{
"code": null,
"e": 2088,
"s": 1153,
"text": "class Solution\n{\n static boolean isSafe(int x,int y,int N){\n if(x>=0 && x<N && y>=0 && y<N)return true;\n return false;\n }\n private static double solver(int x,int y,int step,int N){\n double count=0;\n if(isSafe(x,y,N)){\n if(step==0)return 1;\n count+= solver(x-2, y+1, step-1,N);\n count+= solver(x-2, y-1, step-1,N);\n count+= solver(x-1, y+2, step-1,N);\n count+= solver(x-1, y-2, step-1,N);\n count+= solver(x+1, y+2, step-1,N);\n count+= solver(x+1, y-2, step-1,N);\n count+= solver(x+2, y+1, step-1,N);\n count+= solver(x+2, y-1, step-1,N);\n }\n return count;\n }\n \n public double findProb(int N, int start_x, int start_y, int step)\n {\n // recursion solution\n \n double count =solver(start_x,start_y,step,N);\n return count/Math.pow(8,step);\n \n }\n}"
},
{
"code": null,
"e": 2109,
"s": 2090,
"text": " 2-→ MEMOZATION =>"
},
{
"code": null,
"e": 3196,
"s": 2111,
"text": "class Solution\n{\n static Double[][][]dp;\n static boolean isSafe(int x,int y,int N){\n if(x>=0 && x<N && y>=0 && y<N)return true;\n return false;\n }\n private static double solver(int x,int y,int step,int N){\n double count=0;\n if(isSafe(x,y,N)){\n if(step==0)return 1;\n if(dp[x][y][step]!=null)return dp[x][y][step];\n count+= solver(x-2, y+1, step-1,N);\n count+= solver(x-2, y-1, step-1,N);\n count+= solver(x-1, y+2, step-1,N);\n count+= solver(x-1, y-2, step-1,N);\n count+= solver(x+1, y+2, step-1,N);\n count+= solver(x+1, y-2, step-1,N);\n count+= solver(x+2, y+1, step-1,N);\n count+= solver(x+2, y-1, step-1,N);\n dp[x][y][step]=count;\n }\n return count;\n }\n \n public double findProb(int N, int start_x, int start_y, int step)\n {\n // memoziation solution\n dp=new Double[N][N][step+1];\n double count =solver(start_x,start_y,step,N);\n return count/Math.pow(8,step);\n \n }\n}"
},
{
"code": null,
"e": 3214,
"s": 3196,
"text": " 3-→ TABULATION=>"
},
{
"code": null,
"e": 4241,
"s": 3216,
"text": "\nclass Solution\n{\n static boolean isSafe(int x,int y,int N){\n if(x>=0 && x<N && y>=0 && y<N)return true;\n return false;\n }\n \n int[][] dirs = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};\n \n public double findProb(int n, int start_x, int start_y, int step)\n {\n // Tabulation solution\n double[][][] dp=new double[step+1][n][n];\n dp[0][start_x][start_y]=1;\n for(int k=1;k<=step;k++){\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n for(int[]dir:dirs){\n int x=i+dir[0];\n int y=j+dir[1];\n if(isSafe(x,y,n)){\n dp[k][i][j]+=dp[k-1][x][y]/8.0;\n }\n }\n }\n }\n }\n \n double res=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n res+=dp[step][i][j];\n }\n }\n return res;\n \n }\n}"
},
{
"code": null,
"e": 4269,
"s": 4243,
"text": " 4-→ SPACE OPTIMAZATION=>"
},
{
"code": null,
"e": 5353,
"s": 4271,
"text": "\nclass Solution\n{\n static boolean isSafe(int x,int y,int N){\n if(x>=0 && x<N && y>=0 && y<N)return true;\n return false;\n }\n \n int[][] dirs = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};\n \n public double findProb(int n, int start_x, int start_y, int step)\n {\n // space optimization solution\n double[][] prev=new double[n][n];\n prev[start_x][start_y]=1;\n for(int k=1;k<=step;k++){\n double[][]curr=new double[n][n];\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n for(int[]dir:dirs){\n int x=i+dir[0];\n int y=j+dir[1];\n if(isSafe(x,y,n)){\n curr[i][j]+=prev[x][y]/8.0;\n }\n }\n }\n }\n prev=curr;\n }\n \n double res=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n res+=prev[i][j];\n }\n }\n return res;\n \n }\n}"
},
{
"code": null,
"e": 5355,
"s": 5353,
"text": "0"
},
{
"code": null,
"e": 5379,
"s": 5355,
"text": "eren08Premium3 days ago"
},
{
"code": null,
"e": 7809,
"s": 5379,
"text": " bool isValid(int ni, int nj, int n)\n {\n return ni >= 0 && ni < n && nj >= 0 && nj < n;\n }\n double findProb(int N, int start_x, int start_y, int steps)\n {\n vector<vector<double>> curr(N, vector<double>(N, 0.0)), next(N, vector<double>(N, 0.0));\n double ans = 0.0;\n curr[start_x][start_y] = 1.0;\n for (int m = 1; m <= steps; m++)\n {\n for (int i = 0; i < N; i++)\n {\n for (int j = 0; j < N; j++)\n {\n if (curr[i][j] != 0.0)\n {\n int ni = 0, nj = 0;\n ni = i - 2;\n nj = j + 1;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n ni = i - 1;\n nj = j + 2;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n ni = i + 1;\n nj = j + 2;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n ni = i + 2;\n nj = j + 1;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n ni = i - 1;\n nj = j - 2;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n ni = i + 1;\n nj = j - 2;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n ni = i + 2;\n nj = j - 1;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n ni = i - 2;\n nj = j - 1;\n if (isValid(ni, nj, N))\n next[ni][nj] += curr[i][j] * 0.125;\n }\n }\n }\n curr = next;\n next = vector<vector<double>>(N, vector<double>(N, 0.0));\n }\n for (int i = 0; i < N; i++)\n {\n for (int j = 0; j < N; j++)\n {\n ans += curr[i][j];\n }\n }\n return ans;\n }"
},
{
"code": null,
"e": 7812,
"s": 7809,
"text": "+2"
},
{
"code": null,
"e": 7837,
"s": 7812,
"text": "kunshmanghwani3 days ago"
},
{
"code": null,
"e": 7891,
"s": 7837,
"text": "Easy to understand , using Lru_cache for memoization "
},
{
"code": null,
"e": 8351,
"s": 7893,
"text": "from functools import lru_cache\nclass Solution:\n\tdef findProb(self, n, r, c, k):\n\t dir = [(-1,-2),(-2,-1),(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2)]\n\t\t@lru_cache(None)\n def solve(x,y,t):\n if not (0<=x<n and 0<=y<n):\n return 0\n if t==0:\n return 1\n ans=0\n for i,j in dir :\n ans+=solve(x+i,y+j,t-1)\n return ans\n \n return solve(r,c,k)/8**k"
},
{
"code": null,
"e": 8354,
"s": 8351,
"text": "+3"
},
{
"code": null,
"e": 8375,
"s": 8354,
"text": "greatwhite3 days ago"
},
{
"code": null,
"e": 8388,
"s": 8375,
"text": "C++ solution"
},
{
"code": null,
"e": 9228,
"s": 8388,
"text": "class Solution{\n\tpublic:\n\tdouble findProb(int N, int x, int y, int steps) {\n\t vector<vector<double>> dp(N, vector<double>(N, 0.0));\n\t dp[x][y] = 1.0;\n\t \n\t int X[] = {1, 1, -1, -1, 2, 2, -2, -2};\n\t int Y[] = {2, -2, 2, -2, 1, -1, 1, -1};\n\t \n\t while(steps--) {\n\t vector<vector<double>> ndp(N, vector<double>(N, 0.0));\n\t for(int x = 0; x < N; x++) for(int y = 0; y < N; y++) {\n\t for(int k = 0; k < 8; k++) {\n\t int nx = x + X[k];\n\t int ny = y + Y[k];\n\t \n\t if(nx >= 0 && ny >= 0 && nx < N && ny < N) \n\t ndp[nx][ny] += dp[x][y] / 8;\n\t }\n\t }\n\t \n\t dp = ndp;\n\t }\n\t \n\t double ans = 0.0;\n\t for(auto it: dp) ans += accumulate(it.begin(), it.end(), 0.0);\n\t \n\t return ans;\n\t}\n};"
},
{
"code": null,
"e": 9231,
"s": 9228,
"text": "+1"
},
{
"code": null,
"e": 9258,
"s": 9231,
"text": "sourav1919sharma3 days ago"
},
{
"code": null,
"e": 10629,
"s": 9258,
"text": "class Solution{\n\tpublic:\n\tbool isValid(int r, int c, int n){\n\t return (r >= 0 and r < n and c >= 0 and c < n);\n\t}\n\t\n\tdouble findProb(int N,int start_x, int start_y, int steps){\n\t vector<vector<double>>curr(N, vector<double>(N, 0.0));\n\t curr[start_x][start_y] = 1.0;\n\t \n\t vector<vector<int>>direction = {{2, 1}, {-2, 1}, {2, -1}, \n\t \t\t\t\t\t\t\t\t{-2, -1}, {1, 2}, {1, -2}, \n\t \t\t\t\t\t\t\t\t {-1, 2}, {-1, -2}};\n\t \n\t for(int step = 1; step <= steps; step++){\n\t vector<vector<double>>next(N, vector<double>(N, 0.0));\n\t for(int i = 0; i < N; i++){\n\t for(int j = 0; j < N; j++){\n\t \n\t if(curr[i][j] != 0){\n\t \n \t for(auto it: direction){\n \t int nextRow = i + it[0];\n \t int nextCol = j + it[1];\n \t \n \t if(isValid(nextRow, nextCol, N)){\n \t next[nextRow][nextCol] += \n \t \t\t\tcurr[i][j] / 8.0;\n \t }\n \t }\n \t \n\t }\n\t \n\t }\n\t }\n\t curr = next;\n\t }\n\t \n\t double prob = 0.0;\n\t for(int i = 0; i < N; i++){\n\t for(int j = 0; j < N; j++){\n\t prob += curr[i][j];\n\t }\n\t }\n\t \n\t return prob;\n\t}\n};"
},
{
"code": null,
"e": 10632,
"s": 10629,
"text": "+2"
},
{
"code": null,
"e": 10656,
"s": 10632,
"text": "rajshaurya9883 days ago"
},
{
"code": null,
"e": 10723,
"s": 10656,
"text": "C++ Solution. 0.08 secSolution explained visually in YouTube video"
},
{
"code": null,
"e": 11672,
"s": 10723,
"text": "double findInBoardCount(int N,int x, int y, int K, vector<vector<vector<double>>>& lookup)\n{\n double count = 0;\n if (x >= 0 && x < N && y >= 0 && y < N) //Inside board\n {\n if (lookup[x][y][K] != -1)\n return lookup[x][y][K];\n \n if (K == 0)\n return 1;\n //1\n count += findInBoardCount(N, x-2, y-1, K-1, lookup);\n //2\n count += findInBoardCount(N, x-2, y+1, K-1, lookup);\n //3\n count += findInBoardCount(N, x+2, y-1, K-1, lookup);\n //4\n count += findInBoardCount(N, x+2, y+1, K-1, lookup);\n //5\n count += findInBoardCount(N, x-1, y-2, K-1, lookup);\n //6\n count += findInBoardCount(N, x-1, y+2, K-1, lookup);\n //7\n count += findInBoardCount(N, x+1, y-2, K-1, lookup);\n //8\n count += findInBoardCount(N, x+1, y+2, K-1, lookup);\n lookup[x][y][K] = count;\n }\n return count;\n}"
},
{
"code": null,
"e": 11674,
"s": 11672,
"text": "0"
},
{
"code": null,
"e": 11698,
"s": 11674,
"text": "patildhiren443 days ago"
},
{
"code": null,
"e": 11723,
"s": 11698,
"text": "JAVA - 0.23 - Tabulation"
},
{
"code": null,
"e": 12889,
"s": 11723,
"text": "boolean isValid(int r, int c, int n) {\n if (r < 0 || r >= n || c < 0 || c >= n) {\n return false;\n }\n return true;\n }\n\n int[][] direction = {{2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};\n\n \n public double findProb(int n, int r, int c, int k)\n {\n // Code here\n double[][][]dp = new double[k+1][n][n];\n \n dp[0][r][c] = 1;\n \n for(int step=1; step<=k; step++){\n for(int i=0; i<n; i++){\n for(int j=0; j<n; j++){\n \n for(int[]dir : direction){\n int oldrow = i + dir[0];\n int oldcol = j + dir[1];\n \n if(isValid(oldrow, oldcol, n)){\n dp[step][i][j] += dp[step-1][oldrow][oldcol]/8.0;\n }\n }\n }\n }\n }\n \n double res = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n\n res += dp[k][i][j];\n }\n }\n\n return res;\n }"
},
{
"code": null,
"e": 12891,
"s": 12889,
"text": "0"
},
{
"code": null,
"e": 12915,
"s": 12891,
"text": "neeshumaini553 days ago"
},
{
"code": null,
"e": 13355,
"s": 12915,
"text": "from functools import lru_cache\nclass Solution:\n\tdef findProb(self, n, r, c, k):\n\t @lru_cache(None)\n def helper(x,y,total):\n if not (0<=x<n and 0<=y<n): return 0\n if total==0: return 1\n res=0\n for addX,addY in [(-1,-2),(-2,-1),(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2)]:\n res+=helper(x+addX,y+addY,total-1)\n return res\n \n return helper(r,c,k)/8**k"
},
{
"code": null,
"e": 13357,
"s": 13355,
"text": "0"
},
{
"code": null,
"e": 13381,
"s": 13357,
"text": "neeshumaini553 days ago"
},
{
"code": null,
"e": 13979,
"s": 13381,
"text": "#f[r][c][steps]= ∑f[r+dr][c+dc][steps−1]/8.0\n\ndef findProb(self, N, r, c, K):\n\tdp = [[0] * N for _ in range(N)]\n dp[r][c] = 1\n for _ in range(K):\n dp2 = [[0] * N for _ in range(N)]\n for r, row in enumerate(dp):\n for c, val in enumerate(row):\n for dr, dc in ((2,1),(2,-1),(-2,1),(-2,-1),\n (1,2),(1,-2),(-1,2),(-1,-2)):\n if 0 <= r + dr < N and 0 <= c + dc < N:\n dp2[r+dr][c+dc] += val / 8.0\n dp = dp2\n\n return sum(map(sum, dp))"
},
{
"code": null,
"e": 13982,
"s": 13979,
"text": "+1"
},
{
"code": null,
"e": 14013,
"s": 13982,
"text": "sskanojiya165Premium3 days ago"
},
{
"code": null,
"e": 14030,
"s": 14013,
"text": "My C++ Solution:"
},
{
"code": null,
"e": 15033,
"s": 14030,
"text": "bool isSafe(int x, int y, int n) {\n if(x >= 0 && x < n && y >= 0 && y < n) return true;\n else return false;\n }\n \n\tdouble solve(int i , int j, int n, int k, vector<vector<vector<double>>> &dp) {\n\t pair<int,int> dir[] = {{-2,-1}, {-2,1}, {-1,-2}, {1, -2}, {2,-1}, {2,1}, {1,2}, {-1,2}};\n\t \n\t if(k == 0){\n return 1;\n }\n \n if(dp[i][j][k] != -1)\n return dp[i][j][k];\n \n double ans = 0;\n \n for(int d = 0; d < 8; d++) {\n int p = i + dir[d].first;\n int q = j + dir[d].second;\n \n if(isSafe(p,q,n)) {\n ans += (solve(p,q,n,k-1,dp)/8);\n }\n }\n \n dp[i][j][k] = (double)ans;\n \n return (double)dp[i][j][k];\n\t}\n\t\n\t\n\tdouble findProb(int n,int x, int y, int steps)\n\t{\n\t vector<vector<vector<double>>> \n\t dp(n, vector<vector<double>>(n, vector<double>(steps+1, -1)));\n\t \n\t return solve(x, y, n, steps, dp);\n\t}"
},
{
"code": null,
"e": 15179,
"s": 15033,
"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": 15215,
"s": 15179,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 15225,
"s": 15215,
"text": "\nProblem\n"
},
{
"code": null,
"e": 15235,
"s": 15225,
"text": "\nContest\n"
},
{
"code": null,
"e": 15298,
"s": 15235,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 15446,
"s": 15298,
"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": 15654,
"s": 15446,
"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": 15760,
"s": 15654,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Android - Application Components | Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.
There are following four main components that can be used within an Android application −
Activities
They dictate the UI and handle the user interaction to the smart phone screen.
Services
They handle background processing associated with an application.
Broadcast Receivers
They handle communication between Android OS and applications.
Content Providers
They handle data and database management issues.
An activity represents a single screen with a user interface,in-short Activity performs actions on the screen. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −
public class MainActivity extends Activity {
}
A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows −
public class MyService extends Service {
}
Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}
A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}
We will go through these tags in detail while covering application components in individual chapters.
There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are −
Fragments
Represents a portion of user interface in an Activity.
Views
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
View hierarchies that control screen format and appearance of the views.
Intents
Messages wiring components together.
Resources
External elements, such as strings, constants and drawable pictures.
Manifest
Configuration file for the application.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3853,
"s": 3607,
"text": "Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact."
},
{
"code": null,
"e": 3944,
"s": 3853,
"text": "There are following four main components that can be used within an Android application −"
},
{
"code": null,
"e": 3955,
"s": 3944,
"text": "Activities"
},
{
"code": null,
"e": 4034,
"s": 3955,
"text": "They dictate the UI and handle the user interaction to the smart phone screen."
},
{
"code": null,
"e": 4043,
"s": 4034,
"text": "Services"
},
{
"code": null,
"e": 4109,
"s": 4043,
"text": "They handle background processing associated with an application."
},
{
"code": null,
"e": 4129,
"s": 4109,
"text": "Broadcast Receivers"
},
{
"code": null,
"e": 4192,
"s": 4129,
"text": "They handle communication between Android OS and applications."
},
{
"code": null,
"e": 4210,
"s": 4192,
"text": "Content Providers"
},
{
"code": null,
"e": 4259,
"s": 4210,
"text": "They handle data and database management issues."
},
{
"code": null,
"e": 4688,
"s": 4259,
"text": "An activity represents a single screen with a user interface,in-short Activity performs actions on the screen. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched."
},
{
"code": null,
"e": 4760,
"s": 4688,
"text": "An activity is implemented as a subclass of Activity class as follows −"
},
{
"code": null,
"e": 4807,
"s": 4760,
"text": "public class MainActivity extends Activity {\n}"
},
{
"code": null,
"e": 5092,
"s": 4807,
"text": "A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity."
},
{
"code": null,
"e": 5161,
"s": 5092,
"text": "A service is implemented as a subclass of Service class as follows −"
},
{
"code": null,
"e": 5204,
"s": 5161,
"text": "public class MyService extends Service {\n}"
},
{
"code": null,
"e": 5580,
"s": 5204,
"text": "Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action."
},
{
"code": null,
"e": 5710,
"s": 5580,
"text": "A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcaster as an Intent object."
},
{
"code": null,
"e": 5809,
"s": 5710,
"text": "public class MyReceiver extends BroadcastReceiver {\n public void onReceive(context,intent){}\n}"
},
{
"code": null,
"e": 6050,
"s": 5809,
"text": "A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely."
},
{
"code": null,
"e": 6221,
"s": 6050,
"text": "A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions."
},
{
"code": null,
"e": 6309,
"s": 6221,
"text": "public class MyContentProvider extends ContentProvider {\n public void onCreate(){}\n}"
},
{
"code": null,
"e": 6411,
"s": 6309,
"text": "We will go through these tags in detail while covering application components in individual chapters."
},
{
"code": null,
"e": 6572,
"s": 6411,
"text": "There are additional components which will be used in the construction of above mentioned entities, their logic, and wiring between them. These components are −"
},
{
"code": null,
"e": 6582,
"s": 6572,
"text": "Fragments"
},
{
"code": null,
"e": 6637,
"s": 6582,
"text": "Represents a portion of user interface in an Activity."
},
{
"code": null,
"e": 6643,
"s": 6637,
"text": "Views"
},
{
"code": null,
"e": 6716,
"s": 6643,
"text": "UI elements that are drawn on-screen including buttons, lists forms etc."
},
{
"code": null,
"e": 6724,
"s": 6716,
"text": "Layouts"
},
{
"code": null,
"e": 6797,
"s": 6724,
"text": "View hierarchies that control screen format and appearance of the views."
},
{
"code": null,
"e": 6805,
"s": 6797,
"text": "Intents"
},
{
"code": null,
"e": 6842,
"s": 6805,
"text": "Messages wiring components together."
},
{
"code": null,
"e": 6852,
"s": 6842,
"text": "Resources"
},
{
"code": null,
"e": 6921,
"s": 6852,
"text": "External elements, such as strings, constants and drawable pictures."
},
{
"code": null,
"e": 6930,
"s": 6921,
"text": "Manifest"
},
{
"code": null,
"e": 6970,
"s": 6930,
"text": "Configuration file for the application."
},
{
"code": null,
"e": 7005,
"s": 6970,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7017,
"s": 7005,
"text": " Aditya Dua"
},
{
"code": null,
"e": 7052,
"s": 7017,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7066,
"s": 7052,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 7098,
"s": 7066,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7115,
"s": 7098,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7150,
"s": 7115,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7167,
"s": 7150,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7202,
"s": 7167,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7219,
"s": 7202,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7252,
"s": 7219,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7269,
"s": 7252,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7276,
"s": 7269,
"text": " Print"
},
{
"code": null,
"e": 7287,
"s": 7276,
"text": " Add Notes"
}
]
|
Count words in a given string in C++ | We are given with a sentence or string containing words that can contain spaces, new line characters and tab characters in between. The task is to calculate the total number of words in a string and print the result.
Input − string str = “welcome to\n tutorials point\t”
Output − Count of words in a string are − 4
Explanation − There are four words in a string i.e. welcome, to, tutorials, point and the rest are spaces(“ ”), next line character(\n) and tab character(\t) present between the words.
Input − string str = “\nhonesty\t is the best policy”
Output − Count of words in a string are − 5
Explanation − There are four words in a string i.e. honesty, is, the, best, policy and the rest are spaces(“ ”), next line character(\n) and tab character(\t) present between the words.
There can be multiple solutions for this. So let’s first look at the simpler approach we had used in the below code −
Create an array of char type for storing the string let’s say, str[]
Create an array of char type for storing the string let’s say, str[]
Declare two temporary variable one is count to count the number of words in a string and temp to perform the flag operations
Declare two temporary variable one is count to count the number of words in a string and temp to perform the flag operations
Start loop While str is not null
Start loop While str is not null
Inside the loop, check IF *str = space OR *str = next line OR *str = tab then set temp to 0
Inside the loop, check IF *str = space OR *str = next line OR *str = tab then set temp to 0
Else If temp = 0 then set temp to 1 and increment the value of count by 1
Else If temp = 0 then set temp to 1 and increment the value of count by 1
Increment the str pointer by 1
Increment the str pointer by 1
Return the value in count
Return the value in count
Print the result
Print the result
Live Demo
#include
using namespace std;
//count words in a given string
int total_words(char *str){
int count = 0;
int temp = 0;
while (*str){
if (*str == ' ' || *str == '\n' || *str == '\t'){
temp = 0;
}
else if(temp == 0){
temp = 1;
count++;
}
++str;
}
return count;
}
int main(){
char str[] = "welcome to\n tutorials point\t";
cout<<"Count of words in a string are: "<<total_words(str);
return 0;
}
If we run the above code it will generate the following output −
Count of words in a string are: 4 | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "We are given with a sentence or string containing words that can contain spaces, new line characters and tab characters in between. The task is to calculate the total number of words in a string and print the result."
},
{
"code": null,
"e": 1333,
"s": 1279,
"text": "Input − string str = “welcome to\\n tutorials point\\t”"
},
{
"code": null,
"e": 1377,
"s": 1333,
"text": "Output − Count of words in a string are − 4"
},
{
"code": null,
"e": 1562,
"s": 1377,
"text": "Explanation − There are four words in a string i.e. welcome, to, tutorials, point and the rest are spaces(“ ”), next line character(\\n) and tab character(\\t) present between the words."
},
{
"code": null,
"e": 1616,
"s": 1562,
"text": "Input − string str = “\\nhonesty\\t is the best policy”"
},
{
"code": null,
"e": 1660,
"s": 1616,
"text": "Output − Count of words in a string are − 5"
},
{
"code": null,
"e": 1846,
"s": 1660,
"text": "Explanation − There are four words in a string i.e. honesty, is, the, best, policy and the rest are spaces(“ ”), next line character(\\n) and tab character(\\t) present between the words."
},
{
"code": null,
"e": 1964,
"s": 1846,
"text": "There can be multiple solutions for this. So let’s first look at the simpler approach we had used in the below code −"
},
{
"code": null,
"e": 2033,
"s": 1964,
"text": "Create an array of char type for storing the string let’s say, str[]"
},
{
"code": null,
"e": 2102,
"s": 2033,
"text": "Create an array of char type for storing the string let’s say, str[]"
},
{
"code": null,
"e": 2227,
"s": 2102,
"text": "Declare two temporary variable one is count to count the number of words in a string and temp to perform the flag operations"
},
{
"code": null,
"e": 2352,
"s": 2227,
"text": "Declare two temporary variable one is count to count the number of words in a string and temp to perform the flag operations"
},
{
"code": null,
"e": 2385,
"s": 2352,
"text": "Start loop While str is not null"
},
{
"code": null,
"e": 2418,
"s": 2385,
"text": "Start loop While str is not null"
},
{
"code": null,
"e": 2510,
"s": 2418,
"text": "Inside the loop, check IF *str = space OR *str = next line OR *str = tab then set temp to 0"
},
{
"code": null,
"e": 2602,
"s": 2510,
"text": "Inside the loop, check IF *str = space OR *str = next line OR *str = tab then set temp to 0"
},
{
"code": null,
"e": 2676,
"s": 2602,
"text": "Else If temp = 0 then set temp to 1 and increment the value of count by 1"
},
{
"code": null,
"e": 2750,
"s": 2676,
"text": "Else If temp = 0 then set temp to 1 and increment the value of count by 1"
},
{
"code": null,
"e": 2781,
"s": 2750,
"text": "Increment the str pointer by 1"
},
{
"code": null,
"e": 2812,
"s": 2781,
"text": "Increment the str pointer by 1"
},
{
"code": null,
"e": 2838,
"s": 2812,
"text": "Return the value in count"
},
{
"code": null,
"e": 2864,
"s": 2838,
"text": "Return the value in count"
},
{
"code": null,
"e": 2881,
"s": 2864,
"text": "Print the result"
},
{
"code": null,
"e": 2898,
"s": 2881,
"text": "Print the result"
},
{
"code": null,
"e": 2909,
"s": 2898,
"text": " Live Demo"
},
{
"code": null,
"e": 3382,
"s": 2909,
"text": "#include\nusing namespace std;\n//count words in a given string\nint total_words(char *str){\n int count = 0;\n int temp = 0;\n while (*str){\n if (*str == ' ' || *str == '\\n' || *str == '\\t'){\n temp = 0;\n }\n else if(temp == 0){\n temp = 1;\n count++;\n }\n ++str;\n }\n return count;\n}\nint main(){\n char str[] = \"welcome to\\n tutorials point\\t\";\n cout<<\"Count of words in a string are: \"<<total_words(str);\n return 0;\n}"
},
{
"code": null,
"e": 3447,
"s": 3382,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3481,
"s": 3447,
"text": "Count of words in a string are: 4"
}
]
|
StringWriter vs StringReader in C#? | StringReader and StringWriter derive from TextReader and TextWriter
StringWriter is used for writing into a string buffer. It implements a TextWriter for writing information to a string.
For StringWriter −
StringWriter sWriter = new StringWriter();
while(true) {
myChar = strReader.Read();
if(myChar == -1) break;
convertedChar = Convert.ToChar(myChar);
if(convertedChar == '.') {
strWriter.Write(".\n\n");
sReader.Read();
sReader.Read();
}else {
sWriter.Write(convertedChar);
}
}
}
StringReader to read a string −
StringBuilder sbuilder = new StringBuilder();
// append
sbuilder.AppendLine("Line one characters");
sbuilder.AppendLine("Line two characters");
sbuilder.AppendLine("Line three characters");
// read string
using (StringReader sReader = new StringReader(sbuilder.ToString())) {
string readString = await sReader.ReadToEndAsync();
Console.WriteLine(readString);
} | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "StringReader and StringWriter derive from TextReader and TextWriter"
},
{
"code": null,
"e": 1249,
"s": 1130,
"text": "StringWriter is used for writing into a string buffer. It implements a TextWriter for writing information to a string."
},
{
"code": null,
"e": 1268,
"s": 1249,
"text": "For StringWriter −"
},
{
"code": null,
"e": 1589,
"s": 1268,
"text": "StringWriter sWriter = new StringWriter();\nwhile(true) {\n myChar = strReader.Read();\n if(myChar == -1) break;\n\n convertedChar = Convert.ToChar(myChar);\n if(convertedChar == '.') {\n strWriter.Write(\".\\n\\n\");\n\n sReader.Read();\n sReader.Read();\n }else {\n sWriter.Write(convertedChar);\n }\n}\n}"
},
{
"code": null,
"e": 1621,
"s": 1589,
"text": "StringReader to read a string −"
},
{
"code": null,
"e": 1990,
"s": 1621,
"text": "StringBuilder sbuilder = new StringBuilder();\n\n// append\nsbuilder.AppendLine(\"Line one characters\");\nsbuilder.AppendLine(\"Line two characters\");\nsbuilder.AppendLine(\"Line three characters\");\n\n// read string\nusing (StringReader sReader = new StringReader(sbuilder.ToString())) {\n string readString = await sReader.ReadToEndAsync();\n Console.WriteLine(readString);\n}"
}
]
|
Hands-on Web Scraping: Building your Twitter dataset with python and scrapy | by Amit Upreti | Towards Data Science | I get it — You are tired of searching for datasets online for your machine learning project or maybe for analyzing a popular Twitter trend.
Today we will learn how to generate your own custom dataset from Twitter by using hashtag search. According to internetlivestats.com, every second, on average, around 6,000 tweets are tweeted which corresponds to over 350,000 tweets sent per minute and 500 million tweets per day. This makes Twitter an excellent place to get data for your projects as Tweets are an accurate representation of today’s natural language on social media.
Want to skip the post and see the good stuff directly? Here is the Github repo for you
First things first, let’s make sure we follow the policies made by twitter.com for robots to follow while crawling so that we don’t run into any legal issues. This can be found at https://twitter.com/robots.txt
We can see from the User-agent and Allow section(lines 1–4) that Twitter allows all the robots to visit the hashtag and search URLs with a 1-second delay between the crawl requests.
User-agent: *Allow: /hashtag/*?src=Crawl-delay: 1
This assumes that you have some basic knowledge of python and scrapy. If you are interested only in generating your dataset, skip this section and go to the sample crawl section on the GitHub repo.
For searching for tweets we will be using the legacy Twitter website. Let’s try searching for #cat https://mobile.twitter.com/hashtag/cats. We want to use this legacy version for gathering tweets URLs as it loads the data without using javascript which makes our job super easy.
I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.
― Bill Gates
Finding all the tweet URL for our hashtag search — find_tweets( ) function
find_tweets function for scrapy crawler
Explanation: We will find all the tweets URL in the current page using XPaths and crawl these URLs and send the response to our 2nd function parse_tweet ()
tweets = response.xpath('//table[@class="tweet "]/@href').getall() logging.info(f'{len(tweets)} tweets found') for tweet_id in tweets: tweet_id = re.findall("\d+", tweet_id)[-1] tweet_url = 'https://twitter.com/anyuser/status/'+str(tweet_id) yield scrapy.Request(tweet_url, callback=self.parse_tweet)
Now we will find the next URL for Load older Tweets button and crawl it and send the response to our current find_tweets() function. This way our crawler will keep clicking on the Load older Tweet button recursively if it is available on every crawl. This means we will visit all the results pages one by one.
next_page = response.xpath( '//*[@class="w-button-more"]/a/@href').get(default='')logging.info('Next page found:')if next_page != '': next_page = 'https://mobile.twitter.com' + next_page yield scrapy.Request(next_page, callback=self.find_tweets)
Finding all the data from an individual tweet — parse_tweet( ) function
Explanation: Here, we will use the current version of Twitter (example: https://twitter.com/catsfootprint/status/1213603795663491075) as it turns out the current version loads all the data such as no of likes, retweets, comments, and other metadata. Here is a comparison of loading the above tweet in legacy and the current version of twitter.
parse_tweet( ) function
Our dataset will consist of 14 columns which consist of almost all of the data that can be scraped from a tweet. At the moment the crawler doesn’t collect the comments. The dataset will also include the columnshashtags and mentions which are obtained by parsing the tweet text and searching for words with # at the beginning(for finding hashtags) and @ at the beginning (for finding mentions).
A few ways you might want to use this dataset is:
Sentiment analysis for a popular twitter trend
Competitors Analysis (For example one could find and analyze tweets of their competitors)
Build your Database of tweets by hashtags
Analyze a popular trend. For example, one could find and analyze tweets with #globalwarmingto to find out what the opinion of people.
At the moment, we can see that Twitter allows crawling of its content search results — i.e., tweets and hashtags, and that there is no restriction on how many pages we can crawl. Therefore, our crawler is not affected by any kind of rate limit, and we are able to crawl millions of tweets with this simple script using hashtags and tweet search method. To collect a large number of tweets, I would recommend you to use hundreds of hashtags and run the crawler on a VPS server or scrapy cloud to avoid any kind of interruption.
If you have suggestions or find some issues. I welcome you to open an issue or a Pull Request on GitHub. | [
{
"code": null,
"e": 312,
"s": 172,
"text": "I get it — You are tired of searching for datasets online for your machine learning project or maybe for analyzing a popular Twitter trend."
},
{
"code": null,
"e": 747,
"s": 312,
"text": "Today we will learn how to generate your own custom dataset from Twitter by using hashtag search. According to internetlivestats.com, every second, on average, around 6,000 tweets are tweeted which corresponds to over 350,000 tweets sent per minute and 500 million tweets per day. This makes Twitter an excellent place to get data for your projects as Tweets are an accurate representation of today’s natural language on social media."
},
{
"code": null,
"e": 834,
"s": 747,
"text": "Want to skip the post and see the good stuff directly? Here is the Github repo for you"
},
{
"code": null,
"e": 1045,
"s": 834,
"text": "First things first, let’s make sure we follow the policies made by twitter.com for robots to follow while crawling so that we don’t run into any legal issues. This can be found at https://twitter.com/robots.txt"
},
{
"code": null,
"e": 1227,
"s": 1045,
"text": "We can see from the User-agent and Allow section(lines 1–4) that Twitter allows all the robots to visit the hashtag and search URLs with a 1-second delay between the crawl requests."
},
{
"code": null,
"e": 1277,
"s": 1227,
"text": "User-agent: *Allow: /hashtag/*?src=Crawl-delay: 1"
},
{
"code": null,
"e": 1475,
"s": 1277,
"text": "This assumes that you have some basic knowledge of python and scrapy. If you are interested only in generating your dataset, skip this section and go to the sample crawl section on the GitHub repo."
},
{
"code": null,
"e": 1754,
"s": 1475,
"text": "For searching for tweets we will be using the legacy Twitter website. Let’s try searching for #cat https://mobile.twitter.com/hashtag/cats. We want to use this legacy version for gathering tweets URLs as it loads the data without using javascript which makes our job super easy."
},
{
"code": null,
"e": 1849,
"s": 1754,
"text": "I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it."
},
{
"code": null,
"e": 1862,
"s": 1849,
"text": "― Bill Gates"
},
{
"code": null,
"e": 1937,
"s": 1862,
"text": "Finding all the tweet URL for our hashtag search — find_tweets( ) function"
},
{
"code": null,
"e": 1977,
"s": 1937,
"text": "find_tweets function for scrapy crawler"
},
{
"code": null,
"e": 2133,
"s": 1977,
"text": "Explanation: We will find all the tweets URL in the current page using XPaths and crawl these URLs and send the response to our 2nd function parse_tweet ()"
},
{
"code": null,
"e": 2477,
"s": 2133,
"text": "tweets = response.xpath('//table[@class=\"tweet \"]/@href').getall() logging.info(f'{len(tweets)} tweets found') for tweet_id in tweets: tweet_id = re.findall(\"\\d+\", tweet_id)[-1] tweet_url = 'https://twitter.com/anyuser/status/'+str(tweet_id) yield scrapy.Request(tweet_url, callback=self.parse_tweet)"
},
{
"code": null,
"e": 2787,
"s": 2477,
"text": "Now we will find the next URL for Load older Tweets button and crawl it and send the response to our current find_tweets() function. This way our crawler will keep clicking on the Load older Tweet button recursively if it is available on every crawl. This means we will visit all the results pages one by one."
},
{
"code": null,
"e": 3042,
"s": 2787,
"text": "next_page = response.xpath( '//*[@class=\"w-button-more\"]/a/@href').get(default='')logging.info('Next page found:')if next_page != '': next_page = 'https://mobile.twitter.com' + next_page yield scrapy.Request(next_page, callback=self.find_tweets)"
},
{
"code": null,
"e": 3114,
"s": 3042,
"text": "Finding all the data from an individual tweet — parse_tweet( ) function"
},
{
"code": null,
"e": 3458,
"s": 3114,
"text": "Explanation: Here, we will use the current version of Twitter (example: https://twitter.com/catsfootprint/status/1213603795663491075) as it turns out the current version loads all the data such as no of likes, retweets, comments, and other metadata. Here is a comparison of loading the above tweet in legacy and the current version of twitter."
},
{
"code": null,
"e": 3482,
"s": 3458,
"text": "parse_tweet( ) function"
},
{
"code": null,
"e": 3876,
"s": 3482,
"text": "Our dataset will consist of 14 columns which consist of almost all of the data that can be scraped from a tweet. At the moment the crawler doesn’t collect the comments. The dataset will also include the columnshashtags and mentions which are obtained by parsing the tweet text and searching for words with # at the beginning(for finding hashtags) and @ at the beginning (for finding mentions)."
},
{
"code": null,
"e": 3926,
"s": 3876,
"text": "A few ways you might want to use this dataset is:"
},
{
"code": null,
"e": 3973,
"s": 3926,
"text": "Sentiment analysis for a popular twitter trend"
},
{
"code": null,
"e": 4063,
"s": 3973,
"text": "Competitors Analysis (For example one could find and analyze tweets of their competitors)"
},
{
"code": null,
"e": 4105,
"s": 4063,
"text": "Build your Database of tweets by hashtags"
},
{
"code": null,
"e": 4239,
"s": 4105,
"text": "Analyze a popular trend. For example, one could find and analyze tweets with #globalwarmingto to find out what the opinion of people."
},
{
"code": null,
"e": 4766,
"s": 4239,
"text": "At the moment, we can see that Twitter allows crawling of its content search results — i.e., tweets and hashtags, and that there is no restriction on how many pages we can crawl. Therefore, our crawler is not affected by any kind of rate limit, and we are able to crawl millions of tweets with this simple script using hashtags and tweet search method. To collect a large number of tweets, I would recommend you to use hundreds of hashtags and run the crawler on a VPS server or scrapy cloud to avoid any kind of interruption."
}
]
|
How to insert image in database using PHP | Theory of Computation
In this article, you will learn how to insert an image in the database using PHP. In some applications, there may be a requirement to develop for image upload. Database is preferred best to store data and the file system is the best place to store files. For storing an image in a database, we can store the name or path of the image in the database and store the image as a file on the server. So that the web server can easily access it where we want or send it to the visitor.
PHP provides the easiest way for uploading and storing images in the MySQL database and saved the image in a particular location. First, let's create an HTML form that allow users to choose the image file they want to upload. The enctype='multipart/form-data' form attributes allow files to be sent through post.
<form method='post' action='#' enctype='multipart/form-data'>
<div class="form-group">
<input type="file" name="image" >
</div>
<div class="form-group">
<input type='submit' name='submit' value='Upload' class="btn btn-primary">
</div>
</form>
The form looks something like this -
Next, create a database to store files. You can either copy paste this CREATE statement in your database or use your existing one.
CREATE TABLE `image` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`uploaded_on` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Next, we have written the database connection code. Make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name.
$conn = mysqli_connect('hostname', 'username', 'password', 'database');
//Check for connection error
if($conn->connect_error){
die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);
}
Next, we have written code to check the submitted image, valid file extension and insert it into the database. The move_uploaded_file() function of PHP moves an uploaded file to a new destination. It returns TRUE on success, FALSE on failure.
if(isset($_POST['submit'])){
$filename = $_FILES['image']['name'];
// Select file type
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
// valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Upload files and store in database
if(move_uploaded_file($_FILES["image"]["tmp_name"],'upload/'.$filename)){
// Image db insert sql
$insert = "INSERT into image(file_name,uploaded_on,status) values('$filename',now(),1)";
if(mysqli_query($conn, $insert)){
echo 'Data inserted successfully';
}
else{
echo 'Error: '.mysqli_error($conn);
}
}else{
echo 'Error in uploading file - '.$_FILES['image']['name'].'';
}
}
}
Here, we have merged the above code to upload image to the database.
<?php
// database Connection
$conn = mysqli_connect('hostname', 'username', 'password', 'database');
// check for connection error
if($conn->connect_error){
die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);
}
if(isset($_POST['submit'])){
$filename = $_FILES['image']['name'];
// Select file type
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
// valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Upload files and store in database
if(move_uploaded_file($_FILES["image"]["tmp_name"],'upload/'.$filename)){
// Image db insert sql
$insert = "INSERT into image(file_name,uploaded_on,status) values('$filename',now(),1)";
if(mysqli_query($conn, $insert)){
echo 'Data inserted successfully';
}
else{
echo 'Error: '.mysqli_error($conn);
}
}else{
echo 'Error in uploading file - '.$_FILES['image']['name'].'<br/>';
}
}
}
?>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Select Image to Upload</h1>
<form method='post' action='#' enctype='multipart/form-data'>
<div class="form-group">
<input type="file" name="image" id="file" multiple>
</div>
<div class="form-group">
<input type='submit' name='submit' value='Upload' class="btn btn-primary">
</div>
</form>
</div>
</body>
</html>
Jan 3
Stateful vs Stateless
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...
Dec 29
Best programming language to learn in 2021
In this article, we have mentioned the analyzed results of the best programming language for 2021...
In this article, we have mentioned the analyzed results of the best programming language for 2021...
Dec 20
How is Python best for mobile app development?
Python has a set of useful Libraries and Packages that minimize the use of code...
Python has a set of useful Libraries and Packages that minimize the use of code...
July 18
Learn all about Emoji
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...
Jan 10
Data Science Recruitment of Freshers
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...
eTutorialsPoint©Copyright 2016-2022. All Rights Reserved. | [
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 592,
"s": 112,
"text": "In this article, you will learn how to insert an image in the database using PHP. In some applications, there may be a requirement to develop for image upload. Database is preferred best to store data and the file system is the best place to store files. For storing an image in a database, we can store the name or path of the image in the database and store the image as a file on the server. So that the web server can easily access it where we want or send it to the visitor."
},
{
"code": null,
"e": 905,
"s": 592,
"text": "PHP provides the easiest way for uploading and storing images in the MySQL database and saved the image in a particular location. First, let's create an HTML form that allow users to choose the image file they want to upload. The enctype='multipart/form-data' form attributes allow files to be sent through post."
},
{
"code": null,
"e": 1153,
"s": 905,
"text": "<form method='post' action='#' enctype='multipart/form-data'>\n<div class=\"form-group\">\n <input type=\"file\" name=\"image\" >\n</div> \n<div class=\"form-group\"> \n <input type='submit' name='submit' value='Upload' class=\"btn btn-primary\">\n</div> \n</form>"
},
{
"code": null,
"e": 1190,
"s": 1153,
"text": "The form looks something like this -"
},
{
"code": null,
"e": 1321,
"s": 1190,
"text": "Next, create a database to store files. You can either copy paste this CREATE statement in your database or use your existing one."
},
{
"code": null,
"e": 1629,
"s": 1321,
"text": "CREATE TABLE `image` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\n `uploaded_on` datetime NOT NULL,\n `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"
},
{
"code": null,
"e": 1793,
"s": 1629,
"text": "Next, we have written the database connection code. Make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name."
},
{
"code": null,
"e": 2009,
"s": 1793,
"text": "$conn = mysqli_connect('hostname', 'username', 'password', 'database');\n//Check for connection error\nif($conn->connect_error){\n die(\"Error in DB connection: \".$conn->connect_errno.\" : \".$conn->connect_error); \n}"
},
{
"code": null,
"e": 2252,
"s": 2009,
"text": "Next, we have written code to check the submitted image, valid file extension and insert it into the database. The move_uploaded_file() function of PHP moves an uploaded file to a new destination. It returns TRUE on success, FALSE on failure."
},
{
"code": null,
"e": 3010,
"s": 2252,
"text": "if(isset($_POST['submit'])){\n\n\t$filename = $_FILES['image']['name'];\n\t\n\t// Select file type\n\t$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));\n\t\n\t// valid file extensions\n\t$extensions_arr = array(\"jpg\",\"jpeg\",\"png\",\"gif\");\n \n\t// Check extension\n\tif( in_array($imageFileType,$extensions_arr) ){\n \n\t// Upload files and store in database\n\tif(move_uploaded_file($_FILES[\"image\"][\"tmp_name\"],'upload/'.$filename)){\n\t\t// Image db insert sql\n\t\t$insert = \"INSERT into image(file_name,uploaded_on,status) values('$filename',now(),1)\";\n\t\tif(mysqli_query($conn, $insert)){\n\t\t echo 'Data inserted successfully';\n\t\t}\n\t\telse{\n\t\t echo 'Error: '.mysqli_error($conn);\n\t\t}\n\t}else{\n\t\techo 'Error in uploading file - '.$_FILES['image']['name'].'';\n\t}\n\t}\n} "
},
{
"code": null,
"e": 3079,
"s": 3010,
"text": "Here, we have merged the above code to upload image to the database."
},
{
"code": null,
"e": 4673,
"s": 3079,
"text": "<?php \n\n// database Connection\n$conn = mysqli_connect('hostname', 'username', 'password', 'database');\n// check for connection error\nif($conn->connect_error){\n die(\"Error in DB connection: \".$conn->connect_errno.\" : \".$conn->connect_error); \n}\n\nif(isset($_POST['submit'])){\n\n\t$filename = $_FILES['image']['name'];\n\t\n\t// Select file type\n\t$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));\n\t\n\t// valid file extensions\n\t$extensions_arr = array(\"jpg\",\"jpeg\",\"png\",\"gif\");\n \n\t// Check extension\n\tif( in_array($imageFileType,$extensions_arr) ){\n \n\t// Upload files and store in database\n\tif(move_uploaded_file($_FILES[\"image\"][\"tmp_name\"],'upload/'.$filename)){\n\t\t// Image db insert sql\n\t\t$insert = \"INSERT into image(file_name,uploaded_on,status) values('$filename',now(),1)\";\n\t\tif(mysqli_query($conn, $insert)){\n\t\t echo 'Data inserted successfully';\n\t\t}\n\t\telse{\n\t\t echo 'Error: '.mysqli_error($conn);\n\t\t}\n\t}else{\n\t\techo 'Error in uploading file - '.$_FILES['image']['name'].'<br/>';\n\t}\n\t}\n} \n?>\n<html>\n<head>\n\t<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">\n\t<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"></script>\n</head>\n<body>\n<div class=\"container\">\n\t<h1>Select Image to Upload</h1>\n\t<form method='post' action='#' enctype='multipart/form-data'>\n\t<div class=\"form-group\">\n\t <input type=\"file\" name=\"image\" id=\"file\" multiple>\n\t</div> \n\t<div class=\"form-group\"> \n\t <input type='submit' name='submit' value='Upload' class=\"btn btn-primary\">\n\t</div> \n\t</form>\n</div>\t\n</body>\n</html>"
},
{
"code": null,
"e": 4819,
"s": 4673,
"text": "\nJan 3\nStateful vs Stateless\nA Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...\n"
},
{
"code": null,
"e": 4935,
"s": 4819,
"text": "A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities..."
},
{
"code": null,
"e": 5088,
"s": 4935,
"text": "\nDec 29\nBest programming language to learn in 2021\nIn this article, we have mentioned the analyzed results of the best programming language for 2021...\n"
},
{
"code": null,
"e": 5189,
"s": 5088,
"text": "In this article, we have mentioned the analyzed results of the best programming language for 2021..."
},
{
"code": null,
"e": 5328,
"s": 5189,
"text": "\nDec 20\nHow is Python best for mobile app development?\nPython has a set of useful Libraries and Packages that minimize the use of code...\n"
},
{
"code": null,
"e": 5411,
"s": 5328,
"text": "Python has a set of useful Libraries and Packages that minimize the use of code..."
},
{
"code": null,
"e": 5577,
"s": 5411,
"text": "\nJuly 18\nLearn all about Emoji\nIn this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...\n"
},
{
"code": null,
"e": 5711,
"s": 5577,
"text": "In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more..."
},
{
"code": null,
"e": 5878,
"s": 5711,
"text": "\nJan 10\nData Science Recruitment of Freshers\nIn this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...\n"
},
{
"code": null,
"e": 5999,
"s": 5878,
"text": "In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician..."
}
]
|
Program to print the diamond shape - GeeksforGeeks | 08 Apr, 2021
Given a number n, write a program to print a diamond shape with 2n rows.Examples :
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to print diamond shape// with 2n rows#include <bits/stdc++.h>using namespace std; // Prints diamond pattern with 2n rowsvoid printDiamond(int n){ int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0;j < space; j++) cout << " "; // Print i+1 stars for (int j = 0; j <= i; j++) cout << "* "; cout << endl; space--; } // Repeat again in reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) cout << " "; // Print i stars for (int j = 0;j < i;j++) cout << "* "; cout << endl; space++; }} // Driver codeint main(){ printDiamond(5); return 0;} // This is code is contributed// by rathbhupendra
// C program to print// diamond shape with// 2n rows#include<stdio.h> // Prints diamond// pattern with 2n rowsvoid printDiamond(int n){ int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0;j < space; j++) printf(" "); // Print i+1 stars for (int j = 0;j <= i; j++) printf("* "); printf("\n"); space--; } // Repeat again in // reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) printf(" "); // Print i stars for (int j = 0;j < i;j++) printf("* "); printf("\n"); space++; }} // Driver codeint main(){ printDiamond(5); return 0;}
// JAVA Code to print// the diamond shapeimport java.util.*; class GFG{ // Prints diamond pattern // with 2n rows static void printDiamond(int n) { int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) System.out.print(" "); // Print i+1 stars for (int j = 0; j <= i; j++) System.out.print("* "); System.out.print("\n"); space--; } // Repeat again in // reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) System.out.print(" "); // Print i stars for (int j = 0; j < i; j++) System.out.print("* "); System.out.print("\n"); space++; } } // Driver Code public static void main(String[] args) { printDiamond(5); }} // This code is contributed// by Arnav Kr. Mandal.
# Python program to# print Diamond shape # Function to print# Diamond shapedef Diamond(rows): n = 0 for i in range(1, rows + 1): # loop to print spaces for j in range (1, (rows - i) + 1): print(end = " ") # loop to print star while n != (2 * i - 1): print("*", end = "") n = n + 1 n = 0 # line break print() k = 1 n = 1 for i in range(1, rows): # loop to print spaces for j in range (1, k + 1): print(end = " ") k = k + 1 # loop to print star while n <= (2 * (rows - i) - 1): print("*", end = "") n = n + 1 n = 1 print() # Driver Code# number of rows inputrows = 5Diamond(rows)
// C# Code to print// the diamond shapeusing System; class GFG{ // Prints diamond pattern // with 2n rows static void printDiamond(int n) { int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) Console.Write(" "); // Print i+1 stars for (int j = 0; j <= i; j++) Console.Write("* "); Console.Write("\n"); space--; } // Repeat again in // reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) Console.Write(" "); // Print i stars for (int j = 0; j < i; j++) Console.Write("* "); Console.Write("\n"); space++; } } // Driver Code public static void Main() { printDiamond(5); }} // This code is contributed// by Smitha Semwal.
<?php// PHP program to print// diamond shape with// 2n rows // Prints diamond $// pattern with 2n rowsfunction printDiamond($n){ $space = $n - 1; // run loop (parent loop) // till number of rows for ($i = 0; $i < $n; $i++) { // loop for initially space, // before star printing for ($j = 0;$j < $space; $j++) printf(" "); // Print i+1 stars for ($j = 0;$j <= $i; $j++) printf("* "); printf("\n"); $space--; } // Repeat again in // reverse order $space = 0; // run loop (parent loop) // till number of rows for ($i = $n; $i > 0; $i--) { // loop for initially space, // before star printing for ($j = 0; $j < $space; $j++) printf(" "); // Pr$i stars for ($j = 0;$j < $i;$j++) printf("* "); printf("\n"); $space++; }} // Driver code printDiamond(5); // This code is contributed by Anuj_67?>
<script> // JavaScript program to print diamond shape // with 2n rows // Prints diamond pattern with 2n rows function printDiamond(n) { var space = n - 1; // run loop (parent loop) // till number of rows for (var i = 0; i < n; i++) { // loop for initially space, // before star printing for (var j = 0; j < space; j++) document.write(" "); // Print i+1 stars for (var j = 0; j <= i; j++) document.write("*" + " "); document.write("<br>"); space--; } // Repeat again in reverse order space = 0; // run loop (parent loop) // till number of rows for (var i = n; i > 0; i--) { // loop for initially space, // before star printing for (var j = 0; j < space; j++) document.write(" "); // Print i stars for (var j = 0; j < i; j++) document.write("*" + " "); document.write("<br>"); space++; } } // Driver code printDiamond(5); // This code is contributed by rdtank. </script>
Output :
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
This article is contributed by Rahul Singh(Nit KKR). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Smitha Dinesh Semwal
vt_m
rathbhupendra
rdtank
pattern-printing
Python Pattern-printing
C Language
C++
Python
School Programming
pattern-printing
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects | [
{
"code": null,
"e": 24171,
"s": 24143,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 24256,
"s": 24171,
"text": "Given a number n, write a program to print a diamond shape with 2n rows.Examples : "
},
{
"code": null,
"e": 24264,
"s": 24260,
"text": "C++"
},
{
"code": null,
"e": 24266,
"s": 24264,
"text": "C"
},
{
"code": null,
"e": 24271,
"s": 24266,
"text": "Java"
},
{
"code": null,
"e": 24279,
"s": 24271,
"text": "Python3"
},
{
"code": null,
"e": 24282,
"s": 24279,
"text": "C#"
},
{
"code": null,
"e": 24286,
"s": 24282,
"text": "PHP"
},
{
"code": null,
"e": 24297,
"s": 24286,
"text": "Javascript"
},
{
"code": "// C++ program to print diamond shape// with 2n rows#include <bits/stdc++.h>using namespace std; // Prints diamond pattern with 2n rowsvoid printDiamond(int n){ int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0;j < space; j++) cout << \" \"; // Print i+1 stars for (int j = 0; j <= i; j++) cout << \"* \"; cout << endl; space--; } // Repeat again in reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) cout << \" \"; // Print i stars for (int j = 0;j < i;j++) cout << \"* \"; cout << endl; space++; }} // Driver codeint main(){ printDiamond(5); return 0;} // This is code is contributed// by rathbhupendra",
"e": 25342,
"s": 24297,
"text": null
},
{
"code": "// C program to print// diamond shape with// 2n rows#include<stdio.h> // Prints diamond// pattern with 2n rowsvoid printDiamond(int n){ int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0;j < space; j++) printf(\" \"); // Print i+1 stars for (int j = 0;j <= i; j++) printf(\"* \"); printf(\"\\n\"); space--; } // Repeat again in // reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) printf(\" \"); // Print i stars for (int j = 0;j < i;j++) printf(\"* \"); printf(\"\\n\"); space++; }} // Driver codeint main(){ printDiamond(5); return 0;}",
"e": 26317,
"s": 25342,
"text": null
},
{
"code": "// JAVA Code to print// the diamond shapeimport java.util.*; class GFG{ // Prints diamond pattern // with 2n rows static void printDiamond(int n) { int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) System.out.print(\" \"); // Print i+1 stars for (int j = 0; j <= i; j++) System.out.print(\"* \"); System.out.print(\"\\n\"); space--; } // Repeat again in // reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) System.out.print(\" \"); // Print i stars for (int j = 0; j < i; j++) System.out.print(\"* \"); System.out.print(\"\\n\"); space++; } } // Driver Code public static void main(String[] args) { printDiamond(5); }} // This code is contributed// by Arnav Kr. Mandal.",
"e": 27645,
"s": 26317,
"text": null
},
{
"code": "# Python program to# print Diamond shape # Function to print# Diamond shapedef Diamond(rows): n = 0 for i in range(1, rows + 1): # loop to print spaces for j in range (1, (rows - i) + 1): print(end = \" \") # loop to print star while n != (2 * i - 1): print(\"*\", end = \"\") n = n + 1 n = 0 # line break print() k = 1 n = 1 for i in range(1, rows): # loop to print spaces for j in range (1, k + 1): print(end = \" \") k = k + 1 # loop to print star while n <= (2 * (rows - i) - 1): print(\"*\", end = \"\") n = n + 1 n = 1 print() # Driver Code# number of rows inputrows = 5Diamond(rows)",
"e": 28430,
"s": 27645,
"text": null
},
{
"code": "// C# Code to print// the diamond shapeusing System; class GFG{ // Prints diamond pattern // with 2n rows static void printDiamond(int n) { int space = n - 1; // run loop (parent loop) // till number of rows for (int i = 0; i < n; i++) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) Console.Write(\" \"); // Print i+1 stars for (int j = 0; j <= i; j++) Console.Write(\"* \"); Console.Write(\"\\n\"); space--; } // Repeat again in // reverse order space = 0; // run loop (parent loop) // till number of rows for (int i = n; i > 0; i--) { // loop for initially space, // before star printing for (int j = 0; j < space; j++) Console.Write(\" \"); // Print i stars for (int j = 0; j < i; j++) Console.Write(\"* \"); Console.Write(\"\\n\"); space++; } } // Driver Code public static void Main() { printDiamond(5); }} // This code is contributed// by Smitha Semwal.",
"e": 29716,
"s": 28430,
"text": null
},
{
"code": "<?php// PHP program to print// diamond shape with// 2n rows // Prints diamond $// pattern with 2n rowsfunction printDiamond($n){ $space = $n - 1; // run loop (parent loop) // till number of rows for ($i = 0; $i < $n; $i++) { // loop for initially space, // before star printing for ($j = 0;$j < $space; $j++) printf(\" \"); // Print i+1 stars for ($j = 0;$j <= $i; $j++) printf(\"* \"); printf(\"\\n\"); $space--; } // Repeat again in // reverse order $space = 0; // run loop (parent loop) // till number of rows for ($i = $n; $i > 0; $i--) { // loop for initially space, // before star printing for ($j = 0; $j < $space; $j++) printf(\" \"); // Pr$i stars for ($j = 0;$j < $i;$j++) printf(\"* \"); printf(\"\\n\"); $space++; }} // Driver code printDiamond(5); // This code is contributed by Anuj_67?>",
"e": 30720,
"s": 29716,
"text": null
},
{
"code": "<script> // JavaScript program to print diamond shape // with 2n rows // Prints diamond pattern with 2n rows function printDiamond(n) { var space = n - 1; // run loop (parent loop) // till number of rows for (var i = 0; i < n; i++) { // loop for initially space, // before star printing for (var j = 0; j < space; j++) document.write(\" \"); // Print i+1 stars for (var j = 0; j <= i; j++) document.write(\"*\" + \" \"); document.write(\"<br>\"); space--; } // Repeat again in reverse order space = 0; // run loop (parent loop) // till number of rows for (var i = n; i > 0; i--) { // loop for initially space, // before star printing for (var j = 0; j < space; j++) document.write(\" \"); // Print i stars for (var j = 0; j < i; j++) document.write(\"*\" + \" \"); document.write(\"<br>\"); space++; } } // Driver code printDiamond(5); // This code is contributed by rdtank. </script>",
"e": 31871,
"s": 30720,
"text": null
},
{
"code": null,
"e": 31882,
"s": 31871,
"text": "Output : "
},
{
"code": null,
"e": 32002,
"s": 31882,
"text": " *\n * *\n * * *\n * * * *\n * * * * *\n * * * * *\n * * * *\n * * *\n * *\n *"
},
{
"code": null,
"e": 32435,
"s": 32002,
"text": "This article is contributed by Rahul Singh(Nit KKR). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32456,
"s": 32435,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 32461,
"s": 32456,
"text": "vt_m"
},
{
"code": null,
"e": 32475,
"s": 32461,
"text": "rathbhupendra"
},
{
"code": null,
"e": 32482,
"s": 32475,
"text": "rdtank"
},
{
"code": null,
"e": 32499,
"s": 32482,
"text": "pattern-printing"
},
{
"code": null,
"e": 32523,
"s": 32499,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 32534,
"s": 32523,
"text": "C Language"
},
{
"code": null,
"e": 32538,
"s": 32534,
"text": "C++"
},
{
"code": null,
"e": 32545,
"s": 32538,
"text": "Python"
},
{
"code": null,
"e": 32564,
"s": 32545,
"text": "School Programming"
},
{
"code": null,
"e": 32581,
"s": 32564,
"text": "pattern-printing"
},
{
"code": null,
"e": 32585,
"s": 32581,
"text": "CPP"
},
{
"code": null,
"e": 32683,
"s": 32585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32692,
"s": 32683,
"text": "Comments"
},
{
"code": null,
"e": 32705,
"s": 32692,
"text": "Old Comments"
},
{
"code": null,
"e": 32740,
"s": 32705,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 32768,
"s": 32740,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 32814,
"s": 32768,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 32826,
"s": 32814,
"text": "fork() in C"
},
{
"code": null,
"e": 32858,
"s": 32826,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 32876,
"s": 32858,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 32922,
"s": 32876,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 32965,
"s": 32922,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 32984,
"s": 32965,
"text": "Inheritance in C++"
}
]
|
Python Program for Linear Search | In this article, we will learn about the Linear Search and its implementation in Python 3.x. Or earlier.
Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[]
If x matches with any of the element, return the index value.
If x doesn’t match with any of elements in arr[] , return -1 or element not found.
Now let’s see the visual representation of the given approach −
Live Demo
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))
element found at index 6
The scope of the variables are shown in the figure −
In this article, we learned about the mechanism of linear search in Python3.x. Or earlier. | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "In this article, we will learn about the Linear Search and its implementation in Python 3.x. Or earlier."
},
{
"code": null,
"e": 1419,
"s": 1167,
"text": "Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[]\nIf x matches with any of the element, return the index value.\nIf x doesn’t match with any of elements in arr[] , return -1 or element not found."
},
{
"code": null,
"e": 1483,
"s": 1419,
"text": "Now let’s see the visual representation of the given approach −"
},
{
"code": null,
"e": 1494,
"s": 1483,
"text": " Live Demo"
},
{
"code": null,
"e": 1711,
"s": 1494,
"text": "def linearsearch(arr, x):\n for i in range(len(arr)):\n if arr[i] == x:\n return i\n return -1\narr = ['t','u','t','o','r','i','a','l']\nx = 'a'\nprint(\"element found at index \"+str(linearsearch(arr,x)))"
},
{
"code": null,
"e": 1736,
"s": 1711,
"text": "element found at index 6"
},
{
"code": null,
"e": 1789,
"s": 1736,
"text": "The scope of the variables are shown in the figure −"
},
{
"code": null,
"e": 1880,
"s": 1789,
"text": "In this article, we learned about the mechanism of linear search in Python3.x. Or earlier."
}
]
|
Check if a String is empty ("") or null in Java | To check if a string is null or empty in Java, use the == operator.
Let’s say we have the following strings.
String myStr1 = "Jack Sparrow";
String myStr2 = "";
Let us check both the strings now whether they are null or empty. Result will be a boolean.
res = (myStr1 == null || myStr1.length() == 0);
res = (myStr2 == null || myStr2.length() == 0);
Live Demo
public class Demo {
public static void main(String[] args) {
String myStr1 = "Jack Sparrow";
String myStr2 = "";
boolean res;
res = (myStr1 == null || myStr1.length() == 0);
System.out.println("String 1 is null or empty? "+res);
res = (myStr2 == null || myStr2.length() == 0);
System.out.println("String 2 is null or empty? "+res);
}
}
String 1 is null or empty? False
String 2 is null or empty? True | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To check if a string is null or empty in Java, use the == operator."
},
{
"code": null,
"e": 1171,
"s": 1130,
"text": "Let’s say we have the following strings."
},
{
"code": null,
"e": 1223,
"s": 1171,
"text": "String myStr1 = \"Jack Sparrow\";\nString myStr2 = \"\";"
},
{
"code": null,
"e": 1315,
"s": 1223,
"text": "Let us check both the strings now whether they are null or empty. Result will be a boolean."
},
{
"code": null,
"e": 1411,
"s": 1315,
"text": "res = (myStr1 == null || myStr1.length() == 0);\nres = (myStr2 == null || myStr2.length() == 0);"
},
{
"code": null,
"e": 1422,
"s": 1411,
"text": " Live Demo"
},
{
"code": null,
"e": 1806,
"s": 1422,
"text": "public class Demo {\n public static void main(String[] args) {\n String myStr1 = \"Jack Sparrow\";\n String myStr2 = \"\";\n boolean res;\n res = (myStr1 == null || myStr1.length() == 0);\n System.out.println(\"String 1 is null or empty? \"+res);\n res = (myStr2 == null || myStr2.length() == 0);\n System.out.println(\"String 2 is null or empty? \"+res);\n }\n}"
},
{
"code": null,
"e": 1871,
"s": 1806,
"text": "String 1 is null or empty? False\nString 2 is null or empty? True"
}
]
|
How to add multiple font files for the same font ? - GeeksforGeeks | 10 Sep, 2020
@font-faceIn CSS, it is a rule that specifies a custom font. This allows us to expand our scope beyond the web-safe fonts.In this rule, @font-face must be first defined and then webpage elements can be made to refer to it as required.
Objective:To define multiple font files under the same font name.Framing this in a more understandable way, what we are trying to do here is that if we want to display a specific font in multiple other ways like bold, italics, etc. traditionally we must define them separately. But, here we will look at a way to combine these font files in a single font name.
The following example shows how different font files with the same are usually employed:
Example 1:
<!DOCTYPE html><html> <head> <style> @font-face { font-family: "quicksandregular"; src: url("quicksand-regular-webfont.woff2") format("woff2"), url("quicksand-regular-webfont.woff") format("woff"); font-weight: normal; font-style: normal; } @font-face { font-family: "quicksandbold"; src: url("quicksand-bold-webfont.woff2") format("woff2"), url("quicksand-bold-webfont.woff") format("woff"); font-weight: normal; font-style: normal; } @font-face { font-family: "quicksanditalic"; src: url("quicksand-italic-webfont.woff2") format("woff2"), url("quicksand-italic-webfont.woff") format("woff"); font-weight: normal; font-style: normal; } .first { font-family: "quicksandregular"; color: green; } .second { font-family: "quicksandbold"; color: green; } .third { font-family: "quicksanditalic"; color: green; } </style> </head> <body> geeks for geeks <div class="first">geeks for geeks</div> <div class="second">geeks for geeks</div> <div class="third">geeks for geeks</div> </body></html>
Output:
In the above program for each font file of the same font, we had to define multiple files with different names and then refer them accordingly.
The piece of code depicts how just by using a single font name multiple files can be used.These changes need to be done in the extracted CSS file of a specific font file.
Example 2:
<!DOCTYPE html><html> <head> <style> @font-face { font-family: "quicksand"; src: url("quicksand-regular-webfont.woff2") format("woff2"), url("quicksand-regular-webfont.woff") format("woff"); font-weight: normal; font-style: normal; } @font-face { font-family: "quicksand"; src: url("quicksand-bold-webfont.woff2") format("woff2"), url("quicksand-bold-webfont.woff") format("woff"); font-weight: bold; font-style: normal; } @font-face { font-family: "quicksand"; src: url("quicksand-italic-webfont.woff2") format("woff2"), url("quicksand-italic-webfont.woff") format("woff"); font-weight: normal; font-style: normal; } .first { font-family: "quicksand"; color: green; } .second { font-family: "quicksand"; font-weight: bold; color: green; } .third { font-family: "quicksand"; font-style: italic; color: green; } </style> </head> <body> geeks for geeks <div class="first">geeks for geeks</div> <div class="second">geeks for geeks</div> <div class="third">geeks for geeks</div> </body></html>
Output:
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to fetch data from localserver database and display on HTML table using PHP ?
How to Create Time-Table schedule using HTML ?
Search Bar using HTML, CSS and JavaScript
Express.js express.Router() Function
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 25296,
"s": 25268,
"text": "\n10 Sep, 2020"
},
{
"code": null,
"e": 25531,
"s": 25296,
"text": "@font-faceIn CSS, it is a rule that specifies a custom font. This allows us to expand our scope beyond the web-safe fonts.In this rule, @font-face must be first defined and then webpage elements can be made to refer to it as required."
},
{
"code": null,
"e": 25892,
"s": 25531,
"text": "Objective:To define multiple font files under the same font name.Framing this in a more understandable way, what we are trying to do here is that if we want to display a specific font in multiple other ways like bold, italics, etc. traditionally we must define them separately. But, here we will look at a way to combine these font files in a single font name."
},
{
"code": null,
"e": 25981,
"s": 25892,
"text": "The following example shows how different font files with the same are usually employed:"
},
{
"code": null,
"e": 25992,
"s": 25981,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> @font-face { font-family: \"quicksandregular\"; src: url(\"quicksand-regular-webfont.woff2\") format(\"woff2\"), url(\"quicksand-regular-webfont.woff\") format(\"woff\"); font-weight: normal; font-style: normal; } @font-face { font-family: \"quicksandbold\"; src: url(\"quicksand-bold-webfont.woff2\") format(\"woff2\"), url(\"quicksand-bold-webfont.woff\") format(\"woff\"); font-weight: normal; font-style: normal; } @font-face { font-family: \"quicksanditalic\"; src: url(\"quicksand-italic-webfont.woff2\") format(\"woff2\"), url(\"quicksand-italic-webfont.woff\") format(\"woff\"); font-weight: normal; font-style: normal; } .first { font-family: \"quicksandregular\"; color: green; } .second { font-family: \"quicksandbold\"; color: green; } .third { font-family: \"quicksanditalic\"; color: green; } </style> </head> <body> geeks for geeks <div class=\"first\">geeks for geeks</div> <div class=\"second\">geeks for geeks</div> <div class=\"third\">geeks for geeks</div> </body></html>",
"e": 27440,
"s": 25992,
"text": null
},
{
"code": null,
"e": 27448,
"s": 27440,
"text": "Output:"
},
{
"code": null,
"e": 27592,
"s": 27448,
"text": "In the above program for each font file of the same font, we had to define multiple files with different names and then refer them accordingly."
},
{
"code": null,
"e": 27763,
"s": 27592,
"text": "The piece of code depicts how just by using a single font name multiple files can be used.These changes need to be done in the extracted CSS file of a specific font file."
},
{
"code": null,
"e": 27774,
"s": 27763,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> @font-face { font-family: \"quicksand\"; src: url(\"quicksand-regular-webfont.woff2\") format(\"woff2\"), url(\"quicksand-regular-webfont.woff\") format(\"woff\"); font-weight: normal; font-style: normal; } @font-face { font-family: \"quicksand\"; src: url(\"quicksand-bold-webfont.woff2\") format(\"woff2\"), url(\"quicksand-bold-webfont.woff\") format(\"woff\"); font-weight: bold; font-style: normal; } @font-face { font-family: \"quicksand\"; src: url(\"quicksand-italic-webfont.woff2\") format(\"woff2\"), url(\"quicksand-italic-webfont.woff\") format(\"woff\"); font-weight: normal; font-style: normal; } .first { font-family: \"quicksand\"; color: green; } .second { font-family: \"quicksand\"; font-weight: bold; color: green; } .third { font-family: \"quicksand\"; font-style: italic; color: green; } </style> </head> <body> geeks for geeks <div class=\"first\">geeks for geeks</div> <div class=\"second\">geeks for geeks</div> <div class=\"third\">geeks for geeks</div> </body></html>",
"e": 29420,
"s": 27774,
"text": null
},
{
"code": null,
"e": 29428,
"s": 29420,
"text": "Output:"
},
{
"code": null,
"e": 29437,
"s": 29428,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29444,
"s": 29437,
"text": "Picked"
},
{
"code": null,
"e": 29448,
"s": 29444,
"text": "CSS"
},
{
"code": null,
"e": 29465,
"s": 29448,
"text": "Web Technologies"
},
{
"code": null,
"e": 29563,
"s": 29465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29572,
"s": 29563,
"text": "Comments"
},
{
"code": null,
"e": 29585,
"s": 29572,
"text": "Old Comments"
},
{
"code": null,
"e": 29622,
"s": 29585,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29651,
"s": 29622,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29733,
"s": 29651,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 29780,
"s": 29733,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 29822,
"s": 29780,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29859,
"s": 29822,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 29892,
"s": 29859,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29935,
"s": 29892,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29996,
"s": 29935,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
Boss Fight in Python | Suppose we have a binary list called fighters and another list of binary lists called bosses. In fighters list the 1 is representing a fighter. Similarly, in bosses list 1 representing a boss. That fighters can beat a boss’s row if it contains more fighters than bosses. We have to return a new bosses matrix with defeated boss rows removed.
So, if the input is like fighters = [0,1,1]
then the output will be
To solve this, we will follow these steps −
fighter_cnt := sum of all elements of fighters
fighter_cnt := sum of all elements of fighters
result := a new list
result := a new list
for each row in bosses, doif fighter_cnt <= sum of each element in row, theninsert row at the end of result
for each row in bosses, do
if fighter_cnt <= sum of each element in row, theninsert row at the end of result
if fighter_cnt <= sum of each element in row, then
insert row at the end of result
insert row at the end of result
return result
return result
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, fighters, bosses):
fighter_cnt = sum(fighters)
result = []
for row in bosses:
if fighter_cnt <= sum(row):
result.append(row)
return result
ob = Solution()
fighters = [0, 1, 1]
bosses = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
print(ob.solve(fighters, bosses))
[0, 1, 1], [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
[[0, 1, 1], [1, 1, 1]] | [
{
"code": null,
"e": 1404,
"s": 1062,
"text": "Suppose we have a binary list called fighters and another list of binary lists called bosses. In fighters list the 1 is representing a fighter. Similarly, in bosses list 1 representing a boss. That fighters can beat a boss’s row if it contains more fighters than bosses. We have to return a new bosses matrix with defeated boss rows removed."
},
{
"code": null,
"e": 1448,
"s": 1404,
"text": "So, if the input is like fighters = [0,1,1]"
},
{
"code": null,
"e": 1472,
"s": 1448,
"text": "then the output will be"
},
{
"code": null,
"e": 1516,
"s": 1472,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1563,
"s": 1516,
"text": "fighter_cnt := sum of all elements of fighters"
},
{
"code": null,
"e": 1610,
"s": 1563,
"text": "fighter_cnt := sum of all elements of fighters"
},
{
"code": null,
"e": 1631,
"s": 1610,
"text": "result := a new list"
},
{
"code": null,
"e": 1652,
"s": 1631,
"text": "result := a new list"
},
{
"code": null,
"e": 1760,
"s": 1652,
"text": "for each row in bosses, doif fighter_cnt <= sum of each element in row, theninsert row at the end of result"
},
{
"code": null,
"e": 1787,
"s": 1760,
"text": "for each row in bosses, do"
},
{
"code": null,
"e": 1869,
"s": 1787,
"text": "if fighter_cnt <= sum of each element in row, theninsert row at the end of result"
},
{
"code": null,
"e": 1920,
"s": 1869,
"text": "if fighter_cnt <= sum of each element in row, then"
},
{
"code": null,
"e": 1952,
"s": 1920,
"text": "insert row at the end of result"
},
{
"code": null,
"e": 1984,
"s": 1952,
"text": "insert row at the end of result"
},
{
"code": null,
"e": 1998,
"s": 1984,
"text": "return result"
},
{
"code": null,
"e": 2012,
"s": 1998,
"text": "return result"
},
{
"code": null,
"e": 2082,
"s": 2012,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2093,
"s": 2082,
"text": " Live Demo"
},
{
"code": null,
"e": 2437,
"s": 2093,
"text": "class Solution:\n def solve(self, fighters, bosses):\n fighter_cnt = sum(fighters)\n result = []\n for row in bosses:\n if fighter_cnt <= sum(row):\n result.append(row)\n return result\nob = Solution()\nfighters = [0, 1, 1]\nbosses = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]\nprint(ob.solve(fighters, bosses))"
},
{
"code": null,
"e": 2493,
"s": 2437,
"text": "[0, 1, 1], [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]"
},
{
"code": null,
"e": 2516,
"s": 2493,
"text": "[[0, 1, 1], [1, 1, 1]]"
}
]
|
Beginner’s guide to deploying H2o models as APIs using FLASK | by Dr. Varshita Sher | Towards Data Science | As a data scientist, most of our time is spent on data preprocessing (or data wrangling), model training, hyperparameter tuning, model validation, etc. However, the number of hats donned by data scientists is ever-increasing, and thus, many industries have now started looking for people who can turn their ML models into an API.
What does this even mean? It means:
You built an awesome ML model with superb accuracy.
You now want others to be able to make use of your model for making predictions (because you are nice or because it is profitable or both) without them needing to see your entire code. This is where an API comes in..
APIs allow us to build a connection so that outsiders can request data from server, send new information to the server, make changes to existing data on server and remove existing data on server.
To explain it in simpler terms (for the purpose of this article), an API is an interface that lets you access and manipulate data (either from a database or some other data source) in the backend when a user requests the data from the frontend. Flask is one of the most popular python frameworks to write data science APIs in the backend.
To test your APIs, you can run the backend server locally which by default runs on the localhost URL (http://127.0.0.1). This URL is followed by a port, say 5000, so that entire URL looks like http://127.0.0.1:5000 . The port can be changed in Flask settings so that if you want to run multiple local servers you can run them on http://127.0.0.1:5000, http://127.0.0.1:5001, and so on.
We will be building a machine learning model using H2o AutoML (uses very few lines of code but generates high-performing models). Our model will be able to predict whether a loan application would be approved or declined based on certain features. Following this, we will be creating our first API to which we would send a query with the client’s age, car type, loan amount, etc and it shall return the status of the application — approved or declined.
Note: I will be using Jupyter Notebook to build and test the H2o model and Spyder to write the Flask code. Finally, I will be accessing my API from within Jupyter as well.
Before we begin writing simple APIs for models, I wanted to give a brief taste of how it feels like to write an even simpler HelloWorld API (one that takes no input from the user). Let’s get started in Spyder...
Here is some boilerplate code that we are going to be using (and later making modifications to):
from flask import Flaskfrom flask_restful import Resource, Apiapp = Flask(__name__)api = Api(app)class HelloWorld(Resource): def get(self): return {'hello': 'world'}api.add_resource(HelloWorld, '/')if __name__ == '__main__': app.run(debug=True, port = 12345)
Few things to note:
return here is of type dict i.e. a key-value pair (key is hello; value is world).
debug = True enables code reloading and better error messages. Never use debug mode in a production environment!
important to add whatever resource you create (such as HelloWorld) to the API using api.add_resource.
the port is explicitly specified as port = 12345 since sometimes the default port can be in use by some other application and can throw an error.
Finally, save the file as medium_tut.py and run it using the green Run button on top (or F5 on Mac). The output in the console pane on the right should look something like this:
As you can see the API is running on local server http://127.0.0.1:12345/.Now open Jupyter Notebook and type the following code to access the API we just wrote.
from requests import getimport requestsurl = 'http://127.0.0.1:12345/'get(url).json()
Kudos on writing your first ever API. :-)
If you notice carefully, the return type of our get function inHelloWorld was dict and thus we use .json() in the code above to parse the outputs of that dictionary.
We will be modifying our previous code in medium_tut.py file to accept one parameter (more specifically a number) from the user’s end and return its square to the user.
from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)# argument parsingparser = reqparse.RequestParser()parser.add_argument('num1')class HelloWorld(Resource): def get(self): return {'hello': 'world'}class PrintSquare(Resource): def get(self): # use parser and find the user's input args = parser.parse_args() user_query = float(args['num1']) return {'ans': user_query * user_query}api.add_resource(HelloWorld, '/hello')api.add_resource(PrintSquare, '/sq')if __name__ == '__main__': app.run(debug=True, port = 12345)
Assessing the modifications we made:
we have added the user inputs (in our case a single number) to the parser using parser.add_argument().
we now have a new class PrintSquare for returning the square of a number.
since we have multiple classes now, and we do not want to confuse the API as to which function it should run when the user makes a request, we had to update our add_resource for HelloWorld by adding '/hello' as the endpoint to it. So now, HelloWorld would be running onhttp://127.0.0.1:12345/hello instead of http://127.0.0.1:12345/
Let’s check if we can access our API, back to Jupyter Notebook:
# note the URL has been updates, i.e. the 'sq' endpoint has been added to iturl = 'http://127.0.0.1:12345/sq'# we have one input parameter 'num1'params = {'num1': '2'}# outputting the response from APIresponse = requests.get(url, params)response.json()
Updating the medium_tut.py file on Spyder to accept two numbers as inputs from the user and return its sum.
from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)# argument parsingparser = reqparse.RequestParser()parser.add_argument('num1')parser.add_argument('num2')class HelloWorld(Resource): def get(self): return {'hello': 'world'}class PrintSquare(Resource): def get(self): # use parser and find the user's input args = parser.parse_args() user_query = float(args['num1']) return {'ans': user_query * user_query}class PrintSum(Resource): def get(self): # use parser and find the user's inputs args = parser.parse_args() num1 = float(args['num1']) num2 = float(args['num2']) return {'ans': num1 + num2}api.add_resource(HelloWorld, '/hello')api.add_resource(PrintSquare, '/sq')api.add_resource(PrintSum, '/sum')if __name__ == '__main__': app.run(debug=True, port = 12345)
And finally checking to see if the API works in Jupyter Notebook:
url = 'http://127.0.0.1:12345/sum'# we have two input parameters - 'num1' & 'num2params = {'num1': '2', 'num2': '5'}response = requests.get(url, params)response.json()
And voila, you are all set to create APIs for your own ML models.
Tip: Go ahead and create a new directory on Desktop (or elsewhere), name it H2o_API. This is where we will be saving the Jupyter Notebook containing code to train our model. Later on, when we create the API script (in Spyder), it will also be saved in the same directory. The whole logic behind doing so is that when we create and download the model locally, it would be accessible by our Flask script.
Our dataset has 5 predictor features:
age_group: (Older, Young, Middle-Aged)
car_type: categorical (Convertible, Saloon, SUV)
loanamount: float
deposit: float
area: categorical (rural, urban)
and one outcome variable i.e. application_outcome which can take two values: approved or declined.
This is how our data looks like:
#Categorical Columns - enum#Numerical Columns - realcol_dict = {'age_group' : 'enum', 'car_type' : 'enum', 'loanamount' : 'real', 'deposit' : 'real', 'area' : 'enum', 'application_outcome': 'enum'}train_h2o = h2o.H2OFrame(train, column_types = col_dict)test_h2o = h2o.H2OFrame(test, column_types = col_dict)
Automated machine learning (AutoML) is the process of automating the end-to-end process of applying machine learning to real-world problems. It can be easily performed using H2o’s AutoML interface (I will be talking in-depth about it in my next article). In a nutshell, it provides a leaderboard with top-performing models, obtained from automatic training and tuning of many models.
For now, let’s load it into our Jupyter notebook:
from h2o.automl import H2OAutoMLaml = H2OAutoML(max_models = 5, max_runtime_secs=100, seed = 1)
Setting the predictor and response features:
# setting predictor and response featuresx = ['age_group', 'car_type', 'loanamount', 'deposit', 'area']y = 'application_outcome'
The training process can be achieved simply using a single line of code in H2o.
# Trainingaml.train(x=x, y='application_outcome', training_frame=train_h2o, validation_frame=test_h2o)
The best model (based on default metric AUC) is stored in aml.leader:
aml.leader
As you can see, even without much tinkering, we have obtained a model with AUC = 0.87 on the validation set (not bad at all)! Also, note that this model’s name is StackedEnsemble_AllModels_AutoML_20200619_172405. The name of your model would be similar to this, minus the part after last underscore i.e. 172405.
# download the model built above to your local machinemy_local_model = h2o.download_model(aml.leader, path="/Users/UserName/Desktop/H2o_API")
If you check the name of this saved model in your directory, it would look something like StackedEnsemble_AllModels_AutoML_20200619_******.
Creating a new python script pred_API.py to write our Flask script.
from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)import h2oimport pandas as pdh2o.init()## load trained modelmodel_path = 'StackedEnsemble_AllModels_AutoML_20200619_******'uploaded_model = h2o.load_model(model_path)
# argument parsingparser = reqparse.RequestParser(bundle_errors=True) # if there are 2 errors, both of their msgs will be printedparser.add_argument('age_group', choices = ('Young', 'Older', 'Middle-Aged'), help = 'Bad Choice: {error_msg}. Valid choices are Young, Older, Middle-Aged')parser.add_argument('car_type', choices = ('SUV', 'Saloon', 'Convertible'), help = 'Bad Choice: {error_msg}. Valid choices are SUV, Saloon, Convertible')parser.add_argument('loanamount')parser.add_argument('deposit')parser.add_argument('area', choices = ('urban', 'rural'), help = 'Bad Choice: {error_msg}. Valid choices are urban, rural')
While adding the values for categorical features to the parser (such as age_group and car_type), we set the choices as a tuple containing all possible values that the feature can take. In case a value other than those mentioned in choices are encountered, it will throw an error message specified in help.
Finally, we set bundle_errors = True so that in the case of two errors, both the error messages are printed. For instance, we have deliberately set wrong values for age_group as ‘Olderr’ and car_type as ‘SUVv’ in the example below:
#Categorical Columns - enum#Numerical Columns - realcol_dict = {'age_group' : 'enum', 'car_type' : 'enum', 'loanamount' : 'real', 'deposit' : 'real', 'area' : 'enum', 'application_outcome': 'enum'}# prepare empty test data frame to be fed to the modeldata = {}# results dictitem_dict = {}class LoanPred(Resource): def get(self): args = parser.parse_args() age = args['age_group'] car_type = args['car_type'] loanamount = float(args['loanamount']) deposit = float(args['deposit']) area = args['area'] application_outcome = 'declined' #setting as default to declined (can set it as 'approved' as well, doesn't matter) # put key:value pairs in empty dict called data data['age_group'] = age data['car_type'] = car_type data['loanamount'] = [loanamount] data['deposit'] = [deposit] data['area'] = area data['application_outcome'] = application_outcome # creating dataframe from dict testing = pd.DataFrame(data) # converting pandas to h2o dataframe test = h2o.H2OFrame(testing, column_types = col_dict) # making predictions pred_ans = uploaded_model.predict(test).as_data_frame() # put key:value pairs in empty dict called item_dict item_dict['Prediction'] = pred_ans.predict.values[0] item_dict['Approved'] = pred_ans.approved.values[0] item_dict['Declined'] = pred_ans.declined.values[0] return{'ans': item_dict} api.add_resource(LoanPred, '/')if __name__ == '__main__': app.run(debug=True, port= 1234)
We first take all input parameters and use them to create a pandas data frame called testing. This data frame must be converted into an H2o Frame called test before it can be fed to the H2o model for prediction.
One important thing to note is that the output from model.predict() is an H2o frame and currently, Spyder ipython console doesn’t show the h2o data frame correctly (you can follow the issue here on Github). Thus, we need to explicitly convert the output from model.predict() to a pandas data frame using as_data_frame(). The output pred_ans is a data frame containing three columns —
final prediction (approved or declined),
probability of application being approved,
probability of application being declined.
We store all three values as key-value pairs in item_dict.
And finally all the code in pred_API.py in one place:
from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)import h2oimport pandas as pdh2o.init()## load saved modelmodel_path = 'StackedEnsemble_AllModels_AutoML_20200619_******'uploaded_model = h2o.load_model(model_path)# argument parsingparser = reqparse.RequestParser(bundle_errors=True) #if there are 2 errors, both's msg will be printedparser.add_argument('age_group', choices = ('Young', 'Older', 'Middle-Aged'), help = 'Bad Choice: {error_msg}. Valid choices are Young, Older, Middle-Aged')parser.add_argument('car_type', choices = ('SUV', 'Saloon', 'Convertible'), help = 'Bad Choice: {error_msg}. Valid choices are SUV, Saloon, Convertible')parser.add_argument('loanamount')parser.add_argument('deposit')parser.add_argument('area', choices = ('urban', 'rural'), help = 'Bad Choice: {error_msg}. Valid choices are urban, rural')#Categorical Columns - enum#Numerical Columns - realcol_dict = {'age_group' : 'enum', 'car_type' : 'enum', 'loanamount' : 'real', 'deposit' : 'real', 'area' : 'enum', 'application_outcome': 'enum'}#prepare empty test data frame to be fed to the modeldata = {}# results dictitem_dict = {}class LoanPred(Resource): def get(self): args = parser.parse_args() age = args['age_group'] car_type = args['car_type'] loanamount = float(args['loanamount']) deposit = float(args['deposit']) area = args['area'] application_outcome = 'declined' # put key:value pairs in empty dict called data data['age_group'] = age data['car_type'] = car_type data['loanamount'] = [loanamount] data['deposit'] = [deposit] data['area'] = area data['application_outcome'] = application_outcome # creating dataframe from dict testing = pd.DataFrame(data) # converting pandas to h2o dataframe test = h2o.H2OFrame(testing, column_types = col_dict) # making predictions pred_ans = uploaded_model.predict(test).as_data_frame() # put key:value pairs in empty dict called item_dict item_dict['Prediction'] = pred_ans.predict.values[0] item_dict['Approved'] = pred_ans.approved.values[0] item_dict['Declined'] = pred_ans.declined.values[0] return{'ans': item_dict} api.add_resource(LoanPred, '/')if __name__ == '__main__': app.run(debug=True, port= 1234)
In Jupyter Notebook:
# Normal API call with all inputs in correct formaturl = 'http://127.0.0.1:1234/'params = {'age_group': 'Young', 'car_type': 'SUV', 'loanamount': '12342', 'deposit': '2360', 'area': 'rural' }response = requests.get(url, params)response.json()
And there we go.. We have successfully managed to make an API call and retrieve predictions from our model trained in H2o. Now all you have to do is grab a friend who can turn this API output in some fancy web-application.
This was a warm introduction to the concept of creating APIs for ML models. Hopefully, that wasn’t too scary and the descriptions were detailed enough to help you understand the nitty-gritty involved. All the code can be found on Github.
In the next part, we will be learning how to use Flask and Bigquery APIs to extract data from BigQuery datasets based on user query parameters.
Until next time :-) | [
{
"code": null,
"e": 502,
"s": 172,
"text": "As a data scientist, most of our time is spent on data preprocessing (or data wrangling), model training, hyperparameter tuning, model validation, etc. However, the number of hats donned by data scientists is ever-increasing, and thus, many industries have now started looking for people who can turn their ML models into an API."
},
{
"code": null,
"e": 538,
"s": 502,
"text": "What does this even mean? It means:"
},
{
"code": null,
"e": 590,
"s": 538,
"text": "You built an awesome ML model with superb accuracy."
},
{
"code": null,
"e": 807,
"s": 590,
"text": "You now want others to be able to make use of your model for making predictions (because you are nice or because it is profitable or both) without them needing to see your entire code. This is where an API comes in.."
},
{
"code": null,
"e": 1003,
"s": 807,
"text": "APIs allow us to build a connection so that outsiders can request data from server, send new information to the server, make changes to existing data on server and remove existing data on server."
},
{
"code": null,
"e": 1342,
"s": 1003,
"text": "To explain it in simpler terms (for the purpose of this article), an API is an interface that lets you access and manipulate data (either from a database or some other data source) in the backend when a user requests the data from the frontend. Flask is one of the most popular python frameworks to write data science APIs in the backend."
},
{
"code": null,
"e": 1728,
"s": 1342,
"text": "To test your APIs, you can run the backend server locally which by default runs on the localhost URL (http://127.0.0.1). This URL is followed by a port, say 5000, so that entire URL looks like http://127.0.0.1:5000 . The port can be changed in Flask settings so that if you want to run multiple local servers you can run them on http://127.0.0.1:5000, http://127.0.0.1:5001, and so on."
},
{
"code": null,
"e": 2181,
"s": 1728,
"text": "We will be building a machine learning model using H2o AutoML (uses very few lines of code but generates high-performing models). Our model will be able to predict whether a loan application would be approved or declined based on certain features. Following this, we will be creating our first API to which we would send a query with the client’s age, car type, loan amount, etc and it shall return the status of the application — approved or declined."
},
{
"code": null,
"e": 2353,
"s": 2181,
"text": "Note: I will be using Jupyter Notebook to build and test the H2o model and Spyder to write the Flask code. Finally, I will be accessing my API from within Jupyter as well."
},
{
"code": null,
"e": 2565,
"s": 2353,
"text": "Before we begin writing simple APIs for models, I wanted to give a brief taste of how it feels like to write an even simpler HelloWorld API (one that takes no input from the user). Let’s get started in Spyder..."
},
{
"code": null,
"e": 2662,
"s": 2565,
"text": "Here is some boilerplate code that we are going to be using (and later making modifications to):"
},
{
"code": null,
"e": 2934,
"s": 2662,
"text": "from flask import Flaskfrom flask_restful import Resource, Apiapp = Flask(__name__)api = Api(app)class HelloWorld(Resource): def get(self): return {'hello': 'world'}api.add_resource(HelloWorld, '/')if __name__ == '__main__': app.run(debug=True, port = 12345)"
},
{
"code": null,
"e": 2954,
"s": 2934,
"text": "Few things to note:"
},
{
"code": null,
"e": 3036,
"s": 2954,
"text": "return here is of type dict i.e. a key-value pair (key is hello; value is world)."
},
{
"code": null,
"e": 3149,
"s": 3036,
"text": "debug = True enables code reloading and better error messages. Never use debug mode in a production environment!"
},
{
"code": null,
"e": 3251,
"s": 3149,
"text": "important to add whatever resource you create (such as HelloWorld) to the API using api.add_resource."
},
{
"code": null,
"e": 3397,
"s": 3251,
"text": "the port is explicitly specified as port = 12345 since sometimes the default port can be in use by some other application and can throw an error."
},
{
"code": null,
"e": 3575,
"s": 3397,
"text": "Finally, save the file as medium_tut.py and run it using the green Run button on top (or F5 on Mac). The output in the console pane on the right should look something like this:"
},
{
"code": null,
"e": 3736,
"s": 3575,
"text": "As you can see the API is running on local server http://127.0.0.1:12345/.Now open Jupyter Notebook and type the following code to access the API we just wrote."
},
{
"code": null,
"e": 3822,
"s": 3736,
"text": "from requests import getimport requestsurl = 'http://127.0.0.1:12345/'get(url).json()"
},
{
"code": null,
"e": 3864,
"s": 3822,
"text": "Kudos on writing your first ever API. :-)"
},
{
"code": null,
"e": 4030,
"s": 3864,
"text": "If you notice carefully, the return type of our get function inHelloWorld was dict and thus we use .json() in the code above to parse the outputs of that dictionary."
},
{
"code": null,
"e": 4199,
"s": 4030,
"text": "We will be modifying our previous code in medium_tut.py file to accept one parameter (more specifically a number) from the user’s end and return its square to the user."
},
{
"code": null,
"e": 4821,
"s": 4199,
"text": "from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)# argument parsingparser = reqparse.RequestParser()parser.add_argument('num1')class HelloWorld(Resource): def get(self): return {'hello': 'world'}class PrintSquare(Resource): def get(self): # use parser and find the user's input args = parser.parse_args() user_query = float(args['num1']) return {'ans': user_query * user_query}api.add_resource(HelloWorld, '/hello')api.add_resource(PrintSquare, '/sq')if __name__ == '__main__': app.run(debug=True, port = 12345)"
},
{
"code": null,
"e": 4858,
"s": 4821,
"text": "Assessing the modifications we made:"
},
{
"code": null,
"e": 4961,
"s": 4858,
"text": "we have added the user inputs (in our case a single number) to the parser using parser.add_argument()."
},
{
"code": null,
"e": 5035,
"s": 4961,
"text": "we now have a new class PrintSquare for returning the square of a number."
},
{
"code": null,
"e": 5368,
"s": 5035,
"text": "since we have multiple classes now, and we do not want to confuse the API as to which function it should run when the user makes a request, we had to update our add_resource for HelloWorld by adding '/hello' as the endpoint to it. So now, HelloWorld would be running onhttp://127.0.0.1:12345/hello instead of http://127.0.0.1:12345/"
},
{
"code": null,
"e": 5432,
"s": 5368,
"text": "Let’s check if we can access our API, back to Jupyter Notebook:"
},
{
"code": null,
"e": 5685,
"s": 5432,
"text": "# note the URL has been updates, i.e. the 'sq' endpoint has been added to iturl = 'http://127.0.0.1:12345/sq'# we have one input parameter 'num1'params = {'num1': '2'}# outputting the response from APIresponse = requests.get(url, params)response.json()"
},
{
"code": null,
"e": 5793,
"s": 5685,
"text": "Updating the medium_tut.py file on Spyder to accept two numbers as inputs from the user and return its sum."
},
{
"code": null,
"e": 6703,
"s": 5793,
"text": "from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)# argument parsingparser = reqparse.RequestParser()parser.add_argument('num1')parser.add_argument('num2')class HelloWorld(Resource): def get(self): return {'hello': 'world'}class PrintSquare(Resource): def get(self): # use parser and find the user's input args = parser.parse_args() user_query = float(args['num1']) return {'ans': user_query * user_query}class PrintSum(Resource): def get(self): # use parser and find the user's inputs args = parser.parse_args() num1 = float(args['num1']) num2 = float(args['num2']) return {'ans': num1 + num2}api.add_resource(HelloWorld, '/hello')api.add_resource(PrintSquare, '/sq')api.add_resource(PrintSum, '/sum')if __name__ == '__main__': app.run(debug=True, port = 12345)"
},
{
"code": null,
"e": 6769,
"s": 6703,
"text": "And finally checking to see if the API works in Jupyter Notebook:"
},
{
"code": null,
"e": 6937,
"s": 6769,
"text": "url = 'http://127.0.0.1:12345/sum'# we have two input parameters - 'num1' & 'num2params = {'num1': '2', 'num2': '5'}response = requests.get(url, params)response.json()"
},
{
"code": null,
"e": 7003,
"s": 6937,
"text": "And voila, you are all set to create APIs for your own ML models."
},
{
"code": null,
"e": 7406,
"s": 7003,
"text": "Tip: Go ahead and create a new directory on Desktop (or elsewhere), name it H2o_API. This is where we will be saving the Jupyter Notebook containing code to train our model. Later on, when we create the API script (in Spyder), it will also be saved in the same directory. The whole logic behind doing so is that when we create and download the model locally, it would be accessible by our Flask script."
},
{
"code": null,
"e": 7444,
"s": 7406,
"text": "Our dataset has 5 predictor features:"
},
{
"code": null,
"e": 7483,
"s": 7444,
"text": "age_group: (Older, Young, Middle-Aged)"
},
{
"code": null,
"e": 7532,
"s": 7483,
"text": "car_type: categorical (Convertible, Saloon, SUV)"
},
{
"code": null,
"e": 7550,
"s": 7532,
"text": "loanamount: float"
},
{
"code": null,
"e": 7565,
"s": 7550,
"text": "deposit: float"
},
{
"code": null,
"e": 7598,
"s": 7565,
"text": "area: categorical (rural, urban)"
},
{
"code": null,
"e": 7697,
"s": 7598,
"text": "and one outcome variable i.e. application_outcome which can take two values: approved or declined."
},
{
"code": null,
"e": 7730,
"s": 7697,
"text": "This is how our data looks like:"
},
{
"code": null,
"e": 8096,
"s": 7730,
"text": "#Categorical Columns - enum#Numerical Columns - realcol_dict = {'age_group' : 'enum', 'car_type' : 'enum', 'loanamount' : 'real', 'deposit' : 'real', 'area' : 'enum', 'application_outcome': 'enum'}train_h2o = h2o.H2OFrame(train, column_types = col_dict)test_h2o = h2o.H2OFrame(test, column_types = col_dict)"
},
{
"code": null,
"e": 8480,
"s": 8096,
"text": "Automated machine learning (AutoML) is the process of automating the end-to-end process of applying machine learning to real-world problems. It can be easily performed using H2o’s AutoML interface (I will be talking in-depth about it in my next article). In a nutshell, it provides a leaderboard with top-performing models, obtained from automatic training and tuning of many models."
},
{
"code": null,
"e": 8530,
"s": 8480,
"text": "For now, let’s load it into our Jupyter notebook:"
},
{
"code": null,
"e": 8626,
"s": 8530,
"text": "from h2o.automl import H2OAutoMLaml = H2OAutoML(max_models = 5, max_runtime_secs=100, seed = 1)"
},
{
"code": null,
"e": 8671,
"s": 8626,
"text": "Setting the predictor and response features:"
},
{
"code": null,
"e": 8800,
"s": 8671,
"text": "# setting predictor and response featuresx = ['age_group', 'car_type', 'loanamount', 'deposit', 'area']y = 'application_outcome'"
},
{
"code": null,
"e": 8880,
"s": 8800,
"text": "The training process can be achieved simply using a single line of code in H2o."
},
{
"code": null,
"e": 8983,
"s": 8880,
"text": "# Trainingaml.train(x=x, y='application_outcome', training_frame=train_h2o, validation_frame=test_h2o)"
},
{
"code": null,
"e": 9053,
"s": 8983,
"text": "The best model (based on default metric AUC) is stored in aml.leader:"
},
{
"code": null,
"e": 9064,
"s": 9053,
"text": "aml.leader"
},
{
"code": null,
"e": 9376,
"s": 9064,
"text": "As you can see, even without much tinkering, we have obtained a model with AUC = 0.87 on the validation set (not bad at all)! Also, note that this model’s name is StackedEnsemble_AllModels_AutoML_20200619_172405. The name of your model would be similar to this, minus the part after last underscore i.e. 172405."
},
{
"code": null,
"e": 9518,
"s": 9376,
"text": "# download the model built above to your local machinemy_local_model = h2o.download_model(aml.leader, path=\"/Users/UserName/Desktop/H2o_API\")"
},
{
"code": null,
"e": 9658,
"s": 9518,
"text": "If you check the name of this saved model in your directory, it would look something like StackedEnsemble_AllModels_AutoML_20200619_******."
},
{
"code": null,
"e": 9726,
"s": 9658,
"text": "Creating a new python script pred_API.py to write our Flask script."
},
{
"code": null,
"e": 10000,
"s": 9726,
"text": "from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)import h2oimport pandas as pdh2o.init()## load trained modelmodel_path = 'StackedEnsemble_AllModels_AutoML_20200619_******'uploaded_model = h2o.load_model(model_path)"
},
{
"code": null,
"e": 10625,
"s": 10000,
"text": "# argument parsingparser = reqparse.RequestParser(bundle_errors=True) # if there are 2 errors, both of their msgs will be printedparser.add_argument('age_group', choices = ('Young', 'Older', 'Middle-Aged'), help = 'Bad Choice: {error_msg}. Valid choices are Young, Older, Middle-Aged')parser.add_argument('car_type', choices = ('SUV', 'Saloon', 'Convertible'), help = 'Bad Choice: {error_msg}. Valid choices are SUV, Saloon, Convertible')parser.add_argument('loanamount')parser.add_argument('deposit')parser.add_argument('area', choices = ('urban', 'rural'), help = 'Bad Choice: {error_msg}. Valid choices are urban, rural')"
},
{
"code": null,
"e": 10931,
"s": 10625,
"text": "While adding the values for categorical features to the parser (such as age_group and car_type), we set the choices as a tuple containing all possible values that the feature can take. In case a value other than those mentioned in choices are encountered, it will throw an error message specified in help."
},
{
"code": null,
"e": 11163,
"s": 10931,
"text": "Finally, we set bundle_errors = True so that in the case of two errors, both the error messages are printed. For instance, we have deliberately set wrong values for age_group as ‘Olderr’ and car_type as ‘SUVv’ in the example below:"
},
{
"code": null,
"e": 12889,
"s": 11163,
"text": "#Categorical Columns - enum#Numerical Columns - realcol_dict = {'age_group' : 'enum', 'car_type' : 'enum', 'loanamount' : 'real', 'deposit' : 'real', 'area' : 'enum', 'application_outcome': 'enum'}# prepare empty test data frame to be fed to the modeldata = {}# results dictitem_dict = {}class LoanPred(Resource): def get(self): args = parser.parse_args() age = args['age_group'] car_type = args['car_type'] loanamount = float(args['loanamount']) deposit = float(args['deposit']) area = args['area'] application_outcome = 'declined' #setting as default to declined (can set it as 'approved' as well, doesn't matter) # put key:value pairs in empty dict called data data['age_group'] = age data['car_type'] = car_type data['loanamount'] = [loanamount] data['deposit'] = [deposit] data['area'] = area data['application_outcome'] = application_outcome # creating dataframe from dict testing = pd.DataFrame(data) # converting pandas to h2o dataframe test = h2o.H2OFrame(testing, column_types = col_dict) # making predictions pred_ans = uploaded_model.predict(test).as_data_frame() # put key:value pairs in empty dict called item_dict item_dict['Prediction'] = pred_ans.predict.values[0] item_dict['Approved'] = pred_ans.approved.values[0] item_dict['Declined'] = pred_ans.declined.values[0] return{'ans': item_dict} api.add_resource(LoanPred, '/')if __name__ == '__main__': app.run(debug=True, port= 1234)"
},
{
"code": null,
"e": 13101,
"s": 12889,
"text": "We first take all input parameters and use them to create a pandas data frame called testing. This data frame must be converted into an H2o Frame called test before it can be fed to the H2o model for prediction."
},
{
"code": null,
"e": 13485,
"s": 13101,
"text": "One important thing to note is that the output from model.predict() is an H2o frame and currently, Spyder ipython console doesn’t show the h2o data frame correctly (you can follow the issue here on Github). Thus, we need to explicitly convert the output from model.predict() to a pandas data frame using as_data_frame(). The output pred_ans is a data frame containing three columns —"
},
{
"code": null,
"e": 13526,
"s": 13485,
"text": "final prediction (approved or declined),"
},
{
"code": null,
"e": 13569,
"s": 13526,
"text": "probability of application being approved,"
},
{
"code": null,
"e": 13612,
"s": 13569,
"text": "probability of application being declined."
},
{
"code": null,
"e": 13671,
"s": 13612,
"text": "We store all three values as key-value pairs in item_dict."
},
{
"code": null,
"e": 13725,
"s": 13671,
"text": "And finally all the code in pred_API.py in one place:"
},
{
"code": null,
"e": 16254,
"s": 13725,
"text": "from flask import Flaskfrom flask_restful import Resource, Api, reqparseapp = Flask(__name__)api = Api(app)import h2oimport pandas as pdh2o.init()## load saved modelmodel_path = 'StackedEnsemble_AllModels_AutoML_20200619_******'uploaded_model = h2o.load_model(model_path)# argument parsingparser = reqparse.RequestParser(bundle_errors=True) #if there are 2 errors, both's msg will be printedparser.add_argument('age_group', choices = ('Young', 'Older', 'Middle-Aged'), help = 'Bad Choice: {error_msg}. Valid choices are Young, Older, Middle-Aged')parser.add_argument('car_type', choices = ('SUV', 'Saloon', 'Convertible'), help = 'Bad Choice: {error_msg}. Valid choices are SUV, Saloon, Convertible')parser.add_argument('loanamount')parser.add_argument('deposit')parser.add_argument('area', choices = ('urban', 'rural'), help = 'Bad Choice: {error_msg}. Valid choices are urban, rural')#Categorical Columns - enum#Numerical Columns - realcol_dict = {'age_group' : 'enum', 'car_type' : 'enum', 'loanamount' : 'real', 'deposit' : 'real', 'area' : 'enum', 'application_outcome': 'enum'}#prepare empty test data frame to be fed to the modeldata = {}# results dictitem_dict = {}class LoanPred(Resource): def get(self): args = parser.parse_args() age = args['age_group'] car_type = args['car_type'] loanamount = float(args['loanamount']) deposit = float(args['deposit']) area = args['area'] application_outcome = 'declined' # put key:value pairs in empty dict called data data['age_group'] = age data['car_type'] = car_type data['loanamount'] = [loanamount] data['deposit'] = [deposit] data['area'] = area data['application_outcome'] = application_outcome # creating dataframe from dict testing = pd.DataFrame(data) # converting pandas to h2o dataframe test = h2o.H2OFrame(testing, column_types = col_dict) # making predictions pred_ans = uploaded_model.predict(test).as_data_frame() # put key:value pairs in empty dict called item_dict item_dict['Prediction'] = pred_ans.predict.values[0] item_dict['Approved'] = pred_ans.approved.values[0] item_dict['Declined'] = pred_ans.declined.values[0] return{'ans': item_dict} api.add_resource(LoanPred, '/')if __name__ == '__main__': app.run(debug=True, port= 1234)"
},
{
"code": null,
"e": 16275,
"s": 16254,
"text": "In Jupyter Notebook:"
},
{
"code": null,
"e": 16518,
"s": 16275,
"text": "# Normal API call with all inputs in correct formaturl = 'http://127.0.0.1:1234/'params = {'age_group': 'Young', 'car_type': 'SUV', 'loanamount': '12342', 'deposit': '2360', 'area': 'rural' }response = requests.get(url, params)response.json()"
},
{
"code": null,
"e": 16741,
"s": 16518,
"text": "And there we go.. We have successfully managed to make an API call and retrieve predictions from our model trained in H2o. Now all you have to do is grab a friend who can turn this API output in some fancy web-application."
},
{
"code": null,
"e": 16979,
"s": 16741,
"text": "This was a warm introduction to the concept of creating APIs for ML models. Hopefully, that wasn’t too scary and the descriptions were detailed enough to help you understand the nitty-gritty involved. All the code can be found on Github."
},
{
"code": null,
"e": 17123,
"s": 16979,
"text": "In the next part, we will be learning how to use Flask and Bigquery APIs to extract data from BigQuery datasets based on user query parameters."
}
]
|
How to Add a Column to a MySQL Table in Python? - GeeksforGeeks | 02 Dec, 2020
Prerequisite: Python: MySQL Create Table
Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database.
With the ALTER statement, one can add, drop, or modify a column of an existing table as well as modify table constraints.
The syntax for adding a column with ALTER statement:
ALTER TABLE table_name
ADD new_column_name column_definition
[FIRST | AFTER column_name];
Here, the table_name is the name of the table to which the column is being added, new_column_name is the name of the column to be added and column_definition is the datatype and definition of the column to be added. FIRST and AFTER are optional statements that tell MySQL the position for the new column in the table. If this parameter is not specified then the new column is added to the end of the table.
Implementation:
To add a column to a MySQL table in Python, first establish a connection with the database server. Then create a cursor object. This cursor object interacts with the MySQL server and can be used to perform operations such as execute SQL statements, fetch data and call procedures. So, using this cursor object, execute the ALTER statement to add a column either at the end or at a specific position. Let’s see some examples for better understanding.
Database in use:
We will use a database with a students table describing student details such as roll number and name. Before we learn to add a column to a table, create such a sample table (inserting values is optional).
Example 1:
This example shows the addition of a column at the end of the table. Steps are as follows:
Use the connect() function to establish a connection with the database server. Pass the host, user (root or your username), password (if present), and database parameters to the connect() method.
Then to create a cursor object, use the cursor() function.
Execute the ALTER statement for adding the streaming column to the students table.
To check if the column has been added execute and fetch the result of the DESC statement to describe the structure of the table.
Code:
Python
# Import required packagesimport mysql.connector # Establish connection to MySQL databasemydb = mysql.connector.connect( host = "localhost", user = "username", password = "geeksforgeeks", database = "College") # Create a cursor objectmycursor = mydb.cursor() # MySQL query for adding a columnquery = "ALTER TABLE students \ ADD stream VARCHAR(100) DEFAULT 'CS'"# Execute the query mycursor.execute(query) # Print description of students tablemycursor.execute("desc students")myresult = mycursor.fetchall()for row in myresult: print(row) # Close database connectionmydb.close()
Output:
Example 2:
This example shows the addition of a column at the beginning of the table. Follow the same steps as the above example for establishing a connection and creating a cursor object. Use the keyword FIRST in the ALTER statement to append a column, enrollment year, at the beginning of the students table.
Code:
Python
# Import required packagesimport mysql.connector # Establish connection to MySQL databasemydb = mysql.connector.connect( host = "localhost", user = "username", password = "geeksforgeeks", database = "College") # Create a cursor objectmycursor = mydb.cursor() # MySQL query for adding a column # at the beginning of table query = "ALTER TABLE students \ ADD enrollment_year VARCHAR(100) \ FIRST"# Execute the query mycursor.execute(query) # Print description of students tablemycursor.execute("desc students")myresult = mycursor.fetchall()for row in myresult: print(row) # Close database connectionmydb.close()
Output:
Example 3:
This example shows addition of a column at a specific position in the table. Follow the same steps as example 1 for establishing a connection and creating a cursor object. Use the keyword AFTER in the ALTER statement to append an email column after the name column in the students table.
Python
# Import required packagesimport mysql.connector # Establish connection to MySQL databasemydb = mysql.connector.connect( host = "localhost", user = "username", password = "geeksforgeeks", database = "College") # Create a cursor objectmycursor = mydb.cursor() # MySQL query for adding a column # after a specific columnquery = "ALTER TABLE students \ ADD email VARCHAR(100) \ AFTER Name"# Execute the query mycursor.execute(query) # Print description of students tablemycursor.execute("desc students")myresult = mycursor.fetchall()for row in myresult: print(row) # Close database connectionmydb.close()
Output:
Database after adding columns:
Note: If there are existing values or rows in the table, the new column is Null or the specified default value.
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 24333,
"s": 24292,
"text": "Prerequisite: Python: MySQL Create Table"
},
{
"code": null,
"e": 24578,
"s": 24333,
"text": "Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. "
},
{
"code": null,
"e": 24700,
"s": 24578,
"text": "With the ALTER statement, one can add, drop, or modify a column of an existing table as well as modify table constraints."
},
{
"code": null,
"e": 24753,
"s": 24700,
"text": "The syntax for adding a column with ALTER statement:"
},
{
"code": null,
"e": 24843,
"s": 24753,
"text": "ALTER TABLE table_name\nADD new_column_name column_definition\n[FIRST | AFTER column_name];"
},
{
"code": null,
"e": 25250,
"s": 24843,
"text": "Here, the table_name is the name of the table to which the column is being added, new_column_name is the name of the column to be added and column_definition is the datatype and definition of the column to be added. FIRST and AFTER are optional statements that tell MySQL the position for the new column in the table. If this parameter is not specified then the new column is added to the end of the table."
},
{
"code": null,
"e": 25266,
"s": 25250,
"text": "Implementation:"
},
{
"code": null,
"e": 25716,
"s": 25266,
"text": "To add a column to a MySQL table in Python, first establish a connection with the database server. Then create a cursor object. This cursor object interacts with the MySQL server and can be used to perform operations such as execute SQL statements, fetch data and call procedures. So, using this cursor object, execute the ALTER statement to add a column either at the end or at a specific position. Let’s see some examples for better understanding."
},
{
"code": null,
"e": 25733,
"s": 25716,
"text": "Database in use:"
},
{
"code": null,
"e": 25938,
"s": 25733,
"text": "We will use a database with a students table describing student details such as roll number and name. Before we learn to add a column to a table, create such a sample table (inserting values is optional)."
},
{
"code": null,
"e": 25949,
"s": 25938,
"text": "Example 1:"
},
{
"code": null,
"e": 26040,
"s": 25949,
"text": "This example shows the addition of a column at the end of the table. Steps are as follows:"
},
{
"code": null,
"e": 26236,
"s": 26040,
"text": "Use the connect() function to establish a connection with the database server. Pass the host, user (root or your username), password (if present), and database parameters to the connect() method."
},
{
"code": null,
"e": 26295,
"s": 26236,
"text": "Then to create a cursor object, use the cursor() function."
},
{
"code": null,
"e": 26378,
"s": 26295,
"text": "Execute the ALTER statement for adding the streaming column to the students table."
},
{
"code": null,
"e": 26507,
"s": 26378,
"text": "To check if the column has been added execute and fetch the result of the DESC statement to describe the structure of the table."
},
{
"code": null,
"e": 26513,
"s": 26507,
"text": "Code:"
},
{
"code": null,
"e": 26520,
"s": 26513,
"text": "Python"
},
{
"code": "# Import required packagesimport mysql.connector # Establish connection to MySQL databasemydb = mysql.connector.connect( host = \"localhost\", user = \"username\", password = \"geeksforgeeks\", database = \"College\") # Create a cursor objectmycursor = mydb.cursor() # MySQL query for adding a columnquery = \"ALTER TABLE students \\ ADD stream VARCHAR(100) DEFAULT 'CS'\"# Execute the query mycursor.execute(query) # Print description of students tablemycursor.execute(\"desc students\")myresult = mycursor.fetchall()for row in myresult: print(row) # Close database connectionmydb.close()",
"e": 27124,
"s": 26520,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27124,
"text": "Output:"
},
{
"code": null,
"e": 27143,
"s": 27132,
"text": "Example 2:"
},
{
"code": null,
"e": 27443,
"s": 27143,
"text": "This example shows the addition of a column at the beginning of the table. Follow the same steps as the above example for establishing a connection and creating a cursor object. Use the keyword FIRST in the ALTER statement to append a column, enrollment year, at the beginning of the students table."
},
{
"code": null,
"e": 27450,
"s": 27443,
"text": "Code: "
},
{
"code": null,
"e": 27457,
"s": 27450,
"text": "Python"
},
{
"code": "# Import required packagesimport mysql.connector # Establish connection to MySQL databasemydb = mysql.connector.connect( host = \"localhost\", user = \"username\", password = \"geeksforgeeks\", database = \"College\") # Create a cursor objectmycursor = mydb.cursor() # MySQL query for adding a column # at the beginning of table query = \"ALTER TABLE students \\ ADD enrollment_year VARCHAR(100) \\ FIRST\"# Execute the query mycursor.execute(query) # Print description of students tablemycursor.execute(\"desc students\")myresult = mycursor.fetchall()for row in myresult: print(row) # Close database connectionmydb.close()",
"e": 28101,
"s": 27457,
"text": null
},
{
"code": null,
"e": 28109,
"s": 28101,
"text": "Output:"
},
{
"code": null,
"e": 28120,
"s": 28109,
"text": "Example 3:"
},
{
"code": null,
"e": 28408,
"s": 28120,
"text": "This example shows addition of a column at a specific position in the table. Follow the same steps as example 1 for establishing a connection and creating a cursor object. Use the keyword AFTER in the ALTER statement to append an email column after the name column in the students table."
},
{
"code": null,
"e": 28415,
"s": 28408,
"text": "Python"
},
{
"code": "# Import required packagesimport mysql.connector # Establish connection to MySQL databasemydb = mysql.connector.connect( host = \"localhost\", user = \"username\", password = \"geeksforgeeks\", database = \"College\") # Create a cursor objectmycursor = mydb.cursor() # MySQL query for adding a column # after a specific columnquery = \"ALTER TABLE students \\ ADD email VARCHAR(100) \\ AFTER Name\"# Execute the query mycursor.execute(query) # Print description of students tablemycursor.execute(\"desc students\")myresult = mycursor.fetchall()for row in myresult: print(row) # Close database connectionmydb.close()",
"e": 29051,
"s": 28415,
"text": null
},
{
"code": null,
"e": 29059,
"s": 29051,
"text": "Output:"
},
{
"code": null,
"e": 29090,
"s": 29059,
"text": "Database after adding columns:"
},
{
"code": null,
"e": 29203,
"s": 29090,
"text": "Note: If there are existing values or rows in the table, the new column is Null or the specified default value. "
},
{
"code": null,
"e": 29216,
"s": 29203,
"text": "Python-mySQL"
},
{
"code": null,
"e": 29223,
"s": 29216,
"text": "Python"
},
{
"code": null,
"e": 29321,
"s": 29223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29353,
"s": 29321,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29395,
"s": 29353,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29451,
"s": 29395,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29493,
"s": 29451,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29524,
"s": 29493,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29579,
"s": 29524,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29601,
"s": 29579,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29640,
"s": 29601,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29669,
"s": 29640,
"text": "Create a directory in Python"
}
]
|
Immutable annotation in Dart Programming | We know that const keyword provides immutability in objects. But what about the cases, where we want the entire class to be immutable in nature.
In such cases, we make use of the immutable annotation that is present inside the meta package of dart library.
import 'pacakge:meta/meta.dart';
@immutable
class User {
String name;
}
It should be noted that once we declare any class with the immutable notation, all its object and the object properties and methods will be immutable as well.
Consider the example shown below −
Live Demo
import 'pacakge:meta/meta.dart';
@immutable
class User {
final String name;
User(this.name);
User.withPrint(this.name){
print('New user added ${this.name}');
}
}
void main(){
var u = User.withPrint('Mukul');
u = {};
print(u.name);
}
In the above code, we declared the entire class as immutable and hence any object that we instantiate through it will be immutable as well. Inside the main function, we are trying to assign a different value to the variable u, which will give us a compile error.
Error: Overriding not allowed, as 'u' is immutable.
u = {};
^^^^ | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "We know that const keyword provides immutability in objects. But what about the cases, where we want the entire class to be immutable in nature."
},
{
"code": null,
"e": 1319,
"s": 1207,
"text": "In such cases, we make use of the immutable annotation that is present inside the meta package of dart library."
},
{
"code": null,
"e": 1395,
"s": 1319,
"text": "import 'pacakge:meta/meta.dart';\n\n@immutable\nclass User {\n String name;\n}"
},
{
"code": null,
"e": 1554,
"s": 1395,
"text": "It should be noted that once we declare any class with the immutable notation, all its object and the object properties and methods will be immutable as well."
},
{
"code": null,
"e": 1589,
"s": 1554,
"text": "Consider the example shown below −"
},
{
"code": null,
"e": 1600,
"s": 1589,
"text": " Live Demo"
},
{
"code": null,
"e": 1862,
"s": 1600,
"text": "import 'pacakge:meta/meta.dart';\n\n@immutable\nclass User {\n final String name;\n User(this.name);\n User.withPrint(this.name){\n print('New user added ${this.name}');\n }\n}\n\nvoid main(){\n var u = User.withPrint('Mukul');\n u = {};\n print(u.name);\n}"
},
{
"code": null,
"e": 2125,
"s": 1862,
"text": "In the above code, we declared the entire class as immutable and hence any object that we instantiate through it will be immutable as well. Inside the main function, we are trying to assign a different value to the variable u, which will give us a compile error."
},
{
"code": null,
"e": 2196,
"s": 2125,
"text": "Error: Overriding not allowed, as 'u' is immutable.\n u = {};\n ^^^^"
}
]
|
How to Create a Beautify Venn Diagrams in Python | by Di(Candice) Han | Towards Data Science | Venn diagram is the most common diagram in scientific research articles and can be used to represent the relationship between multiple data sets. From Venn diagram, you can easily detect the commonalities and differences among those datasets. This tutorial will show you three different ways to create Venn diagrams in Python and how to beautify these diagrams.
Part 1: How to Create Venn Diagram
Step1: you need to install the library named matplotlib-venn.
pip install matplotlib-venn
Step2: import libraries
#Import librariesfrom matplotlib_venn import venn2, venn2_circles, venn2_unweightedfrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib import pyplot as plt%matplotlib inline
Step3: create datasets for data visualization
The letters in each dataset represent the student names and we would like to visualize how many students are enrolled in each course, how many of them are enrolled in two and three courses.
Course1=[‘A’,’B’,’C’,’E’,’F’,’G’,’I’,’P’,’Q’]Course2=[‘B’,’E’,’F’,’H’,’K’,’Q’,’R’,’S’,’T’,’U’,’V’,’Z’]Course3=[‘C’,’E’,’G’,’H’,’J’,’K’,’O’,’Q’,’Z’]
Step4: visualize Venn diagram
Let us start to draw a Venn Diagram with 2 groups.
There are 3 main methods to make a Venn diagram with the matplotlib library, leading to the same result.
Method 1 is the most straightforward one. Put two datasets directly.
#Method1: put two datasets directlyvenn2([set(Course1), set(Course2)])plt.show()
You will get a Venn diagram like this:
For method 2, you need to know below numbers first.
Ab = Contained in the left group (indicated as A here), but not the right group (indicated as B here)
aB = Contained in right group B, but not the left group A
AB = A⋂B; contained in both groups.
The subsets parameter is a 3 element list where the numbers 5, 8, 4 correspond to Ab, aB, AB.
#Method 2: venn2(subsets = (5, 8, 4))plt.show()
You will get the same diagram as Venn Diagram 1. Matplotlib automatically assigned A and B to the Venn diagram.
For method 3, you need to pass a dictionary to the parameter subset.
#Method 3: venn2(subsets = {‘10’: 5, ‘01’: 8, ‘11’: 4})plt.show()
The key is the binary encoding method. So the three keys must be “10”, “01” and “11”, and each value after the key represents the size of the corresponding area.
Part 2: beautify the Venn diagram
change labels
change labels
venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’))plt.show()
2. set colors and opacity
venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)plt.show()
3. chang the circles
venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)venn2_circles([set(dataset1), set(dataset2)], linestyle=’-.’, linewidth=2, color=’black’)plt.show()
Matplotlib provides a variety of different linestyles. More information about linestyle can be found on Matplotlib website.
4. change the size of label and numbers
vd2=venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)venn2_circles([set(Course1), set(Course2)], linestyle=’-.’, linewidth=2, color=’black’)for text in vd2.set_labels: #change label size text.set_fontsize(16);for text in vd2.subset_labels: #change number size text.set_fontsize(16)plt.show()
5. add title to the chart
To complete the Venn diagram, title has to be added.
vd2=venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)venn2_circles([set(Course1), set(Course2)], linestyle=’-.’, linewidth=2, color=’black’)for text in vd2.set_labels: text.set_fontsize(16);for text in vd2.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for Course1 and Course2’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20,pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);plt.show()
Drawing a Venn diagram with 3 Groups has no significant difference from generating a Venn diagram with 2 Groups.
vd3=venn3([set(Course1),set(Course2),set(Course3)], set_labels=(‘Course1’, ‘Course2’,’Course3'), set_colors=(‘#c4e6ff’, ‘#F4ACB7’,’#9D8189'), alpha = 0.8)venn3_circles([set(Course1), set(Course2),set(Course3)], linestyle=’-.’, linewidth=2, color=’grey’)for text in vd3.set_labels: text.set_fontsize(16);for text in vd3.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for 3 courses’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20, pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);plt.show()
Matplotlib allows us to customize each circle separately. Let us customize the upper left circle.
vd3=venn3([set(Course1),set(Course2),set(Course3)], set_labels=(‘Course1’, ‘Course2’,’Course3'), set_colors=(‘#c4e6ff’, ‘#F4ACB7’,’#9D8189'), alpha = 0.8)c=venn3_circles([set(Course1), set(Course2),set(Course3)], linestyle=’-.’, linewidth=2, color=’grey’)for text in vd3.set_labels: text.set_fontsize(16);for text in vd3.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for 3 courses’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20, pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);c[0].set_lw(3.0) #customize upper left circle c[0].set_ls(‘:’)plt.show()
The color of the circle can be customized as well. However, if we assign a new color to the circle, it will overwrite the colors we set by parameter set_colors in venn3 function.
vd3=venn3([set(Course1),set(Course2),set(Course3)], set_labels=(‘Course1’, ‘Course2’,’Course3'), set_colors=(‘#c4e6ff’, ‘#F4ACB7’,’#9D8189'), alpha = 0.8)c=venn3_circles([set(Course1), set(Course2),set(Course3)], linestyle=’-.’, linewidth=2, color=’grey’)for text in vd3.set_labels: text.set_fontsize(16);for text in vd3.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for 3 courses’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20, pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);c[0].set_lw(7.0)c[0].set_ls(‘:’)c[0].set_color(‘#c4e6ff’)plt.show()
Enjoy Venn Diagramming! | [
{
"code": null,
"e": 408,
"s": 46,
"text": "Venn diagram is the most common diagram in scientific research articles and can be used to represent the relationship between multiple data sets. From Venn diagram, you can easily detect the commonalities and differences among those datasets. This tutorial will show you three different ways to create Venn diagrams in Python and how to beautify these diagrams."
},
{
"code": null,
"e": 443,
"s": 408,
"text": "Part 1: How to Create Venn Diagram"
},
{
"code": null,
"e": 505,
"s": 443,
"text": "Step1: you need to install the library named matplotlib-venn."
},
{
"code": null,
"e": 533,
"s": 505,
"text": "pip install matplotlib-venn"
},
{
"code": null,
"e": 557,
"s": 533,
"text": "Step2: import libraries"
},
{
"code": null,
"e": 743,
"s": 557,
"text": "#Import librariesfrom matplotlib_venn import venn2, venn2_circles, venn2_unweightedfrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib import pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 789,
"s": 743,
"text": "Step3: create datasets for data visualization"
},
{
"code": null,
"e": 979,
"s": 789,
"text": "The letters in each dataset represent the student names and we would like to visualize how many students are enrolled in each course, how many of them are enrolled in two and three courses."
},
{
"code": null,
"e": 1127,
"s": 979,
"text": "Course1=[‘A’,’B’,’C’,’E’,’F’,’G’,’I’,’P’,’Q’]Course2=[‘B’,’E’,’F’,’H’,’K’,’Q’,’R’,’S’,’T’,’U’,’V’,’Z’]Course3=[‘C’,’E’,’G’,’H’,’J’,’K’,’O’,’Q’,’Z’]"
},
{
"code": null,
"e": 1157,
"s": 1127,
"text": "Step4: visualize Venn diagram"
},
{
"code": null,
"e": 1208,
"s": 1157,
"text": "Let us start to draw a Venn Diagram with 2 groups."
},
{
"code": null,
"e": 1313,
"s": 1208,
"text": "There are 3 main methods to make a Venn diagram with the matplotlib library, leading to the same result."
},
{
"code": null,
"e": 1382,
"s": 1313,
"text": "Method 1 is the most straightforward one. Put two datasets directly."
},
{
"code": null,
"e": 1463,
"s": 1382,
"text": "#Method1: put two datasets directlyvenn2([set(Course1), set(Course2)])plt.show()"
},
{
"code": null,
"e": 1502,
"s": 1463,
"text": "You will get a Venn diagram like this:"
},
{
"code": null,
"e": 1554,
"s": 1502,
"text": "For method 2, you need to know below numbers first."
},
{
"code": null,
"e": 1656,
"s": 1554,
"text": "Ab = Contained in the left group (indicated as A here), but not the right group (indicated as B here)"
},
{
"code": null,
"e": 1714,
"s": 1656,
"text": "aB = Contained in right group B, but not the left group A"
},
{
"code": null,
"e": 1750,
"s": 1714,
"text": "AB = A⋂B; contained in both groups."
},
{
"code": null,
"e": 1844,
"s": 1750,
"text": "The subsets parameter is a 3 element list where the numbers 5, 8, 4 correspond to Ab, aB, AB."
},
{
"code": null,
"e": 1892,
"s": 1844,
"text": "#Method 2: venn2(subsets = (5, 8, 4))plt.show()"
},
{
"code": null,
"e": 2004,
"s": 1892,
"text": "You will get the same diagram as Venn Diagram 1. Matplotlib automatically assigned A and B to the Venn diagram."
},
{
"code": null,
"e": 2073,
"s": 2004,
"text": "For method 3, you need to pass a dictionary to the parameter subset."
},
{
"code": null,
"e": 2139,
"s": 2073,
"text": "#Method 3: venn2(subsets = {‘10’: 5, ‘01’: 8, ‘11’: 4})plt.show()"
},
{
"code": null,
"e": 2301,
"s": 2139,
"text": "The key is the binary encoding method. So the three keys must be “10”, “01” and “11”, and each value after the key represents the size of the corresponding area."
},
{
"code": null,
"e": 2335,
"s": 2301,
"text": "Part 2: beautify the Venn diagram"
},
{
"code": null,
"e": 2349,
"s": 2335,
"text": "change labels"
},
{
"code": null,
"e": 2363,
"s": 2349,
"text": "change labels"
},
{
"code": null,
"e": 2443,
"s": 2363,
"text": "venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’))plt.show()"
},
{
"code": null,
"e": 2469,
"s": 2443,
"text": "2. set colors and opacity"
},
{
"code": null,
"e": 2596,
"s": 2469,
"text": "venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)plt.show()"
},
{
"code": null,
"e": 2617,
"s": 2596,
"text": "3. chang the circles"
},
{
"code": null,
"e": 2833,
"s": 2617,
"text": "venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)venn2_circles([set(dataset1), set(dataset2)], linestyle=’-.’, linewidth=2, color=’black’)plt.show()"
},
{
"code": null,
"e": 2957,
"s": 2833,
"text": "Matplotlib provides a variety of different linestyles. More information about linestyle can be found on Matplotlib website."
},
{
"code": null,
"e": 2997,
"s": 2957,
"text": "4. change the size of label and numbers"
},
{
"code": null,
"e": 3358,
"s": 2997,
"text": "vd2=venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)venn2_circles([set(Course1), set(Course2)], linestyle=’-.’, linewidth=2, color=’black’)for text in vd2.set_labels: #change label size text.set_fontsize(16);for text in vd2.subset_labels: #change number size text.set_fontsize(16)plt.show()"
},
{
"code": null,
"e": 3384,
"s": 3358,
"text": "5. add title to the chart"
},
{
"code": null,
"e": 3437,
"s": 3384,
"text": "To complete the Venn diagram, title has to be added."
},
{
"code": null,
"e": 3926,
"s": 3437,
"text": "vd2=venn2([set(Course1), set(Course2)],set_labels=(‘Course1’, ‘Course2’),set_colors=(‘orange’, ‘darkgrey’), alpha = 0.8)venn2_circles([set(Course1), set(Course2)], linestyle=’-.’, linewidth=2, color=’black’)for text in vd2.set_labels: text.set_fontsize(16);for text in vd2.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for Course1 and Course2’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20,pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);plt.show()"
},
{
"code": null,
"e": 4039,
"s": 3926,
"text": "Drawing a Venn diagram with 3 Groups has no significant difference from generating a Venn diagram with 2 Groups."
},
{
"code": null,
"e": 4566,
"s": 4039,
"text": "vd3=venn3([set(Course1),set(Course2),set(Course3)], set_labels=(‘Course1’, ‘Course2’,’Course3'), set_colors=(‘#c4e6ff’, ‘#F4ACB7’,’#9D8189'), alpha = 0.8)venn3_circles([set(Course1), set(Course2),set(Course3)], linestyle=’-.’, linewidth=2, color=’grey’)for text in vd3.set_labels: text.set_fontsize(16);for text in vd3.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for 3 courses’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20, pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);plt.show()"
},
{
"code": null,
"e": 4664,
"s": 4566,
"text": "Matplotlib allows us to customize each circle separately. Let us customize the upper left circle."
},
{
"code": null,
"e": 5255,
"s": 4664,
"text": "vd3=venn3([set(Course1),set(Course2),set(Course3)], set_labels=(‘Course1’, ‘Course2’,’Course3'), set_colors=(‘#c4e6ff’, ‘#F4ACB7’,’#9D8189'), alpha = 0.8)c=venn3_circles([set(Course1), set(Course2),set(Course3)], linestyle=’-.’, linewidth=2, color=’grey’)for text in vd3.set_labels: text.set_fontsize(16);for text in vd3.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for 3 courses’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20, pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);c[0].set_lw(3.0) #customize upper left circle c[0].set_ls(‘:’)plt.show()"
},
{
"code": null,
"e": 5434,
"s": 5255,
"text": "The color of the circle can be customized as well. However, if we assign a new color to the circle, it will overwrite the colors we set by parameter set_colors in venn3 function."
},
{
"code": null,
"e": 6020,
"s": 5434,
"text": "vd3=venn3([set(Course1),set(Course2),set(Course3)], set_labels=(‘Course1’, ‘Course2’,’Course3'), set_colors=(‘#c4e6ff’, ‘#F4ACB7’,’#9D8189'), alpha = 0.8)c=venn3_circles([set(Course1), set(Course2),set(Course3)], linestyle=’-.’, linewidth=2, color=’grey’)for text in vd3.set_labels: text.set_fontsize(16);for text in vd3.subset_labels: text.set_fontsize(16)plt.title(‘Venn Diagram for 3 courses’,fontname=’Times New Roman’,fontweight=’bold’,fontsize=20, pad=30,backgroundcolor=’#cbe7e3',color=’black’,style=’italic’);c[0].set_lw(7.0)c[0].set_ls(‘:’)c[0].set_color(‘#c4e6ff’)plt.show()"
}
]
|
How to define alternate names to a field using Jackson in Java? | The @JsonAlias annotation can define one or more alternate names for the attributes accepted during the deserialization, setting the JSON data to a Java object. But when serializing, i.e. getting JSON from a Java object, only the actual logical property name is used instead of the alias.
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonAlias
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class ObjectToJsonTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Technology tech = new Technology("Java", "Oracle");
Employee emp = new Employee(110, "Raja", tech);
String jsonWriter = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(jsonWriter);
}
}
// Technology class
class Technology {
@JsonProperty("skill")
private String skill;
@JsonProperty("subSkill")
@JsonAlias({"sSkill", "mySubSkill"})
private String subSkill;
public Technology(){}
public Technology(String skill, String subSkill) {
this.skill = skill;
this.subSkill = subSkill;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
public String getSubSkill() {
return subSkill;
}
public void setSubSkill(String subSkill) {
this.subSkill = subSkill;
}
}
// Employee class
class Employee {
@JsonProperty("empId")
private Integer id;
@JsonProperty("empName")
@JsonAlias({"ename", "myename"})
private String name;
@JsonProperty("empTechnology")
private Technology tech;
public Employee(){}
public Employee(Integer id, String name, Technology tech){
this.id = id;
this.name = name;
this.tech = tech;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Technology getTechnology() {
return tech;
}
public void setTechnology(Technology tech) {
this.tech = tech;
}
}
{
"technology" : {
"skill" : "Java",
"subSkill" : "Oracle"
},
"empId" : 110,
"empName" : "Raja",
"empTechnology" : {
"skill" : "Java",
"subSkill" : "Oracle"
}
} | [
{
"code": null,
"e": 1351,
"s": 1062,
"text": "The @JsonAlias annotation can define one or more alternate names for the attributes accepted during the deserialization, setting the JSON data to a Java object. But when serializing, i.e. getting JSON from a Java object, only the actual logical property name is used instead of the alias."
},
{
"code": null,
"e": 1461,
"s": 1351,
"text": "@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER})\n@Retention(value=RUNTIME)\npublic @interface JsonAlias"
},
{
"code": null,
"e": 3368,
"s": 1461,
"text": "import com.fasterxml.jackson.annotation.*;\nimport com.fasterxml.jackson.core.*;\nimport com.fasterxml.jackson.databind.*;\nimport java.io.*;\npublic class ObjectToJsonTest {\n public static void main(String[] args) throws JsonProcessingException {\n ObjectMapper mapper = new ObjectMapper();\n Technology tech = new Technology(\"Java\", \"Oracle\");\n Employee emp = new Employee(110, \"Raja\", tech);\n String jsonWriter = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);\n System.out.println(jsonWriter);\n }\n}\n// Technology class\nclass Technology {\n @JsonProperty(\"skill\")\n private String skill;\n @JsonProperty(\"subSkill\")\n @JsonAlias({\"sSkill\", \"mySubSkill\"})\n private String subSkill;\n public Technology(){}\n public Technology(String skill, String subSkill) {\n this.skill = skill;\n this.subSkill = subSkill;\n }\n public String getSkill() {\n return skill;\n }\n public void setSkill(String skill) {\n this.skill = skill;\n }\n public String getSubSkill() {\n return subSkill;\n }\n public void setSubSkill(String subSkill) {\n this.subSkill = subSkill;\n }\n}\n// Employee class\nclass Employee {\n @JsonProperty(\"empId\")\n private Integer id;\n @JsonProperty(\"empName\")\n @JsonAlias({\"ename\", \"myename\"})\n private String name;\n @JsonProperty(\"empTechnology\")\n private Technology tech;\n public Employee(){}\n public Employee(Integer id, String name, Technology tech){\n this.id = id;\n this.name = name;\n this.tech = tech;\n }\n public Integer getId() {\n return id;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public Technology getTechnology() {\n return tech;\n }\n public void setTechnology(Technology tech) {\n this.tech = tech;\n }\n}"
},
{
"code": null,
"e": 3539,
"s": 3368,
"text": "{\n \"technology\" : {\n \"skill\" : \"Java\",\n \"subSkill\" : \"Oracle\"\n },\n \"empId\" : 110,\n \"empName\" : \"Raja\",\n \"empTechnology\" : {\n \"skill\" : \"Java\",\n \"subSkill\" : \"Oracle\"\n }\n}"
}
]
|
Android - ImageButton Control | An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This shows a button with an image (instead of text) that can be pressed or clicked by the user.
Following are the important attributes related to ImageButton control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time.
Inherited from android.widget.ImageView Class −
android:adjustViewBounds
Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.
android:baseline
This is the offset of the baseline within this view.
android:baselineAlignBottom
If true, the image view will be baseline aligned with based on its bottom edge.
android:cropToPadding
If true, the image will be cropped to fit within its padding.
android:src
This sets a drawable as the content of this ImageView.
Inherited from android.view.View Class −
android:background
This is a drawable to use as the background.
android:contentDescription
This defines text that briefly describes content of the view.
android:id
This supplies an identifier name for this view
android:onClick
This is the name of the method in this View's context to invoke when the view is clicked.
android:visibility
This controls the initial visibility of the view.
This example will take you through simple steps to show how to create your own Android application using Linear Layout and ImageButton.
Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
ImageButton imgButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton =(ImageButton)findViewById(R.id.imageButton);
imgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"You download is
resumed",Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView android:text="Tutorials Point"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<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 myapplication application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
The following screen will appear after ImageButton is clicked,It shows a toast message.
I will recommend to try above example with different attributes of ImageButton in Layout XML file as well at programming time to have different look and feel of the ImageButton. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple ImageButton controls in one activity.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3804,
"s": 3607,
"text": "An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This shows a button with an image (instead of text) that can be pressed or clicked by the user."
},
{
"code": null,
"e": 4031,
"s": 3804,
"text": "Following are the important attributes related to ImageButton control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time."
},
{
"code": null,
"e": 4079,
"s": 4031,
"text": "Inherited from android.widget.ImageView Class −"
},
{
"code": null,
"e": 4104,
"s": 4079,
"text": "android:adjustViewBounds"
},
{
"code": null,
"e": 4214,
"s": 4104,
"text": "Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable."
},
{
"code": null,
"e": 4231,
"s": 4214,
"text": "android:baseline"
},
{
"code": null,
"e": 4284,
"s": 4231,
"text": "This is the offset of the baseline within this view."
},
{
"code": null,
"e": 4312,
"s": 4284,
"text": "android:baselineAlignBottom"
},
{
"code": null,
"e": 4392,
"s": 4312,
"text": "If true, the image view will be baseline aligned with based on its bottom edge."
},
{
"code": null,
"e": 4414,
"s": 4392,
"text": "android:cropToPadding"
},
{
"code": null,
"e": 4476,
"s": 4414,
"text": "If true, the image will be cropped to fit within its padding."
},
{
"code": null,
"e": 4488,
"s": 4476,
"text": "android:src"
},
{
"code": null,
"e": 4543,
"s": 4488,
"text": "This sets a drawable as the content of this ImageView."
},
{
"code": null,
"e": 4584,
"s": 4543,
"text": "Inherited from android.view.View Class −"
},
{
"code": null,
"e": 4603,
"s": 4584,
"text": "android:background"
},
{
"code": null,
"e": 4648,
"s": 4603,
"text": "This is a drawable to use as the background."
},
{
"code": null,
"e": 4675,
"s": 4648,
"text": "android:contentDescription"
},
{
"code": null,
"e": 4737,
"s": 4675,
"text": "This defines text that briefly describes content of the view."
},
{
"code": null,
"e": 4748,
"s": 4737,
"text": "android:id"
},
{
"code": null,
"e": 4795,
"s": 4748,
"text": "This supplies an identifier name for this view"
},
{
"code": null,
"e": 4811,
"s": 4795,
"text": "android:onClick"
},
{
"code": null,
"e": 4901,
"s": 4811,
"text": "This is the name of the method in this View's context to invoke when the view is clicked."
},
{
"code": null,
"e": 4920,
"s": 4901,
"text": "android:visibility"
},
{
"code": null,
"e": 4970,
"s": 4920,
"text": "This controls the initial visibility of the view."
},
{
"code": null,
"e": 5106,
"s": 4970,
"text": "This example will take you through simple steps to show how to create your own Android application using Linear Layout and ImageButton."
},
{
"code": null,
"e": 5280,
"s": 5106,
"text": "Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 6075,
"s": 5280,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.ImageButton;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n ImageButton imgButton;\n \n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n imgButton =(ImageButton)findViewById(R.id.imageButton);\n imgButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(),\"You download is \n resumed\",Toast.LENGTH_LONG).show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 6144,
"s": 6075,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 7250,
"s": 6144,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n \n <TextView android:text=\"Tutorials Point\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"30dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_alignRight=\"@+id/imageButton\"\n android:layout_alignEnd=\"@+id/imageButton\" />\n \n <ImageButton\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageButton\"\n android:layout_centerVertical=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:src=\"@drawable/abc\"/>\n\n</RelativeLayout>"
},
{
"code": null,
"e": 7339,
"s": 7250,
"text": "Following will be the content of res/values/strings.xml to define these new constants −"
},
{
"code": null,
"e": 7453,
"s": 7339,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">myapplication</string>\n</resources>"
},
{
"code": null,
"e": 7512,
"s": 7453,
"text": "Following is the default content of AndroidManifest.xml −"
},
{
"code": null,
"e": 8227,
"s": 7512,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 8618,
"s": 8227,
"text": "Let's try to run your myapplication application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 8706,
"s": 8618,
"text": "The following screen will appear after ImageButton is clicked,It shows a toast message."
},
{
"code": null,
"e": 9067,
"s": 8706,
"text": "I will recommend to try above example with different attributes of ImageButton in Layout XML file as well at programming time to have different look and feel of the ImageButton. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple ImageButton controls in one activity."
},
{
"code": null,
"e": 9102,
"s": 9067,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9114,
"s": 9102,
"text": " Aditya Dua"
},
{
"code": null,
"e": 9149,
"s": 9114,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9163,
"s": 9149,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 9195,
"s": 9163,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9212,
"s": 9195,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9247,
"s": 9212,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9264,
"s": 9247,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9299,
"s": 9264,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9316,
"s": 9299,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9349,
"s": 9316,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9366,
"s": 9349,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9373,
"s": 9366,
"text": " Print"
},
{
"code": null,
"e": 9384,
"s": 9373,
"text": " Add Notes"
}
]
|
Get all text of the page using Selenium in Python - GeeksforGeeks | 25 Feb, 2021
As we know Selenium is an automation tool through which we can automate the browsers by writing some lines of code. It is compatible with all browsers, Operating systems and also its program can be written in any programming language such as Python, Java, and many more.
Selenium provides a convenient API to access Selenium WebDrivers like Firefox, IE, Chrome, Remote etc. The currently supported Python versions are 3.5 and above.
Installation:
Use pip to install the Selenium package. Just write this below command on Command Prompt.
pip install selenium
Once installation gets done. Open Python Console and just write these two commands for verifying whether Selenium is installed or not.
Python3
import selenium print(selenium.__version__)
Output:
'3.141.0'
Previously, We should download binary chromedriver and Unzip it somewhere on our PC and also set a path. After that, set path to this driver like this:
webdriver.Chrome(executable_path=”D:\PyCharm_Projects\SeleniumLearning\Drivers\ChromeDriverServer.exe”)
But Every time, the new version of the driver released, so we need to download a new driver otherwise it will give us errors. For Solving this issue, we need to install webdriver-manager:
Installation:
pip install webdriver-manager
If we are using chrome driver, then we need to write these lines:
Python3
from selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install())
Like Chrome, We have some other browsers also. For Example:
Use with Chromium:
Python3
from selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManagerfrom webdriver_manager.utils import ChromeType driver = webdriver.Chrome(ChromeDriverManager(chrome_type = ChromeType.CHROMIUM).install())
Use with FireFox:
Python3
from selenium import webdriverfrom webdriver_manager.firefox import GeckoDriverManager driver = webdriver.Firefox(executable_path = GeckoDriverManager().install())
Use with IE:
Python3
from selenium import webdriverfrom webdriver_manager.microsoft import IEDriverManager driver = webdriver.Ie(IEDriverManager().install())
Use with Edge:
Python3
from selenium import webdriverfrom webdriver_manager.microsoft import EdgeChromiumDriverManager driver = webdriver.Edge(EdgeChromiumDriverManager().install())
Let’s learn how to automate the tasks with the help of selenium in Python Programming. Here in this article, We are discussing how to get all text of the page using selenium.
Approach:
Import the webdriver from selenium moduleHere, in this article, we will automate the task on Chrome browser. So, We have to import ChromeDriverManager from the webdriver_manager.chrome. Now, We are not required to download any drivers from the internet. This command will automatically download the drivers from the Internet. Currently, Supported WebDriver implementations are Firefox, Chrome, IE, and Remote.Installing the Chrome driver and store in the instance of webdriver.The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page gets fully loaded before returning control to our program.WebDriver gives various ways to find the elements in our page using one of the find_element_by_* methods. For example, Body section of the given page can be located with the help of it’s xpath, we will use the find_element_by_xpath method.Finally, for closing the browser window. We will use the driver.close method. One more method, we have driver.exit method which closes entire browsers where driver.close will close only one window tab.
Import the webdriver from selenium module
Here, in this article, we will automate the task on Chrome browser. So, We have to import ChromeDriverManager from the webdriver_manager.chrome. Now, We are not required to download any drivers from the internet. This command will automatically download the drivers from the Internet. Currently, Supported WebDriver implementations are Firefox, Chrome, IE, and Remote.
Installing the Chrome driver and store in the instance of webdriver.
The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page gets fully loaded before returning control to our program.
WebDriver gives various ways to find the elements in our page using one of the find_element_by_* methods. For example, Body section of the given page can be located with the help of it’s xpath, we will use the find_element_by_xpath method.
Finally, for closing the browser window. We will use the driver.close method. One more method, we have driver.exit method which closes entire browsers where driver.close will close only one window tab.
Below is the Implementation:
Python3
# Importing necessary modulesfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # WebDriver Chromedriver = webdriver.Chrome(ChromeDriverManager().install()) # Target URLdriver.get("https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/") # print(driver.title) # Printing the whole body textprint(driver.find_element_by_xpath("/html/body").text) # Closing the driverdriver.close()
Output:
Picked
Python Selenium-Exercises
Python-selenium
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 24172,
"s": 23901,
"text": "As we know Selenium is an automation tool through which we can automate the browsers by writing some lines of code. It is compatible with all browsers, Operating systems and also its program can be written in any programming language such as Python, Java, and many more."
},
{
"code": null,
"e": 24334,
"s": 24172,
"text": "Selenium provides a convenient API to access Selenium WebDrivers like Firefox, IE, Chrome, Remote etc. The currently supported Python versions are 3.5 and above."
},
{
"code": null,
"e": 24348,
"s": 24334,
"text": "Installation:"
},
{
"code": null,
"e": 24438,
"s": 24348,
"text": "Use pip to install the Selenium package. Just write this below command on Command Prompt."
},
{
"code": null,
"e": 24459,
"s": 24438,
"text": "pip install selenium"
},
{
"code": null,
"e": 24594,
"s": 24459,
"text": "Once installation gets done. Open Python Console and just write these two commands for verifying whether Selenium is installed or not."
},
{
"code": null,
"e": 24602,
"s": 24594,
"text": "Python3"
},
{
"code": "import selenium print(selenium.__version__)",
"e": 24647,
"s": 24602,
"text": null
},
{
"code": null,
"e": 24655,
"s": 24647,
"text": "Output:"
},
{
"code": null,
"e": 24665,
"s": 24655,
"text": "'3.141.0'"
},
{
"code": null,
"e": 24817,
"s": 24665,
"text": "Previously, We should download binary chromedriver and Unzip it somewhere on our PC and also set a path. After that, set path to this driver like this:"
},
{
"code": null,
"e": 24921,
"s": 24817,
"text": "webdriver.Chrome(executable_path=”D:\\PyCharm_Projects\\SeleniumLearning\\Drivers\\ChromeDriverServer.exe”)"
},
{
"code": null,
"e": 25109,
"s": 24921,
"text": "But Every time, the new version of the driver released, so we need to download a new driver otherwise it will give us errors. For Solving this issue, we need to install webdriver-manager:"
},
{
"code": null,
"e": 25123,
"s": 25109,
"text": "Installation:"
},
{
"code": null,
"e": 25153,
"s": 25123,
"text": "pip install webdriver-manager"
},
{
"code": null,
"e": 25219,
"s": 25153,
"text": "If we are using chrome driver, then we need to write these lines:"
},
{
"code": null,
"e": 25227,
"s": 25219,
"text": "Python3"
},
{
"code": "from selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install())",
"e": 25374,
"s": 25227,
"text": null
},
{
"code": null,
"e": 25434,
"s": 25374,
"text": "Like Chrome, We have some other browsers also. For Example:"
},
{
"code": null,
"e": 25453,
"s": 25434,
"text": "Use with Chromium:"
},
{
"code": null,
"e": 25461,
"s": 25453,
"text": "Python3"
},
{
"code": "from selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManagerfrom webdriver_manager.utils import ChromeType driver = webdriver.Chrome(ChromeDriverManager(chrome_type = ChromeType.CHROMIUM).install())",
"e": 25687,
"s": 25461,
"text": null
},
{
"code": null,
"e": 25705,
"s": 25687,
"text": "Use with FireFox:"
},
{
"code": null,
"e": 25713,
"s": 25705,
"text": "Python3"
},
{
"code": "from selenium import webdriverfrom webdriver_manager.firefox import GeckoDriverManager driver = webdriver.Firefox(executable_path = GeckoDriverManager().install())",
"e": 25878,
"s": 25713,
"text": null
},
{
"code": null,
"e": 25891,
"s": 25878,
"text": "Use with IE:"
},
{
"code": null,
"e": 25899,
"s": 25891,
"text": "Python3"
},
{
"code": "from selenium import webdriverfrom webdriver_manager.microsoft import IEDriverManager driver = webdriver.Ie(IEDriverManager().install())",
"e": 26037,
"s": 25899,
"text": null
},
{
"code": null,
"e": 26052,
"s": 26037,
"text": "Use with Edge:"
},
{
"code": null,
"e": 26060,
"s": 26052,
"text": "Python3"
},
{
"code": "from selenium import webdriverfrom webdriver_manager.microsoft import EdgeChromiumDriverManager driver = webdriver.Edge(EdgeChromiumDriverManager().install())",
"e": 26220,
"s": 26060,
"text": null
},
{
"code": null,
"e": 26395,
"s": 26220,
"text": "Let’s learn how to automate the tasks with the help of selenium in Python Programming. Here in this article, We are discussing how to get all text of the page using selenium."
},
{
"code": null,
"e": 26405,
"s": 26395,
"text": "Approach:"
},
{
"code": null,
"e": 27481,
"s": 26405,
"text": "Import the webdriver from selenium moduleHere, in this article, we will automate the task on Chrome browser. So, We have to import ChromeDriverManager from the webdriver_manager.chrome. Now, We are not required to download any drivers from the internet. This command will automatically download the drivers from the Internet. Currently, Supported WebDriver implementations are Firefox, Chrome, IE, and Remote.Installing the Chrome driver and store in the instance of webdriver.The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page gets fully loaded before returning control to our program.WebDriver gives various ways to find the elements in our page using one of the find_element_by_* methods. For example, Body section of the given page can be located with the help of it’s xpath, we will use the find_element_by_xpath method.Finally, for closing the browser window. We will use the driver.close method. One more method, we have driver.exit method which closes entire browsers where driver.close will close only one window tab."
},
{
"code": null,
"e": 27523,
"s": 27481,
"text": "Import the webdriver from selenium module"
},
{
"code": null,
"e": 27892,
"s": 27523,
"text": "Here, in this article, we will automate the task on Chrome browser. So, We have to import ChromeDriverManager from the webdriver_manager.chrome. Now, We are not required to download any drivers from the internet. This command will automatically download the drivers from the Internet. Currently, Supported WebDriver implementations are Firefox, Chrome, IE, and Remote."
},
{
"code": null,
"e": 27961,
"s": 27892,
"text": "Installing the Chrome driver and store in the instance of webdriver."
},
{
"code": null,
"e": 28119,
"s": 27961,
"text": "The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page gets fully loaded before returning control to our program."
},
{
"code": null,
"e": 28360,
"s": 28119,
"text": "WebDriver gives various ways to find the elements in our page using one of the find_element_by_* methods. For example, Body section of the given page can be located with the help of it’s xpath, we will use the find_element_by_xpath method."
},
{
"code": null,
"e": 28562,
"s": 28360,
"text": "Finally, for closing the browser window. We will use the driver.close method. One more method, we have driver.exit method which closes entire browsers where driver.close will close only one window tab."
},
{
"code": null,
"e": 28591,
"s": 28562,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 28599,
"s": 28591,
"text": "Python3"
},
{
"code": "# Importing necessary modulesfrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManager # WebDriver Chromedriver = webdriver.Chrome(ChromeDriverManager().install()) # Target URLdriver.get(\"https://www.geeksforgeeks.org/competitive-programming-a-complete-guide/\") # print(driver.title) # Printing the whole body textprint(driver.find_element_by_xpath(\"/html/body\").text) # Closing the driverdriver.close()",
"e": 29037,
"s": 28599,
"text": null
},
{
"code": null,
"e": 29045,
"s": 29037,
"text": "Output:"
},
{
"code": null,
"e": 29052,
"s": 29045,
"text": "Picked"
},
{
"code": null,
"e": 29078,
"s": 29052,
"text": "Python Selenium-Exercises"
},
{
"code": null,
"e": 29094,
"s": 29078,
"text": "Python-selenium"
},
{
"code": null,
"e": 29118,
"s": 29094,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29125,
"s": 29118,
"text": "Python"
},
{
"code": null,
"e": 29144,
"s": 29125,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29242,
"s": 29144,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29251,
"s": 29242,
"text": "Comments"
},
{
"code": null,
"e": 29264,
"s": 29251,
"text": "Old Comments"
},
{
"code": null,
"e": 29296,
"s": 29264,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29352,
"s": 29296,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29394,
"s": 29352,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29436,
"s": 29394,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29472,
"s": 29436,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29494,
"s": 29472,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29533,
"s": 29494,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29560,
"s": 29533,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29591,
"s": 29560,
"text": "Python | os.path.join() method"
}
]
|
Cordova - Dialogs | The Cordova Dialogs plugin will call the platform native dialog UI element.
Type the following command in the command prompt window to install this plugin.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-dialogs
Let us now open index.html and add four buttons, one for every type of dialog.
<button id = "dialogAlert">ALERT</button>
<button id = "dialogConfirm">CONFIRM</button>
<button id = "dialogPrompt">PROMPT</button>
<button id = "dialogBeep">BEEP</button>
Now we will add the event listeners inside the onDeviceReady function in index.js. The listeners will call the callback function once the corresponding button is clicked.
document.getElementById("dialogAlert").addEventListener("click", dialogAlert);
document.getElementById("dialogConfirm").addEventListener("click", dialogConfirm);
document.getElementById("dialogPrompt").addEventListener("click", dialogPrompt);
document.getElementById("dialogBeep").addEventListener("click", dialogBeep);
Since we added four event listeners, we will now create the callback functions for all of them in index.js. The first one is dialogAlert.
function dialogAlert() {
var message = "I am Alert Dialog!";
var title = "ALERT";
var buttonName = "Alert Button";
navigator.notification.alert(message, alertCallback, title, buttonName);
function alertCallback() {
console.log("Alert is Dismissed!");
}
}
If we click the ALERT button, we will get see the alert dialog box.
When we click the dialog button, the following output will be displayed on the console.
The second function we need to create is the dialogConfirm function.
function dialogConfirm() {
var message = "Am I Confirm Dialog?";
var title = "CONFIRM";
var buttonLabels = "YES,NO";
navigator.notification.confirm(message, confirmCallback, title, buttonLabels);
function confirmCallback(buttonIndex) {
console.log("You clicked " + buttonIndex + " button!");
}
}
When the CONFIRM button is pressed, the new dialog will pop up.
We will click the YES button to answer the question. The following output will be displayed on the console.
The third function is the dialogPrompt function. This allows the users to type text into the dialog input element.
function dialogPrompt() {
var message = "Am I Prompt Dialog?";
var title = "PROMPT";
var buttonLabels = ["YES","NO"];
var defaultText = "Default"
navigator.notification.prompt(message, promptCallback,
title, buttonLabels, defaultText);
function promptCallback(result) {
console.log("You clicked " + result.buttonIndex + " button! \n" +
"You entered " + result.input1);
}
}
The PROMPT button will trigger a dialog box as in the following screenshot.
In this dialog box, we have an option to type the text. We will log this text in the console, together with a button that is clicked.
The last one is the dialogBeep function. This is used for calling the audio beep notification. The times parameter will set the number of repeats for the beep signal.
function dialogBeep() {
var times = 2;
navigator.notification.beep(times);
}
When we click the BEEP button, we will hear the notification sound twice, since the times value is set to 2.
45 Lectures
2 hours
Skillbakerystudios
16 Lectures
1 hours
Nilay Mehta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2256,
"s": 2180,
"text": "The Cordova Dialogs plugin will call the platform native dialog UI element."
},
{
"code": null,
"e": 2336,
"s": 2256,
"text": "Type the following command in the command prompt window to install this plugin."
},
{
"code": null,
"e": 2420,
"s": 2336,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-dialogs\n"
},
{
"code": null,
"e": 2499,
"s": 2420,
"text": "Let us now open index.html and add four buttons, one for every type of dialog."
},
{
"code": null,
"e": 2671,
"s": 2499,
"text": "<button id = \"dialogAlert\">ALERT</button>\n<button id = \"dialogConfirm\">CONFIRM</button>\n<button id = \"dialogPrompt\">PROMPT</button>\n<button id = \"dialogBeep\">BEEP</button>"
},
{
"code": null,
"e": 2842,
"s": 2671,
"text": "Now we will add the event listeners inside the onDeviceReady function in index.js. The listeners will call the callback function once the corresponding button is clicked."
},
{
"code": null,
"e": 3163,
"s": 2842,
"text": "document.getElementById(\"dialogAlert\").addEventListener(\"click\", dialogAlert);\ndocument.getElementById(\"dialogConfirm\").addEventListener(\"click\", dialogConfirm);\ndocument.getElementById(\"dialogPrompt\").addEventListener(\"click\", dialogPrompt);\ndocument.getElementById(\"dialogBeep\").addEventListener(\"click\", dialogBeep);\t"
},
{
"code": null,
"e": 3301,
"s": 3163,
"text": "Since we added four event listeners, we will now create the callback functions for all of them in index.js. The first one is dialogAlert."
},
{
"code": null,
"e": 3584,
"s": 3301,
"text": "function dialogAlert() {\n var message = \"I am Alert Dialog!\";\n var title = \"ALERT\";\n var buttonName = \"Alert Button\";\n navigator.notification.alert(message, alertCallback, title, buttonName);\n \n function alertCallback() {\n console.log(\"Alert is Dismissed!\");\n }\n}"
},
{
"code": null,
"e": 3652,
"s": 3584,
"text": "If we click the ALERT button, we will get see the alert dialog box."
},
{
"code": null,
"e": 3740,
"s": 3652,
"text": "When we click the dialog button, the following output will be displayed on the console."
},
{
"code": null,
"e": 3809,
"s": 3740,
"text": "The second function we need to create is the dialogConfirm function."
},
{
"code": null,
"e": 4132,
"s": 3809,
"text": "function dialogConfirm() {\n var message = \"Am I Confirm Dialog?\";\n var title = \"CONFIRM\";\n var buttonLabels = \"YES,NO\";\n navigator.notification.confirm(message, confirmCallback, title, buttonLabels);\n\n function confirmCallback(buttonIndex) {\n console.log(\"You clicked \" + buttonIndex + \" button!\");\n }\n\t\n}"
},
{
"code": null,
"e": 4196,
"s": 4132,
"text": "When the CONFIRM button is pressed, the new dialog will pop up."
},
{
"code": null,
"e": 4304,
"s": 4196,
"text": "We will click the YES button to answer the question. The following output will be displayed on the console."
},
{
"code": null,
"e": 4419,
"s": 4304,
"text": "The third function is the dialogPrompt function. This allows the users to type text into the dialog input element."
},
{
"code": null,
"e": 4840,
"s": 4419,
"text": "function dialogPrompt() {\n var message = \"Am I Prompt Dialog?\";\n var title = \"PROMPT\";\n var buttonLabels = [\"YES\",\"NO\"];\n var defaultText = \"Default\"\n navigator.notification.prompt(message, promptCallback, \n title, buttonLabels, defaultText);\n\n function promptCallback(result) {\n console.log(\"You clicked \" + result.buttonIndex + \" button! \\n\" + \n \"You entered \" + result.input1);\n }\n\t\n}"
},
{
"code": null,
"e": 4916,
"s": 4840,
"text": "The PROMPT button will trigger a dialog box as in the following screenshot."
},
{
"code": null,
"e": 5050,
"s": 4916,
"text": "In this dialog box, we have an option to type the text. We will log this text in the console, together with a button that is clicked."
},
{
"code": null,
"e": 5217,
"s": 5050,
"text": "The last one is the dialogBeep function. This is used for calling the audio beep notification. The times parameter will set the number of repeats for the beep signal."
},
{
"code": null,
"e": 5300,
"s": 5217,
"text": "function dialogBeep() {\n var times = 2;\n navigator.notification.beep(times);\n}"
},
{
"code": null,
"e": 5409,
"s": 5300,
"text": "When we click the BEEP button, we will hear the notification sound twice, since the times value is set to 2."
},
{
"code": null,
"e": 5442,
"s": 5409,
"text": "\n 45 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5462,
"s": 5442,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5495,
"s": 5462,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5508,
"s": 5495,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5515,
"s": 5508,
"text": " Print"
},
{
"code": null,
"e": 5526,
"s": 5515,
"text": " Add Notes"
}
]
|
ptrace() - Unix, Linux System Call | Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <sys/ptrace.h>
long ptrace(enum __ptrace_request request, pid_t pid,
void *addr, void *data);
long ptrace(enum __ptrace_request request, pid_t pid,
void *addr, void *data);
The parent can initiate a trace by calling
fork(2)
and having the resulting child do a PTRACE_TRACEME,
followed (typically) by an
exec(3).
Alternatively, the parent may commence trace of an existing process using
PTRACE_ATTACH.
While being traced, the child will stop each time a signal is delivered,
even if the signal is being ignored.
(The exception is SIGKILL, which has its usual effect.)
The parent will be notified at its next
wait(2)
and may inspect and modify the child process while it is stopped.
The parent then causes the child to continue,
optionally ignoring the delivered signal
(or even delivering a different signal instead).
When the parent is finished tracing, it can terminate the child with
PTRACE_KILL or cause it to continue executing in a normal, untraced mode
via PTRACE_DETACH.
The value of request determines the action to be performed:
init(8),
the process with PID 1, may not be traced.
The layout of the contents of memory and the USER area are quite OS- and
architecture-specific. The offset supplied and the data returned might
not entirely match with the definition of
struct user
The size of a "word" is determined by the OS variant
(e.g., for 32-bit Linux it’s 32 bits, etc.).
Tracing causes a few subtle differences in the semantics of
traced processes.
For example, if a process is attached to with PTRACE_ATTACH,
its original parent can no longer receive notification via
wait() when it stops, and there is no way for the new parent to
effectively simulate this notification.
This page documents the way the
ptrace() call works currently in Linux.
Its behavior differs noticeably on other flavors of Unix.
In any case, use of
ptrace() is highly OS- and architecture-specific.
The SunOS man page describes
ptrace() as "unique and arcane", which it is.
The proc-based debugging interface
present in Solaris 2 implements a superset of
ptrace() functionality in a more powerful and uniform way.
gdb (1)
gdb (1)
strace (1)
strace (1)
execve (2)
execve (2)
fork (2)
fork (2)
signal (2)
signal (2)
wait (2)
wait (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2440,
"s": 2319,
"text": "#include <sys/ptrace.h> \n\nlong ptrace(enum __ptrace_request request, pid_t pid, \n void *addr, void *data); \n"
},
{
"code": null,
"e": 2536,
"s": 2440,
"text": "\nlong ptrace(enum __ptrace_request request, pid_t pid, \n void *addr, void *data); \n"
},
{
"code": null,
"e": 2766,
"s": 2536,
"text": "\nThe parent can initiate a trace by calling\nfork(2)\nand having the resulting child do a PTRACE_TRACEME,\nfollowed (typically) by an\nexec(3).\nAlternatively, the parent may commence trace of an existing process using\nPTRACE_ATTACH.\n"
},
{
"code": null,
"e": 3187,
"s": 2766,
"text": "\nWhile being traced, the child will stop each time a signal is delivered,\neven if the signal is being ignored. \n(The exception is SIGKILL, which has its usual effect.) \nThe parent will be notified at its next\nwait(2)\nand may inspect and modify the child process while it is stopped. \nThe parent then causes the child to continue,\noptionally ignoring the delivered signal\n(or even delivering a different signal instead).\n"
},
{
"code": null,
"e": 3350,
"s": 3187,
"text": "\nWhen the parent is finished tracing, it can terminate the child with\nPTRACE_KILL or cause it to continue executing in a normal, untraced mode\nvia PTRACE_DETACH.\n"
},
{
"code": null,
"e": 3412,
"s": 3350,
"text": "\nThe value of request determines the action to be performed:\n"
},
{
"code": null,
"e": 3466,
"s": 3412,
"text": "\ninit(8),\nthe process with PID 1, may not be traced.\n"
},
{
"code": null,
"e": 3666,
"s": 3466,
"text": "\nThe layout of the contents of memory and the USER area are quite OS- and\narchitecture-specific. The offset supplied and the data returned might\nnot entirely match with the definition of\nstruct user "
},
{
"code": null,
"e": 3766,
"s": 3666,
"text": "\nThe size of a \"word\" is determined by the OS variant\n(e.g., for 32-bit Linux it’s 32 bits, etc.).\n"
},
{
"code": null,
"e": 4070,
"s": 3766,
"text": "\nTracing causes a few subtle differences in the semantics of\ntraced processes.\nFor example, if a process is attached to with PTRACE_ATTACH,\nits original parent can no longer receive notification via\nwait() when it stops, and there is no way for the new parent to\neffectively simulate this notification.\n"
},
{
"code": null,
"e": 4274,
"s": 4070,
"text": "\nThis page documents the way the\nptrace() call works currently in Linux. \nIts behavior differs noticeably on other flavors of Unix. \nIn any case, use of\nptrace() is highly OS- and architecture-specific.\n"
},
{
"code": null,
"e": 4492,
"s": 4274,
"text": "\nThe SunOS man page describes\nptrace() as \"unique and arcane\", which it is. \nThe proc-based debugging interface\npresent in Solaris 2 implements a superset of\nptrace() functionality in a more powerful and uniform way.\n"
},
{
"code": null,
"e": 4500,
"s": 4492,
"text": "gdb (1)"
},
{
"code": null,
"e": 4508,
"s": 4500,
"text": "gdb (1)"
},
{
"code": null,
"e": 4519,
"s": 4508,
"text": "strace (1)"
},
{
"code": null,
"e": 4530,
"s": 4519,
"text": "strace (1)"
},
{
"code": null,
"e": 4541,
"s": 4530,
"text": "execve (2)"
},
{
"code": null,
"e": 4552,
"s": 4541,
"text": "execve (2)"
},
{
"code": null,
"e": 4561,
"s": 4552,
"text": "fork (2)"
},
{
"code": null,
"e": 4570,
"s": 4561,
"text": "fork (2)"
},
{
"code": null,
"e": 4581,
"s": 4570,
"text": "signal (2)"
},
{
"code": null,
"e": 4592,
"s": 4581,
"text": "signal (2)"
},
{
"code": null,
"e": 4601,
"s": 4592,
"text": "wait (2)"
},
{
"code": null,
"e": 4610,
"s": 4601,
"text": "wait (2)"
},
{
"code": null,
"e": 4627,
"s": 4610,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 4662,
"s": 4627,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 4690,
"s": 4662,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4724,
"s": 4690,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4741,
"s": 4724,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4774,
"s": 4741,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4785,
"s": 4774,
"text": " Pradeep D"
},
{
"code": null,
"e": 4820,
"s": 4785,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4836,
"s": 4820,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4869,
"s": 4836,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4881,
"s": 4869,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 4913,
"s": 4881,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4921,
"s": 4913,
"text": " Uplatz"
},
{
"code": null,
"e": 4928,
"s": 4921,
"text": " Print"
},
{
"code": null,
"e": 4939,
"s": 4928,
"text": " Add Notes"
}
]
|
Java program to find if the given number is a leap year? | Finding a year is a leap or not is a bit tricky. We generally assume that if a year number is evenly divisible by 4 is a leap year. But it is not the only case. A year is a leap year if −
1. It is evenly divisible by 100
2. If it is divisible by 100, then it should also be divisible by 400
3. Except this, all other years evenly divisible by 4 are leap years.
1. Take integer variable year
2. Assign a value to the variable
3. Check if the year is divisible by 4 but not 100, DISPLAY "leap year"
4. Check if the year is divisible by 400, DISPLAY "leap year"
5. Otherwise, DISPLAY "not leap year"
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args){
int year;
System.out.println("Enter an Year :: ");
Scanner sc = new Scanner(System.in);
year = sc.nextInt();
if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
System.out.println("Specified year is a leap year");
else
System.out.println("Specified year is not a leap year");
}
}
Enter an Year ::
2020
Specified year is a leap year
Java Programming questions
31
Enter an Year ::
2017
Specified year is not a leap year | [
{
"code": null,
"e": 1250,
"s": 1062,
"text": "Finding a year is a leap or not is a bit tricky. We generally assume that if a year number is evenly divisible by 4 is a leap year. But it is not the only case. A year is a leap year if −"
},
{
"code": null,
"e": 1283,
"s": 1250,
"text": "1. It is evenly divisible by 100"
},
{
"code": null,
"e": 1353,
"s": 1283,
"text": "2. If it is divisible by 100, then it should also be divisible by 400"
},
{
"code": null,
"e": 1423,
"s": 1353,
"text": "3. Except this, all other years evenly divisible by 4 are leap years."
},
{
"code": null,
"e": 1453,
"s": 1423,
"text": "1. Take integer variable year"
},
{
"code": null,
"e": 1487,
"s": 1453,
"text": "2. Assign a value to the variable"
},
{
"code": null,
"e": 1559,
"s": 1487,
"text": "3. Check if the year is divisible by 4 but not 100, DISPLAY \"leap year\""
},
{
"code": null,
"e": 1621,
"s": 1559,
"text": "4. Check if the year is divisible by 400, DISPLAY \"leap year\""
},
{
"code": null,
"e": 1659,
"s": 1621,
"text": "5. Otherwise, DISPLAY \"not leap year\""
},
{
"code": null,
"e": 2100,
"s": 1659,
"text": "import java.util.Scanner;\npublic class LeapYear {\n public static void main(String[] args){\n int year;\n System.out.println(\"Enter an Year :: \");\n Scanner sc = new Scanner(System.in);\n year = sc.nextInt();\n\n if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))\n System.out.println(\"Specified year is a leap year\");\n else\n System.out.println(\"Specified year is not a leap year\");\n }\n}"
},
{
"code": null,
"e": 2152,
"s": 2100,
"text": "Enter an Year ::\n2020\nSpecified year is a leap year"
},
{
"code": null,
"e": 2238,
"s": 2152,
"text": "Java Programming questions\n31\nEnter an Year ::\n2017\nSpecified year is not a leap year"
}
]
|
wxPython - Slider Class | A slider presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. Position of the handle on the groove is equivalent to an integer between the lower and upper bounds of the control.
wxPython API contains wx.Slider class. It offers same functionality as that of Scrollbar. Slider offers a convenient way to handle dragging the handle by slider specific wx.EVT_SLIDER event binder.
The definition of wx.Slider constructor takes the following eight parameters −
wx.Slider(parent, id, value, minValue, maxValue, pos, size, style)
Slider’s lower and upper values are set by minValue and maxValue parameters. The starting value is defined by the value parameter.
Many style parameter values are defined. Following are some of them −
wxSL_HORIZONTAL
Horizontal slider
wxSL_VERTICAL
Vertical slider
wxSL_AUTOTICKS
Displays tickmarks on the slider
wxSL_LABELS
Displays the min, max, and current value
wxSL_MIN_MAX_LABELS
Displays the min and max value
wxSL_VALUE_LABEL
Displays the current value only
The useful methods of wx.Slider class are −
GetMin()
Returns the minimum value of the slider
GetMax()
Returns the maximum value of the slider
GetValue()
Returns the current value of the slider
SetMin()
Sets the minimum value of the slider
SetMax()
Sets the maximum value of the slider
SetRange()
Sets the minimum and maximum slider values
SetValue()
Sets the current value programmatically
SetTick()
Displays the tick mark at the given position
SetTickFreq()
Sets the tick interval between the min and max values
As the slider behaves similar to a scroll bar, the scroll bar event binders can also be used along with it.
wx.EVT_SCROLL
Processes the scroll event
wx.EVT_SLIDER
When the slider position changes, either by moving the handle or programmatically
In the example that follows, the slider is used to control the size of a label. First of all, a slider object is placed in a vertical box sizer below which is a StaticText.
self.sld = wx.Slider(pnl, value = 10, minValue = 1, maxValue = 100,
style = wx.SL_HORIZONTAL|wx.SL_LABELS)
self.txt = wx.StaticText(pnl, label = 'Hello',style = wx.ALIGN_CENTER)
Wx.EVT_SLIDER binder is associated with OnSliderScroll() handler.
self.sld.Bind(wx.EVT_SLIDER, self.OnSliderScroll)
The handler itself is fetching slider’s current value and using it as font size for the label’s text.
def OnSliderScroll(self, e):
obj = e.GetEventObject()
val = obj.GetValue()
font = self.GetFont()
font.SetPointSize(self.sld.GetValue())
self.txt.SetFont(font)
The complete code is as follows −
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title = title,size = (250,150))
self.InitUI()
def InitUI(self):
pnl = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
self.sld = wx.Slider(pnl, value = 10, minValue = 1, maxValue = 100,
style = wx.SL_HORIZONTAL|wx.SL_LABELS)
vbox.Add(self.sld,1,flag = wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, border = 20)
self.sld.Bind(wx.EVT_SLIDER, self.OnSliderScroll)
self.txt = wx.StaticText(pnl, label = 'Hello',style = wx.ALIGN_CENTER)
vbox.Add(self.txt,1,wx.ALIGN_CENTRE_HORIZONTAL)
pnl.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnSliderScroll(self, e):
obj = e.GetEventObject()
val = obj.GetValue()
font = self.GetFont()
font.SetPointSize(self.sld.GetValue())
self.txt.SetFont(font)
ex = wx.App()
Mywin(None,'Slider demo')
ex.MainLoop()
Run the code and try dragging the slider handle to see the label’s font size changing. The above code produces the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2124,
"s": 1882,
"text": "A slider presents the user with a groove over which a handle can be moved. It is a classic widget to control a bounded value. Position of the handle on the groove is equivalent to an integer between the lower and upper bounds of the control."
},
{
"code": null,
"e": 2322,
"s": 2124,
"text": "wxPython API contains wx.Slider class. It offers same functionality as that of Scrollbar. Slider offers a convenient way to handle dragging the handle by slider specific wx.EVT_SLIDER event binder."
},
{
"code": null,
"e": 2401,
"s": 2322,
"text": "The definition of wx.Slider constructor takes the following eight parameters −"
},
{
"code": null,
"e": 2469,
"s": 2401,
"text": "wx.Slider(parent, id, value, minValue, maxValue, pos, size, style)\n"
},
{
"code": null,
"e": 2600,
"s": 2469,
"text": "Slider’s lower and upper values are set by minValue and maxValue parameters. The starting value is defined by the value parameter."
},
{
"code": null,
"e": 2670,
"s": 2600,
"text": "Many style parameter values are defined. Following are some of them −"
},
{
"code": null,
"e": 2686,
"s": 2670,
"text": "wxSL_HORIZONTAL"
},
{
"code": null,
"e": 2704,
"s": 2686,
"text": "Horizontal slider"
},
{
"code": null,
"e": 2718,
"s": 2704,
"text": "wxSL_VERTICAL"
},
{
"code": null,
"e": 2734,
"s": 2718,
"text": "Vertical slider"
},
{
"code": null,
"e": 2749,
"s": 2734,
"text": "wxSL_AUTOTICKS"
},
{
"code": null,
"e": 2782,
"s": 2749,
"text": "Displays tickmarks on the slider"
},
{
"code": null,
"e": 2794,
"s": 2782,
"text": "wxSL_LABELS"
},
{
"code": null,
"e": 2835,
"s": 2794,
"text": "Displays the min, max, and current value"
},
{
"code": null,
"e": 2855,
"s": 2835,
"text": "wxSL_MIN_MAX_LABELS"
},
{
"code": null,
"e": 2886,
"s": 2855,
"text": "Displays the min and max value"
},
{
"code": null,
"e": 2903,
"s": 2886,
"text": "wxSL_VALUE_LABEL"
},
{
"code": null,
"e": 2935,
"s": 2903,
"text": "Displays the current value only"
},
{
"code": null,
"e": 2979,
"s": 2935,
"text": "The useful methods of wx.Slider class are −"
},
{
"code": null,
"e": 2988,
"s": 2979,
"text": "GetMin()"
},
{
"code": null,
"e": 3028,
"s": 2988,
"text": "Returns the minimum value of the slider"
},
{
"code": null,
"e": 3037,
"s": 3028,
"text": "GetMax()"
},
{
"code": null,
"e": 3077,
"s": 3037,
"text": "Returns the maximum value of the slider"
},
{
"code": null,
"e": 3088,
"s": 3077,
"text": "GetValue()"
},
{
"code": null,
"e": 3128,
"s": 3088,
"text": "Returns the current value of the slider"
},
{
"code": null,
"e": 3137,
"s": 3128,
"text": "SetMin()"
},
{
"code": null,
"e": 3174,
"s": 3137,
"text": "Sets the minimum value of the slider"
},
{
"code": null,
"e": 3183,
"s": 3174,
"text": "SetMax()"
},
{
"code": null,
"e": 3220,
"s": 3183,
"text": "Sets the maximum value of the slider"
},
{
"code": null,
"e": 3231,
"s": 3220,
"text": "SetRange()"
},
{
"code": null,
"e": 3274,
"s": 3231,
"text": "Sets the minimum and maximum slider values"
},
{
"code": null,
"e": 3285,
"s": 3274,
"text": "SetValue()"
},
{
"code": null,
"e": 3325,
"s": 3285,
"text": "Sets the current value programmatically"
},
{
"code": null,
"e": 3335,
"s": 3325,
"text": "SetTick()"
},
{
"code": null,
"e": 3380,
"s": 3335,
"text": "Displays the tick mark at the given position"
},
{
"code": null,
"e": 3394,
"s": 3380,
"text": "SetTickFreq()"
},
{
"code": null,
"e": 3448,
"s": 3394,
"text": "Sets the tick interval between the min and max values"
},
{
"code": null,
"e": 3556,
"s": 3448,
"text": "As the slider behaves similar to a scroll bar, the scroll bar event binders can also be used along with it."
},
{
"code": null,
"e": 3570,
"s": 3556,
"text": "wx.EVT_SCROLL"
},
{
"code": null,
"e": 3597,
"s": 3570,
"text": "Processes the scroll event"
},
{
"code": null,
"e": 3611,
"s": 3597,
"text": "wx.EVT_SLIDER"
},
{
"code": null,
"e": 3693,
"s": 3611,
"text": "When the slider position changes, either by moving the handle or programmatically"
},
{
"code": null,
"e": 3866,
"s": 3693,
"text": "In the example that follows, the slider is used to control the size of a label. First of all, a slider object is placed in a vertical box sizer below which is a StaticText."
},
{
"code": null,
"e": 4049,
"s": 3866,
"text": "self.sld = wx.Slider(pnl, value = 10, minValue = 1, maxValue = 100,\n style = wx.SL_HORIZONTAL|wx.SL_LABELS)\n\t\nself.txt = wx.StaticText(pnl, label = 'Hello',style = wx.ALIGN_CENTER)"
},
{
"code": null,
"e": 4115,
"s": 4049,
"text": "Wx.EVT_SLIDER binder is associated with OnSliderScroll() handler."
},
{
"code": null,
"e": 4166,
"s": 4115,
"text": "self.sld.Bind(wx.EVT_SLIDER, self.OnSliderScroll)\n"
},
{
"code": null,
"e": 4268,
"s": 4166,
"text": "The handler itself is fetching slider’s current value and using it as font size for the label’s text."
},
{
"code": null,
"e": 4448,
"s": 4268,
"text": "def OnSliderScroll(self, e): \n obj = e.GetEventObject() \n val = obj.GetValue() \n font = self.GetFont() \n font.SetPointSize(self.sld.GetValue()) \n self.txt.SetFont(font) "
},
{
"code": null,
"e": 4482,
"s": 4448,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 5539,
"s": 4482,
"text": "import wx \n \nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (250,150)) \n self.InitUI() \n \n def InitUI(self): \n pnl = wx.Panel(self) \n vbox = wx.BoxSizer(wx.VERTICAL) \n\t\t\n self.sld = wx.Slider(pnl, value = 10, minValue = 1, maxValue = 100,\n style = wx.SL_HORIZONTAL|wx.SL_LABELS) \n\t\t\t\n vbox.Add(self.sld,1,flag = wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, border = 20) \n self.sld.Bind(wx.EVT_SLIDER, self.OnSliderScroll) \n self.txt = wx.StaticText(pnl, label = 'Hello',style = wx.ALIGN_CENTER) \n vbox.Add(self.txt,1,wx.ALIGN_CENTRE_HORIZONTAL) \n\t\t\n pnl.SetSizer(vbox) \n self.Centre() \n self.Show(True) \n\t\t\n def OnSliderScroll(self, e): \n obj = e.GetEventObject() \n val = obj.GetValue() \n font = self.GetFont() \n font.SetPointSize(self.sld.GetValue()) \n self.txt.SetFont(font) \n\t\t\nex = wx.App() \nMywin(None,'Slider demo') \nex.MainLoop()"
},
{
"code": null,
"e": 5673,
"s": 5539,
"text": "Run the code and try dragging the slider handle to see the label’s font size changing. The above code produces the following output −"
},
{
"code": null,
"e": 5680,
"s": 5673,
"text": " Print"
},
{
"code": null,
"e": 5691,
"s": 5680,
"text": " Add Notes"
}
]
|
MariaDB - Table Cloning | Some situations require producing an exact copy of an existing table. The CREATE...SELECT statement cannot produce this output because it neglects things like indexes and default values.
The procedure for a duplicating a table is as follows −
Utilize SHOW CREATE TABLE to produce a CREATE TABLE statement that details the entire structure of the source table.
Utilize SHOW CREATE TABLE to produce a CREATE TABLE statement that details the entire structure of the source table.
Edit the statement to give the table a new name, and execute it.
Edit the statement to give the table a new name, and execute it.
Use an INSERT INTO...SELECT statement if you also need the table data copied.
Use an INSERT INTO...SELECT statement if you also need the table data copied.
mysql> INSERT INTO inventory_copy_tbl (
product_id,product_name,product_manufacturer,ship_date)
SELECT product_id,product_name,product_manufacturer,ship_date,
FROM inventory_tbl;
Another method for creating a duplicate uses a CREATE TABLE AS statement. The statement copies all columns, column definitions, and populates the copy with the source table's data.
Review its syntax given below −
CREATE TABLE clone_tbl AS
SELECT columns
FROM original_tbl
WHERE conditions];
Review an example of its use below −
CREATE TABLE products_copy_tbl AS
SELECT *
FROM products_tbl;
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2549,
"s": 2362,
"text": "Some situations require producing an exact copy of an existing table. The CREATE...SELECT statement cannot produce this output because it neglects things like indexes and default values."
},
{
"code": null,
"e": 2605,
"s": 2549,
"text": "The procedure for a duplicating a table is as follows −"
},
{
"code": null,
"e": 2722,
"s": 2605,
"text": "Utilize SHOW CREATE TABLE to produce a CREATE TABLE statement that details the entire structure of the source table."
},
{
"code": null,
"e": 2839,
"s": 2722,
"text": "Utilize SHOW CREATE TABLE to produce a CREATE TABLE statement that details the entire structure of the source table."
},
{
"code": null,
"e": 2904,
"s": 2839,
"text": "Edit the statement to give the table a new name, and execute it."
},
{
"code": null,
"e": 2969,
"s": 2904,
"text": "Edit the statement to give the table a new name, and execute it."
},
{
"code": null,
"e": 3047,
"s": 2969,
"text": "Use an INSERT INTO...SELECT statement if you also need the table data copied."
},
{
"code": null,
"e": 3125,
"s": 3047,
"text": "Use an INSERT INTO...SELECT statement if you also need the table data copied."
},
{
"code": null,
"e": 3318,
"s": 3125,
"text": "mysql> INSERT INTO inventory_copy_tbl (\n product_id,product_name,product_manufacturer,ship_date)\n \n SELECT product_id,product_name,product_manufacturer,ship_date,\n FROM inventory_tbl;\n"
},
{
"code": null,
"e": 3499,
"s": 3318,
"text": "Another method for creating a duplicate uses a CREATE TABLE AS statement. The statement copies all columns, column definitions, and populates the copy with the source table's data."
},
{
"code": null,
"e": 3531,
"s": 3499,
"text": "Review its syntax given below −"
},
{
"code": null,
"e": 3619,
"s": 3531,
"text": "CREATE TABLE clone_tbl AS\n SELECT columns\n FROM original_tbl\n WHERE conditions];\n"
},
{
"code": null,
"e": 3656,
"s": 3619,
"text": "Review an example of its use below −"
},
{
"code": null,
"e": 3725,
"s": 3656,
"text": "CREATE TABLE products_copy_tbl AS\n SELECT *\n FROM products_tbl;\n"
},
{
"code": null,
"e": 3732,
"s": 3725,
"text": " Print"
},
{
"code": null,
"e": 3743,
"s": 3732,
"text": " Add Notes"
}
]
|
JCL - Base Library | Base Library is the Partitioned Dataset (PDS), which holds the load modules of the program to be executed in the JCL or the catalogued procedure, which is called in the program. Base libraries can be specified for the whole JCL in a JOBLIB library or for a particular job step in a STEPLIB statement.
A JOBLIB statement is used in order to identify the location of the program to be executed in a JCL. The JOBLIB statement is specified after the JOB statement and before the EXEC statement. This can be used only for the in stream procedures and programs.
Following is the basic syntax of a JCL JOBLIB statement:
//JOBLIB DD DSN=dsnname,DISP=SHR
The JOBLIB statement is applicable to all the EXEC statements within the JCL. The program specified in the EXEC statement will be searched in the JOBLIB library followed by the system library.
For example, if the EXEC statement is executing a COBOL program, the load module of the COBOL program should be placed within the JOBLIB library.
A STEPLIB statement is used in order to identify the location of the program to be executed within a Job Step. The STEPLIB statement is specified after the EXEC statement and before the DD statement of the job step.
Following is the basic syntax of a JCL STEPLIB statement:
//STEPLIB DD DSN=dsnname,DISP=SHR
The program specified in the EXEC statement will be searched in the STEPLIB library followed by the system library. STEPLIB coded in a job step overrides the JOBLIB statement.
The following example shows the usage of JOBLIB and STEPLIB statements:
//MYJCL JOB ,,CLASS=6,NOTIFY=&SYSUID
//*
//JOBLIB DD DSN=MYPROC.BASE.LIB1,DISP=SHR
//*
//STEP1 EXEC PGM=MYPROG1
//INPUT1 DD DSN=MYFILE.SAMPLE.INPUT1,DISP=SHR
//OUTPUT1 DD DSN=MYFILES.SAMPLE.OUTPUT1,DISP=(,CATLG,DELETE),
// RECFM=FB,LRECL=80
//*
//STEP2 EXEC PGM=MYPROG2
//STEPLIB DD DSN=MYPROC.BASE.LIB2,DISP=SHR
//INPUT2 DD DSN=MYFILE.SAMPLE.INPUT2,DISP=SHR
//OUTPUT2 DD DSN=MYFILES.SAMPLE.OUTPUT2,DISP=(,CATLG,DELETE),
// RECFM=FB,LRECL=80
Here, the load module of the program MYPROG1 (in STEP1) is searched in the MYPROC.SAMPLE.LIB1. If not found, it is searched in the system library. In STEP2, STEPLIB overrides JOBLIB and load module of the program MYPROG2 is searched in MYPROC.SAMPLE.LIB2 and then in the system library.
A set of JCL statements coded within a member of a PDS can be included to a JCL using an INCLUDE statement. When the JES interprets the JCL, the set of JCL statements within the INCLUDE member replaces the INCLUDE statement.
Following is the basic syntax of a JCL INCLUDE statement:
//name INCLUDE MEMBER=member-name
The main purpose of INCLUDE statement is reusability. For example, common files to be used across many JCLs can be coded as DD statements within INCLUDE member and used in a JCL.
Dummy DD statements, data card specifications, PROCs, JOB, PROC statements cannot be coded within an INCLUDE member. An INLCUDE statement can be coded within an INCLUDE member and further nesting can be done up to 15 levels.
A JCLLIB statement is used to identify the private libraries used in the job. It can be used both with instream and cataloged procedures.
Following is the basic syntax of a JCL JCLLIB statement:
//name JCLLIB ORDER=(library1, library2....)
The libraries specified in the JCLLIB statement will be searched in the given order to locate the programs, procedures and INCLUDE member used in the job. There can be only one JCLLIB statement in a JCL; specified after a JOB statement and before EXEC and INCLUDE statement but it cannot be coded within an INCLUDE member.
In the following example, the program MYPROG3 and INCLUDE member MYINCL is searched in the order of MYPROC.BASE.LIB1, MYPROC.BASE.LIB2, system library.
//MYJCL JOB ,,CLASS=6,NOTIFY=&SYSUID
//*
//MYLIB JCLLIB ORDER=(MYPROC.BASE.LIB1,MYPROC.BASE.LIB2)
//*
//STEP1 EXEC PGM=MYPROG3
//INC INCLUDE MEMBER=MYINCL
//OUTPUT1 DD DSN=MYFILES.SAMPLE.OUTPUT1,DISP=(,CATLG,DELETE),
// RECFM=FB,LRECL=80
//*
12 Lectures
2 hours
Nishant Malik
73 Lectures
4.5 hours
Topictrick Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2165,
"s": 1864,
"text": "Base Library is the Partitioned Dataset (PDS), which holds the load modules of the program to be executed in the JCL or the catalogued procedure, which is called in the program. Base libraries can be specified for the whole JCL in a JOBLIB library or for a particular job step in a STEPLIB statement."
},
{
"code": null,
"e": 2420,
"s": 2165,
"text": "A JOBLIB statement is used in order to identify the location of the program to be executed in a JCL. The JOBLIB statement is specified after the JOB statement and before the EXEC statement. This can be used only for the in stream procedures and programs."
},
{
"code": null,
"e": 2477,
"s": 2420,
"text": "Following is the basic syntax of a JCL JOBLIB statement:"
},
{
"code": null,
"e": 2548,
"s": 2477,
"text": "//JOBLIB DD DSN=dsnname,DISP=SHR "
},
{
"code": null,
"e": 2741,
"s": 2548,
"text": "The JOBLIB statement is applicable to all the EXEC statements within the JCL. The program specified in the EXEC statement will be searched in the JOBLIB library followed by the system library."
},
{
"code": null,
"e": 2887,
"s": 2741,
"text": "For example, if the EXEC statement is executing a COBOL program, the load module of the COBOL program should be placed within the JOBLIB library."
},
{
"code": null,
"e": 3103,
"s": 2887,
"text": "A STEPLIB statement is used in order to identify the location of the program to be executed within a Job Step. The STEPLIB statement is specified after the EXEC statement and before the DD statement of the job step."
},
{
"code": null,
"e": 3161,
"s": 3103,
"text": "Following is the basic syntax of a JCL STEPLIB statement:"
},
{
"code": null,
"e": 3233,
"s": 3161,
"text": "//STEPLIB DD DSN=dsnname,DISP=SHR "
},
{
"code": null,
"e": 3409,
"s": 3233,
"text": "The program specified in the EXEC statement will be searched in the STEPLIB library followed by the system library. STEPLIB coded in a job step overrides the JOBLIB statement."
},
{
"code": null,
"e": 3481,
"s": 3409,
"text": "The following example shows the usage of JOBLIB and STEPLIB statements:"
},
{
"code": null,
"e": 3981,
"s": 3481,
"text": "//MYJCL JOB ,,CLASS=6,NOTIFY=&SYSUID\n//*\n//JOBLIB DD DSN=MYPROC.BASE.LIB1,DISP=SHR\n//*\n//STEP1 EXEC PGM=MYPROG1\n//INPUT1 DD DSN=MYFILE.SAMPLE.INPUT1,DISP=SHR\n//OUTPUT1 DD DSN=MYFILES.SAMPLE.OUTPUT1,DISP=(,CATLG,DELETE),\n// RECFM=FB,LRECL=80\n//*\n//STEP2 EXEC PGM=MYPROG2\n//STEPLIB DD DSN=MYPROC.BASE.LIB2,DISP=SHR\n//INPUT2 DD DSN=MYFILE.SAMPLE.INPUT2,DISP=SHR\n//OUTPUT2 DD DSN=MYFILES.SAMPLE.OUTPUT2,DISP=(,CATLG,DELETE),\n// RECFM=FB,LRECL=80 "
},
{
"code": null,
"e": 4268,
"s": 3981,
"text": "Here, the load module of the program MYPROG1 (in STEP1) is searched in the MYPROC.SAMPLE.LIB1. If not found, it is searched in the system library. In STEP2, STEPLIB overrides JOBLIB and load module of the program MYPROG2 is searched in MYPROC.SAMPLE.LIB2 and then in the system library."
},
{
"code": null,
"e": 4493,
"s": 4268,
"text": "A set of JCL statements coded within a member of a PDS can be included to a JCL using an INCLUDE statement. When the JES interprets the JCL, the set of JCL statements within the INCLUDE member replaces the INCLUDE statement."
},
{
"code": null,
"e": 4551,
"s": 4493,
"text": "Following is the basic syntax of a JCL INCLUDE statement:"
},
{
"code": null,
"e": 4623,
"s": 4551,
"text": "//name INCLUDE MEMBER=member-name "
},
{
"code": null,
"e": 4802,
"s": 4623,
"text": "The main purpose of INCLUDE statement is reusability. For example, common files to be used across many JCLs can be coded as DD statements within INCLUDE member and used in a JCL."
},
{
"code": null,
"e": 5027,
"s": 4802,
"text": "Dummy DD statements, data card specifications, PROCs, JOB, PROC statements cannot be coded within an INCLUDE member. An INLCUDE statement can be coded within an INCLUDE member and further nesting can be done up to 15 levels."
},
{
"code": null,
"e": 5165,
"s": 5027,
"text": "A JCLLIB statement is used to identify the private libraries used in the job. It can be used both with instream and cataloged procedures."
},
{
"code": null,
"e": 5222,
"s": 5165,
"text": "Following is the basic syntax of a JCL JCLLIB statement:"
},
{
"code": null,
"e": 5301,
"s": 5222,
"text": "//name JCLLIB ORDER=(library1, library2....) "
},
{
"code": null,
"e": 5624,
"s": 5301,
"text": "The libraries specified in the JCLLIB statement will be searched in the given order to locate the programs, procedures and INCLUDE member used in the job. There can be only one JCLLIB statement in a JCL; specified after a JOB statement and before EXEC and INCLUDE statement but it cannot be coded within an INCLUDE member."
},
{
"code": null,
"e": 5776,
"s": 5624,
"text": "In the following example, the program MYPROG3 and INCLUDE member MYINCL is searched in the order of MYPROC.BASE.LIB1, MYPROC.BASE.LIB2, system library."
},
{
"code": null,
"e": 6060,
"s": 5776,
"text": "//MYJCL JOB ,,CLASS=6,NOTIFY=&SYSUID\n//*\n//MYLIB JCLLIB ORDER=(MYPROC.BASE.LIB1,MYPROC.BASE.LIB2)\n//*\n//STEP1 EXEC PGM=MYPROG3\n//INC INCLUDE MEMBER=MYINCL\n//OUTPUT1 DD DSN=MYFILES.SAMPLE.OUTPUT1,DISP=(,CATLG,DELETE),\n// RECFM=FB,LRECL=80\n//* "
},
{
"code": null,
"e": 6093,
"s": 6060,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6108,
"s": 6093,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6143,
"s": 6108,
"text": "\n 73 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6165,
"s": 6143,
"text": " Topictrick Education"
},
{
"code": null,
"e": 6172,
"s": 6165,
"text": " Print"
},
{
"code": null,
"e": 6183,
"s": 6172,
"text": " Add Notes"
}
]
|
Batch Script - XCOPY | This batch command copies files and directories in a more advanced way.
Xcopy [source][destination]
Xcopy c:\lists.txt c:\tp\
The above command will copy the file lists.txt to the tp folder.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2241,
"s": 2169,
"text": "This batch command copies files and directories in a more advanced way."
},
{
"code": null,
"e": 2270,
"s": 2241,
"text": "Xcopy [source][destination]\n"
},
{
"code": null,
"e": 2296,
"s": 2270,
"text": "Xcopy c:\\lists.txt c:\\tp\\"
},
{
"code": null,
"e": 2361,
"s": 2296,
"text": "The above command will copy the file lists.txt to the tp folder."
},
{
"code": null,
"e": 2368,
"s": 2361,
"text": " Print"
},
{
"code": null,
"e": 2379,
"s": 2368,
"text": " Add Notes"
}
]
|
Convolutional Neural Network for Breast Cancer Classification | by Abhinav Sagar | Towards Data Science | Stuck behind the paywall? Click here to read the full story with my Friend Link!
Breast cancer is the second most common cancer in women and men worldwide. In 2012, it represented about 12 percent of all new cancer cases and 25 percent of all cancers in women.
Breast cancer starts when cells in the breast begin to grow out of control. These cells usually form a tumor that can often be seen on an x-ray or felt as a lump. The tumor is malignant (cancer) if the cells can grow into (invade) surrounding tissues or spread (metastasize) to distant areas of the body.
Build an algorithm to automatically identify whether a patient is suffering from breast cancer or not by looking at biopsy images. The algorithm had to be extremely accurate because lives of people is at stake.
The dataset can be downloaded from here. This is a binary classification problem. I split the data as shown-
dataset train benign b1.jpg b2.jpg // malignant m1.jpg m2.jpg // validation benign b1.jpg b2.jpg // malignant m1.jpg m2.jpg //...
The training folder has 1000 images in each category while the validation folder has 250 images in each category.
Let’s go step by step and analyze each layer in the Convolutional Neural Network.
A Matrix of pixel values in the shape of [WIDTH, HEIGHT, CHANNELS]. Let’s assume that our input is [32x32x3].
The purpose of this layer is to receive a feature map. Usually, we start with low number of filters for low-level feature detection. The deeper we go into the CNN, the more filters we use to detect high-level features. Feature detection is based on ‘scanning’ the input with the filter of a given size and applying matrix computations in order to derive a feature map.
The goal of this layer is to provide spatial variance, which simply means that the system will be capable of recognizing an object even when its appearance varies in some way. Pooling layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in output such as [16x16x12] for pooling_size=(2, 2).
In a fully connected layer, we flatten the output of the last convolution layer and connect every node of the current layer with the other nodes of the next layer. Neurons in a fully connected layer have full connections to all activations in the previous layer, as seen in regular Neural Networks and work in a similar way.
The complete image classification pipeline can be formalized as follows:
Our input is a training dataset that consists of N images, each labeled with one of 2 different classes.
Then, we use this training set to train a classifier to learn what every one of the classes looks like.
In the end, we evaluate the quality of the classifier by asking it to predict labels for a new set of images that it has never seen before. We will then compare the true labels of these images to the ones predicted by the classifier.
Without much ado, let’s get started with the code. The complete project on github can be found here.
Let’s start with loading all the libraries and dependencies.
Next I loaded the images in the respective folders.
After that I created a numpy array of zeroes for labeling benign images and similarly a numpy array of ones for labeling malignant images. I also shuffled the dataset and converted the labels into categorical format.
Then I split the data-set into two sets — train and test sets with 80% and 20% images respectively. Let’s see some sample benign and malignant images.
I used a batch size value of 16. Batch size is one of the most important hyperparameters to tune in deep learning. I prefer to use a larger batch size to train my models as it allows computational speedups from the parallelism of GPUs. However, it is well known that too large of a batch size will lead to poor generalization. On the one extreme, using a batch equal to the entire dataset guarantees convergence to the global optima of the objective function. However this is at the cost of slower convergence to that optima. On the other hand, using smaller batch sizes have been shown to have faster convergence to good results. This is intuitively explained by the fact that smaller batch sizes allow the model to start learning before having to see all the data. The downside of using a smaller batch size is that the model is not guaranteed to converge to the global optima.Therefore it is often advised that one starts at a small batch size reaping the benefits of faster training dynamics and steadily grows the batch size through training.
I also did some data augmentation. The practice of data augmentation is an effective way to increase the size of the training set. Augmenting the training examples allow the network to see more diversified, but still representative data points during training.
Then I created a data generator to get the data from our folders and into Keras in an automated way. Keras provides convenient python generator functions for this purpose.
The next step was to build the model. This can be described in the following 3 steps:
I used DenseNet201 as the pre trained weights which is already trained in the Imagenet competition. The learning rate was chosen to be 0.0001.On top of it I used a globalaveragepooling layer followed by 50% dropouts to reduce over-fitting.I used batch normalization and a dense layer with 2 neurons for 2 output classes ie benign and malignant with softmax as the activation function.I have used Adam as the optimizer and binary-cross-entropy as the loss function.
I used DenseNet201 as the pre trained weights which is already trained in the Imagenet competition. The learning rate was chosen to be 0.0001.
On top of it I used a globalaveragepooling layer followed by 50% dropouts to reduce over-fitting.
I used batch normalization and a dense layer with 2 neurons for 2 output classes ie benign and malignant with softmax as the activation function.
I have used Adam as the optimizer and binary-cross-entropy as the loss function.
Let’s see the output shape and the parameters involved in each layer.
Before training the model, it is useful to define one or more callbacks. Pretty handy one, are: ModelCheckpoint and ReduceLROnPlateau.
ModelCheckpoint: When training requires a lot of time to achieve a good result, often many iterations are required. In this case, it is better to save a copy of the best performing model only when an epoch that improves the metrics ends.
ReduceLROnPlateau: Reduce learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2–10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced.
I trained the model for 20 epochs.
The most common metric for evaluating model performance is the accurcacy. However, when only 2% of your dataset is of one class (malignant) and 98% some other class (benign), misclassification scores don’t really make sense. You can be 98% accurate and still catch none of the malignant cases which could make a terrible classifier.
For a better look at misclassification, we often use the following metric to get a better idea of true positives (TP), true negatives (TN), false positive (FP) and false negative (FN).
Precision is the ratio of correctly predicted positive observations to the total predicted positive observations.
Recall is the ratio of correctly predicted positive observations to all the observations in actual class.
F1-Score is the weighted average of Precision and Recall.
The higher the F1-Score, the better the model. For all three metric, 0 is the worst while 1 is the best.
Confusion Matrix is a very important metric when analyzing misclassification. Each row of the matrix represents the instances in a predicted class while each column represents the instances in an actual class. The diagonals represent the classes that have been correctly classified. This helps as we not only know which classes are being misclassified but also what they are being misclassified as.
The 45 degree line is the random line, where the Area Under the Curve or AUC is 0.5 . The further the curve from this line, the higher the AUC and better the model. The highest a model can get is an AUC of 1, where the curve forms a right angled triangle. The ROC curve can also help debug a model. For example, if the bottom left corner of the curve is closer to the random line, it implies that the model is misclassifying at Y=0. Whereas, if it is random on the top right, it implies the errors are occurring at Y=1.
Although this project is far from complete but it is remarkable to see the success of deep learning in such varied real world problems. In this blog, I have demonstrated how to classify benign and malignant breast cancer from a collection of microscopic images using convolutional neural networks and transfer learning.
towardsdatascience.com
towardsdatascience.com
journals.plos.org
becominghuman.ai
The corresponding source code can be found here.
github.com
If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details:
Personal Website
Linkedin
Medium Profile
GitHub
Kaggle
Happy reading, happy learning and happy coding! | [
{
"code": null,
"e": 252,
"s": 171,
"text": "Stuck behind the paywall? Click here to read the full story with my Friend Link!"
},
{
"code": null,
"e": 432,
"s": 252,
"text": "Breast cancer is the second most common cancer in women and men worldwide. In 2012, it represented about 12 percent of all new cancer cases and 25 percent of all cancers in women."
},
{
"code": null,
"e": 737,
"s": 432,
"text": "Breast cancer starts when cells in the breast begin to grow out of control. These cells usually form a tumor that can often be seen on an x-ray or felt as a lump. The tumor is malignant (cancer) if the cells can grow into (invade) surrounding tissues or spread (metastasize) to distant areas of the body."
},
{
"code": null,
"e": 948,
"s": 737,
"text": "Build an algorithm to automatically identify whether a patient is suffering from breast cancer or not by looking at biopsy images. The algorithm had to be extremely accurate because lives of people is at stake."
},
{
"code": null,
"e": 1057,
"s": 948,
"text": "The dataset can be downloaded from here. This is a binary classification problem. I split the data as shown-"
},
{
"code": null,
"e": 1224,
"s": 1057,
"text": "dataset train benign b1.jpg b2.jpg // malignant m1.jpg m2.jpg // validation benign b1.jpg b2.jpg // malignant m1.jpg m2.jpg //..."
},
{
"code": null,
"e": 1338,
"s": 1224,
"text": "The training folder has 1000 images in each category while the validation folder has 250 images in each category."
},
{
"code": null,
"e": 1420,
"s": 1338,
"text": "Let’s go step by step and analyze each layer in the Convolutional Neural Network."
},
{
"code": null,
"e": 1530,
"s": 1420,
"text": "A Matrix of pixel values in the shape of [WIDTH, HEIGHT, CHANNELS]. Let’s assume that our input is [32x32x3]."
},
{
"code": null,
"e": 1899,
"s": 1530,
"text": "The purpose of this layer is to receive a feature map. Usually, we start with low number of filters for low-level feature detection. The deeper we go into the CNN, the more filters we use to detect high-level features. Feature detection is based on ‘scanning’ the input with the filter of a given size and applying matrix computations in order to derive a feature map."
},
{
"code": null,
"e": 2237,
"s": 1899,
"text": "The goal of this layer is to provide spatial variance, which simply means that the system will be capable of recognizing an object even when its appearance varies in some way. Pooling layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in output such as [16x16x12] for pooling_size=(2, 2)."
},
{
"code": null,
"e": 2562,
"s": 2237,
"text": "In a fully connected layer, we flatten the output of the last convolution layer and connect every node of the current layer with the other nodes of the next layer. Neurons in a fully connected layer have full connections to all activations in the previous layer, as seen in regular Neural Networks and work in a similar way."
},
{
"code": null,
"e": 2635,
"s": 2562,
"text": "The complete image classification pipeline can be formalized as follows:"
},
{
"code": null,
"e": 2740,
"s": 2635,
"text": "Our input is a training dataset that consists of N images, each labeled with one of 2 different classes."
},
{
"code": null,
"e": 2844,
"s": 2740,
"text": "Then, we use this training set to train a classifier to learn what every one of the classes looks like."
},
{
"code": null,
"e": 3078,
"s": 2844,
"text": "In the end, we evaluate the quality of the classifier by asking it to predict labels for a new set of images that it has never seen before. We will then compare the true labels of these images to the ones predicted by the classifier."
},
{
"code": null,
"e": 3179,
"s": 3078,
"text": "Without much ado, let’s get started with the code. The complete project on github can be found here."
},
{
"code": null,
"e": 3240,
"s": 3179,
"text": "Let’s start with loading all the libraries and dependencies."
},
{
"code": null,
"e": 3292,
"s": 3240,
"text": "Next I loaded the images in the respective folders."
},
{
"code": null,
"e": 3509,
"s": 3292,
"text": "After that I created a numpy array of zeroes for labeling benign images and similarly a numpy array of ones for labeling malignant images. I also shuffled the dataset and converted the labels into categorical format."
},
{
"code": null,
"e": 3660,
"s": 3509,
"text": "Then I split the data-set into two sets — train and test sets with 80% and 20% images respectively. Let’s see some sample benign and malignant images."
},
{
"code": null,
"e": 4708,
"s": 3660,
"text": "I used a batch size value of 16. Batch size is one of the most important hyperparameters to tune in deep learning. I prefer to use a larger batch size to train my models as it allows computational speedups from the parallelism of GPUs. However, it is well known that too large of a batch size will lead to poor generalization. On the one extreme, using a batch equal to the entire dataset guarantees convergence to the global optima of the objective function. However this is at the cost of slower convergence to that optima. On the other hand, using smaller batch sizes have been shown to have faster convergence to good results. This is intuitively explained by the fact that smaller batch sizes allow the model to start learning before having to see all the data. The downside of using a smaller batch size is that the model is not guaranteed to converge to the global optima.Therefore it is often advised that one starts at a small batch size reaping the benefits of faster training dynamics and steadily grows the batch size through training."
},
{
"code": null,
"e": 4969,
"s": 4708,
"text": "I also did some data augmentation. The practice of data augmentation is an effective way to increase the size of the training set. Augmenting the training examples allow the network to see more diversified, but still representative data points during training."
},
{
"code": null,
"e": 5141,
"s": 4969,
"text": "Then I created a data generator to get the data from our folders and into Keras in an automated way. Keras provides convenient python generator functions for this purpose."
},
{
"code": null,
"e": 5227,
"s": 5141,
"text": "The next step was to build the model. This can be described in the following 3 steps:"
},
{
"code": null,
"e": 5692,
"s": 5227,
"text": "I used DenseNet201 as the pre trained weights which is already trained in the Imagenet competition. The learning rate was chosen to be 0.0001.On top of it I used a globalaveragepooling layer followed by 50% dropouts to reduce over-fitting.I used batch normalization and a dense layer with 2 neurons for 2 output classes ie benign and malignant with softmax as the activation function.I have used Adam as the optimizer and binary-cross-entropy as the loss function."
},
{
"code": null,
"e": 5835,
"s": 5692,
"text": "I used DenseNet201 as the pre trained weights which is already trained in the Imagenet competition. The learning rate was chosen to be 0.0001."
},
{
"code": null,
"e": 5933,
"s": 5835,
"text": "On top of it I used a globalaveragepooling layer followed by 50% dropouts to reduce over-fitting."
},
{
"code": null,
"e": 6079,
"s": 5933,
"text": "I used batch normalization and a dense layer with 2 neurons for 2 output classes ie benign and malignant with softmax as the activation function."
},
{
"code": null,
"e": 6160,
"s": 6079,
"text": "I have used Adam as the optimizer and binary-cross-entropy as the loss function."
},
{
"code": null,
"e": 6230,
"s": 6160,
"text": "Let’s see the output shape and the parameters involved in each layer."
},
{
"code": null,
"e": 6365,
"s": 6230,
"text": "Before training the model, it is useful to define one or more callbacks. Pretty handy one, are: ModelCheckpoint and ReduceLROnPlateau."
},
{
"code": null,
"e": 6603,
"s": 6365,
"text": "ModelCheckpoint: When training requires a lot of time to achieve a good result, often many iterations are required. In this case, it is better to save a copy of the best performing model only when an epoch that improves the metrics ends."
},
{
"code": null,
"e": 6907,
"s": 6603,
"text": "ReduceLROnPlateau: Reduce learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2–10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced."
},
{
"code": null,
"e": 6942,
"s": 6907,
"text": "I trained the model for 20 epochs."
},
{
"code": null,
"e": 7275,
"s": 6942,
"text": "The most common metric for evaluating model performance is the accurcacy. However, when only 2% of your dataset is of one class (malignant) and 98% some other class (benign), misclassification scores don’t really make sense. You can be 98% accurate and still catch none of the malignant cases which could make a terrible classifier."
},
{
"code": null,
"e": 7460,
"s": 7275,
"text": "For a better look at misclassification, we often use the following metric to get a better idea of true positives (TP), true negatives (TN), false positive (FP) and false negative (FN)."
},
{
"code": null,
"e": 7574,
"s": 7460,
"text": "Precision is the ratio of correctly predicted positive observations to the total predicted positive observations."
},
{
"code": null,
"e": 7680,
"s": 7574,
"text": "Recall is the ratio of correctly predicted positive observations to all the observations in actual class."
},
{
"code": null,
"e": 7738,
"s": 7680,
"text": "F1-Score is the weighted average of Precision and Recall."
},
{
"code": null,
"e": 7843,
"s": 7738,
"text": "The higher the F1-Score, the better the model. For all three metric, 0 is the worst while 1 is the best."
},
{
"code": null,
"e": 8242,
"s": 7843,
"text": "Confusion Matrix is a very important metric when analyzing misclassification. Each row of the matrix represents the instances in a predicted class while each column represents the instances in an actual class. The diagonals represent the classes that have been correctly classified. This helps as we not only know which classes are being misclassified but also what they are being misclassified as."
},
{
"code": null,
"e": 8762,
"s": 8242,
"text": "The 45 degree line is the random line, where the Area Under the Curve or AUC is 0.5 . The further the curve from this line, the higher the AUC and better the model. The highest a model can get is an AUC of 1, where the curve forms a right angled triangle. The ROC curve can also help debug a model. For example, if the bottom left corner of the curve is closer to the random line, it implies that the model is misclassifying at Y=0. Whereas, if it is random on the top right, it implies the errors are occurring at Y=1."
},
{
"code": null,
"e": 9082,
"s": 8762,
"text": "Although this project is far from complete but it is remarkable to see the success of deep learning in such varied real world problems. In this blog, I have demonstrated how to classify benign and malignant breast cancer from a collection of microscopic images using convolutional neural networks and transfer learning."
},
{
"code": null,
"e": 9105,
"s": 9082,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9128,
"s": 9105,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9146,
"s": 9128,
"text": "journals.plos.org"
},
{
"code": null,
"e": 9163,
"s": 9146,
"text": "becominghuman.ai"
},
{
"code": null,
"e": 9212,
"s": 9163,
"text": "The corresponding source code can be found here."
},
{
"code": null,
"e": 9223,
"s": 9212,
"text": "github.com"
},
{
"code": null,
"e": 9348,
"s": 9223,
"text": "If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details:"
},
{
"code": null,
"e": 9365,
"s": 9348,
"text": "Personal Website"
},
{
"code": null,
"e": 9374,
"s": 9365,
"text": "Linkedin"
},
{
"code": null,
"e": 9389,
"s": 9374,
"text": "Medium Profile"
},
{
"code": null,
"e": 9396,
"s": 9389,
"text": "GitHub"
},
{
"code": null,
"e": 9403,
"s": 9396,
"text": "Kaggle"
}
]
|
\textbf - Tex Command | \textbf - Used to produce text-mode material in boldface within a mathematical expression.
{ \textbf #1}
\textbf command is used to produce text-mode material in boldface within a mathematical expression.
\textbf{\alpha in textbf mode }\alpha
\alpha in textbf mode α
\textbf{\alpha in textbf mode }\alpha
\alpha in textbf mode α
\textbf{\alpha in textbf mode }\alpha
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8077,
"s": 7986,
"text": "\\textbf - Used to produce text-mode material in boldface within a mathematical expression."
},
{
"code": null,
"e": 8091,
"s": 8077,
"text": "{ \\textbf #1}"
},
{
"code": null,
"e": 8191,
"s": 8091,
"text": "\\textbf command is used to produce text-mode material in boldface within a mathematical expression."
},
{
"code": null,
"e": 8258,
"s": 8191,
"text": "\n\\textbf{\\alpha in textbf mode }\\alpha\n\n\\alpha in textbf mode α\n\n\n"
},
{
"code": null,
"e": 8323,
"s": 8258,
"text": "\\textbf{\\alpha in textbf mode }\\alpha\n\n\\alpha in textbf mode α\n\n"
},
{
"code": null,
"e": 8361,
"s": 8323,
"text": "\\textbf{\\alpha in textbf mode }\\alpha"
},
{
"code": null,
"e": 8393,
"s": 8361,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8406,
"s": 8393,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8439,
"s": 8406,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8452,
"s": 8439,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8484,
"s": 8452,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8520,
"s": 8484,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8555,
"s": 8520,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8572,
"s": 8555,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8605,
"s": 8572,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8619,
"s": 8605,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8651,
"s": 8619,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8666,
"s": 8651,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8673,
"s": 8666,
"text": " Print"
},
{
"code": null,
"e": 8684,
"s": 8673,
"text": " Add Notes"
}
]
|
Art module in Python - GeeksforGeeks | 12 Nov, 2020
Art package is used to print decorative art’s on the terminal as well as to save in file and a word can be represented by ” | “and can be saved in a file
This module doesn’t come built-in with Python. To install this type the below command in the terminal.
pip install art
Function:
Printing Normal and random arts on terminal and aprint() functionPrinting a word in form of | and tprint() function also saving it in text/pdf file
Printing Normal and random arts on terminal and aprint() function
Printing a word in form of | and tprint() function also saving it in text/pdf file
Printing art on terminal:
Syntax: art ( name of art, number is integer denoting number of arts in string )
Python3
# import modulefrom art import * # return multiple art as strart__0=art("woman",number=10) print(art__0)
Output:
Random generation of arts:
Python3
from art import * print(art("random"))
Output:
Using aprint() function
Here, you can directly print arts just like the print function you print something
Python3
from art import * print("Buttterfly by art : ",end=" ") aprint("butterfly")print()
Output:
Now Let’s move towards the capability of python text to art
Python3
# import modulefrom art import * # Return ASCII text with block font# If font=None then there is no blockArt = text2art("GFG", font='block', chr_ignore=True) print(Art)
Output:
tprint() function is same as print() function it prints the text into ASCII format
Python3
# import modulefrom art import * # random large text to art representation # This art will be random every timetprint("GFG","rnd-xlarge")
Output:
We can save this to a txt file too by using tsave() function.
Syntax: tsave(“STRING”, OUTPUT FILE NAME OR PATH)
Python3
# import modulefrom art import * Filename = tsave( "GEEKSFORGEEKS", filename="Output_in_txt_file_using_tsave().txt")
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 24055,
"s": 23901,
"text": "Art package is used to print decorative art’s on the terminal as well as to save in file and a word can be represented by ” | “and can be saved in a file"
},
{
"code": null,
"e": 24159,
"s": 24055,
"text": "This module doesn’t come built-in with Python. To install this type the below command in the terminal. "
},
{
"code": null,
"e": 24178,
"s": 24159,
"text": " pip install art \n"
},
{
"code": null,
"e": 24188,
"s": 24178,
"text": "Function:"
},
{
"code": null,
"e": 24336,
"s": 24188,
"text": "Printing Normal and random arts on terminal and aprint() functionPrinting a word in form of | and tprint() function also saving it in text/pdf file"
},
{
"code": null,
"e": 24402,
"s": 24336,
"text": "Printing Normal and random arts on terminal and aprint() function"
},
{
"code": null,
"e": 24485,
"s": 24402,
"text": "Printing a word in form of | and tprint() function also saving it in text/pdf file"
},
{
"code": null,
"e": 24511,
"s": 24485,
"text": "Printing art on terminal:"
},
{
"code": null,
"e": 24592,
"s": 24511,
"text": "Syntax: art ( name of art, number is integer denoting number of arts in string )"
},
{
"code": null,
"e": 24600,
"s": 24592,
"text": "Python3"
},
{
"code": "# import modulefrom art import * # return multiple art as strart__0=art(\"woman\",number=10) print(art__0)",
"e": 24707,
"s": 24600,
"text": null
},
{
"code": null,
"e": 24716,
"s": 24707,
"text": "Output: "
},
{
"code": null,
"e": 24743,
"s": 24716,
"text": "Random generation of arts:"
},
{
"code": null,
"e": 24751,
"s": 24743,
"text": "Python3"
},
{
"code": "from art import * print(art(\"random\"))",
"e": 24791,
"s": 24751,
"text": null
},
{
"code": null,
"e": 24799,
"s": 24791,
"text": "Output:"
},
{
"code": null,
"e": 24823,
"s": 24799,
"text": "Using aprint() function"
},
{
"code": null,
"e": 24907,
"s": 24823,
"text": "Here, you can directly print arts just like the print function you print something "
},
{
"code": null,
"e": 24915,
"s": 24907,
"text": "Python3"
},
{
"code": "from art import * print(\"Buttterfly by art : \",end=\" \") aprint(\"butterfly\")print()",
"e": 25003,
"s": 24915,
"text": null
},
{
"code": null,
"e": 25011,
"s": 25003,
"text": "Output:"
},
{
"code": null,
"e": 25072,
"s": 25011,
"text": "Now Let’s move towards the capability of python text to art "
},
{
"code": null,
"e": 25080,
"s": 25072,
"text": "Python3"
},
{
"code": "# import modulefrom art import * # Return ASCII text with block font# If font=None then there is no blockArt = text2art(\"GFG\", font='block', chr_ignore=True) print(Art)",
"e": 25251,
"s": 25080,
"text": null
},
{
"code": null,
"e": 25259,
"s": 25251,
"text": "Output:"
},
{
"code": null,
"e": 25342,
"s": 25259,
"text": "tprint() function is same as print() function it prints the text into ASCII format"
},
{
"code": null,
"e": 25350,
"s": 25342,
"text": "Python3"
},
{
"code": "# import modulefrom art import * # random large text to art representation # This art will be random every timetprint(\"GFG\",\"rnd-xlarge\")",
"e": 25489,
"s": 25350,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25489,
"text": "Output:"
},
{
"code": null,
"e": 25560,
"s": 25497,
"text": "We can save this to a txt file too by using tsave() function. "
},
{
"code": null,
"e": 25610,
"s": 25560,
"text": "Syntax: tsave(“STRING”, OUTPUT FILE NAME OR PATH)"
},
{
"code": null,
"e": 25618,
"s": 25610,
"text": "Python3"
},
{
"code": "# import modulefrom art import * Filename = tsave( \"GEEKSFORGEEKS\", filename=\"Output_in_txt_file_using_tsave().txt\")",
"e": 25739,
"s": 25618,
"text": null
},
{
"code": null,
"e": 25747,
"s": 25739,
"text": "Output:"
},
{
"code": null,
"e": 25762,
"s": 25747,
"text": "python-modules"
},
{
"code": null,
"e": 25769,
"s": 25762,
"text": "Python"
},
{
"code": null,
"e": 25867,
"s": 25769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25876,
"s": 25867,
"text": "Comments"
},
{
"code": null,
"e": 25889,
"s": 25876,
"text": "Old Comments"
},
{
"code": null,
"e": 25921,
"s": 25889,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25977,
"s": 25921,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26019,
"s": 25977,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26061,
"s": 26019,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26097,
"s": 26061,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26136,
"s": 26097,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26158,
"s": 26136,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26189,
"s": 26158,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26216,
"s": 26189,
"text": "Python Classes and Objects"
}
]
|
Types of Java comments. | Java supports single-line, multi-line comments, and documentation comments. Documentation comments are understood by Javadoc tool and can be used to create HTML based documentation.
/** is known as documentation comments. It is used by Javadoc tool while creating the documentation for the program code.
/* is used for multi-line comments.
// is used for single line comments
Live Demo
/**
* This is a documentation comment.
* This is my first Java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public class MyFirstJavaProgram {
public static void main(String[] args) {
/* This is an example of multi line comment. */
// This is a single line comment.
System.out.println("Hello World");
}
} | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "Java supports single-line, multi-line comments, and documentation comments. Documentation comments are understood by Javadoc tool and can be used to create HTML based documentation."
},
{
"code": null,
"e": 1366,
"s": 1244,
"text": "/** is known as documentation comments. It is used by Javadoc tool while creating the documentation for the program code."
},
{
"code": null,
"e": 1402,
"s": 1366,
"text": "/* is used for multi-line comments."
},
{
"code": null,
"e": 1438,
"s": 1402,
"text": "// is used for single line comments"
},
{
"code": null,
"e": 1448,
"s": 1438,
"text": "Live Demo"
},
{
"code": null,
"e": 1848,
"s": 1448,
"text": "/**\n * This is a documentation comment.\n * This is my first Java program.\n * This will print 'Hello World' as the output\n * This is an example of multi-line comments.\n*/\npublic class MyFirstJavaProgram {\n public static void main(String[] args) {\n /* This is an example of multi line comment. */\n \n // This is a single line comment.\n System.out.println(\"Hello World\");\n }\n}"
}
]
|
How to change the color of X-axis label using ggplot2 in R? | The default color of labels is black but we might want to change that color to something else so that we can get attention of the viewer to the labels if it is needed. To change the color of X-axis label using ggplot2, we can use theme function that has axis.title.x argument which can be used for changing the color of the label values.
Consider the below data frame −
Live Demo
x<−rnorm(20,5,0.25)
y<−rnorm(20,5,0.004)
df<−data.frame(x,y)
df
x y
1 5.030380 4.997751
2 5.240119 4.998680
3 4.544677 4.999195
4 4.858193 4.998952
5 5.071308 5.001092
6 5.512129 4.998037
7 5.236292 5.002558
8 5.081739 5.001903
9 4.940688 5.005155
10 4.437274 5.002876
11 5.472674 4.997229
12 4.813980 5.005284
13 4.859050 4.993907
14 5.353379 4.998850
15 5.537771 4.988465
16 5.302592 4.999421
17 5.486402 4.991891
18 5.121558 5.003857
19 4.908864 5.003393
20 5.137028 5.008340
Loading ggplot2 package and creating a scatterplot −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating the scatterplot with X-axis label in red color −
ggplot(df,aes(x,y))+geom_point()+theme(axis.title.x=element_text(colour="red")) | [
{
"code": null,
"e": 1400,
"s": 1062,
"text": "The default color of labels is black but we might want to change that color to something else so that we can get attention of the viewer to the labels if it is needed. To change the color of X-axis label using ggplot2, we can use theme function that has axis.title.x argument which can be used for changing the color of the label values."
},
{
"code": null,
"e": 1432,
"s": 1400,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1443,
"s": 1432,
"text": " Live Demo"
},
{
"code": null,
"e": 1507,
"s": 1443,
"text": "x<−rnorm(20,5,0.25)\ny<−rnorm(20,5,0.004)\ndf<−data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1934,
"s": 1507,
"text": " x y\n1 5.030380 4.997751\n2 5.240119 4.998680\n3 4.544677 4.999195\n4 4.858193 4.998952\n5 5.071308 5.001092\n6 5.512129 4.998037\n7 5.236292 5.002558\n8 5.081739 5.001903\n9 4.940688 5.005155\n10 4.437274 5.002876\n11 5.472674 4.997229\n12 4.813980 5.005284\n13 4.859050 4.993907\n14 5.353379 4.998850\n15 5.537771 4.988465\n16 5.302592 4.999421\n17 5.486402 4.991891\n18 5.121558 5.003857\n19 4.908864 5.003393\n20 5.137028 5.008340"
},
{
"code": null,
"e": 1987,
"s": 1934,
"text": "Loading ggplot2 package and creating a scatterplot −"
},
{
"code": null,
"e": 2037,
"s": 1987,
"text": "library(ggplot2)\nggplot(df,aes(x,y))+geom_point()"
},
{
"code": null,
"e": 2095,
"s": 2037,
"text": "Creating the scatterplot with X-axis label in red color −"
},
{
"code": null,
"e": 2175,
"s": 2095,
"text": "ggplot(df,aes(x,y))+geom_point()+theme(axis.title.x=element_text(colour=\"red\"))"
}
]
|
How to Concatenate two 2-dimensional NumPy Arrays? - GeeksforGeeks | 09 Aug, 2021
Sometimes it might be useful or required to concatenate or merge two or more of these NumPy arrays. In this article, we will discuss various methods of concatenating two 2D arrays. But first, we have to import the NumPy package to use it:
# import numpy package
import numpy as np
Then two 2D arrays have to be created to perform the operations, by using arrange() and reshape() functions. Using NumPy, we can perform concatenation of multiple 2D arrays in various ways and methods.
We can perform the concatenation operation using the concatenate() function. With this function, arrays are concatenated either row-wise or column-wise, given that they have equal rows or columns respectively. Column-wise concatenation can be done by equating axis to 1 as an argument in the function.
Example:
Python
# Program to concatenate two 2D arrays column-wise# import numpyimport numpy as np # Creating two 2D arraysarr1 = np.arange(1,10).reshape(3,3)arr2 = np.arange(10,19).reshape(3,3)arr1arr2 # Concatenating operation# axis = 1 implies that it is being done column-wisenp.concatenate((arr1,arr2),axis=1)
Output:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
array([[ 0, 1, 2, 10, 11, 12],
[ 3, 4, 5, 13, 14, 15],
[ 6, 7, 8, 16, 17, 18]])
In the same way, row-wise concatenation can be done by equating axis to 0.
Example:
Python
# Program to concatenate two 2D arrays row-wiseimport numpy as np # Creating two 2D arraysarr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operation# axis = 0 implies that it is being done row-wisenp.concatenate((arr1, arr2), axis=0)
Output:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
The stack() function can be used in the same way as the concatenate() function where the axis is equated to one. The arrays are stacked one over the other by using this.
Example:
Python
# Program to concatenate two 2D arrays row-wiseimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operation# axis = 1 implies that it is being# done row-wisenp.stack((arr1, arr2), axis=1)
Output:
array([[[ 1, 2, 3],
[10, 11, 12]],
[[ 4, 5, 6],
[13, 14, 15]],
[[ 7, 8, 9],
[16, 17, 18]]])
Or by equating axis to 2 the concatenation is done along with the height as shown below.
Example:
Python3
# Program to concatenate two 2D arrays along# the heightimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operation# axis = 2 implies that it is being done# along the heightnp.stack((arr1, arr2), axis=2)
Output:
array([[[ 1, 10],
[ 2, 11],
[ 3, 12]],
[[ 4, 13],
[ 5, 14],
[ 6, 15]],
[[ 7, 16],
[ 8, 17],
[ 9, 18]]])
The hstack() function stacks the array horizontally i.e. along a column.
Example:
Python
# Program to concatenate two 2D arrays# horizontallyimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operationarr = np.hstack((arr1, arr2))
Output:
array([[ 0, 1, 2, 10, 11, 12],
[ 3, 4, 5, 13, 14, 15],
[ 6, 7, 8, 16, 17, 18]])
The vstack() function stacks arrays vertically i.e. along a row.
Example:
Python
# Program to concatenate two 2D arrays# verticallyimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operationarr = np.vstack((arr1, arr2))
Output:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
In the dstack() function, d stands for depth and the concatenations occur along with the height as shown below:
Example:
Python
# Program to concatenate two 2D arrays# along the heightimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operationarr = np.dstack((arr1, arr2))
Output:
array([[[ 1, 10],
[ 2, 11],
[ 3, 12]],
[[ 4, 13],
[ 5, 14],
[ 6, 15]],
[[ 7, 16],
[ 8, 17],
[ 9, 18]]])
Method 6: Using column_stack() function
column_stack() function stacks the array horizontally i.e. along a column, it is usually used to concatenate id arrays into 2d arrays by joining them horizontally.
Python3
import numpy array1 = numpy.array([[1, 2, 3, 4, 5],[20,30,40,50,60]])array2 = numpy.array([[6, 7, 8, 9, 10],[9,8,7,6,5]]) # Stack arrays horizontally.array1 = numpy.column_stack([array1, array2])print(array1)
Output:
[[ 1 2 3 4 5 6 7 8 9 10]
[20 30 40 50 60 9 8 7 6 5]]
pulamolusaimohan
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 24140,
"s": 23901,
"text": "Sometimes it might be useful or required to concatenate or merge two or more of these NumPy arrays. In this article, we will discuss various methods of concatenating two 2D arrays. But first, we have to import the NumPy package to use it:"
},
{
"code": null,
"e": 24182,
"s": 24140,
"text": "# import numpy package\nimport numpy as np"
},
{
"code": null,
"e": 24384,
"s": 24182,
"text": "Then two 2D arrays have to be created to perform the operations, by using arrange() and reshape() functions. Using NumPy, we can perform concatenation of multiple 2D arrays in various ways and methods."
},
{
"code": null,
"e": 24686,
"s": 24384,
"text": "We can perform the concatenation operation using the concatenate() function. With this function, arrays are concatenated either row-wise or column-wise, given that they have equal rows or columns respectively. Column-wise concatenation can be done by equating axis to 1 as an argument in the function."
},
{
"code": null,
"e": 24695,
"s": 24686,
"text": "Example:"
},
{
"code": null,
"e": 24702,
"s": 24695,
"text": "Python"
},
{
"code": "# Program to concatenate two 2D arrays column-wise# import numpyimport numpy as np # Creating two 2D arraysarr1 = np.arange(1,10).reshape(3,3)arr2 = np.arange(10,19).reshape(3,3)arr1arr2 # Concatenating operation# axis = 1 implies that it is being done column-wisenp.concatenate((arr1,arr2),axis=1)",
"e": 25001,
"s": 24702,
"text": null
},
{
"code": null,
"e": 25009,
"s": 25001,
"text": "Output:"
},
{
"code": null,
"e": 25244,
"s": 25009,
"text": "array([[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]])\n \narray([[10, 11, 12],\n [13, 14, 15],\n [16, 17, 18]])\n \narray([[ 0, 1, 2, 10, 11, 12],\n [ 3, 4, 5, 13, 14, 15],\n [ 6, 7, 8, 16, 17, 18]])"
},
{
"code": null,
"e": 25319,
"s": 25244,
"text": "In the same way, row-wise concatenation can be done by equating axis to 0."
},
{
"code": null,
"e": 25328,
"s": 25319,
"text": "Example:"
},
{
"code": null,
"e": 25335,
"s": 25328,
"text": "Python"
},
{
"code": "# Program to concatenate two 2D arrays row-wiseimport numpy as np # Creating two 2D arraysarr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operation# axis = 0 implies that it is being done row-wisenp.concatenate((arr1, arr2), axis=0)",
"e": 25612,
"s": 25335,
"text": null
},
{
"code": null,
"e": 25620,
"s": 25612,
"text": "Output:"
},
{
"code": null,
"e": 25747,
"s": 25620,
"text": "array([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n [10, 11, 12],\n [13, 14, 15],\n [16, 17, 18]])"
},
{
"code": null,
"e": 25917,
"s": 25747,
"text": "The stack() function can be used in the same way as the concatenate() function where the axis is equated to one. The arrays are stacked one over the other by using this."
},
{
"code": null,
"e": 25926,
"s": 25917,
"text": "Example:"
},
{
"code": null,
"e": 25933,
"s": 25926,
"text": "Python"
},
{
"code": "# Program to concatenate two 2D arrays row-wiseimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operation# axis = 1 implies that it is being# done row-wisenp.stack((arr1, arr2), axis=1)",
"e": 26182,
"s": 25933,
"text": null
},
{
"code": null,
"e": 26191,
"s": 26182,
"text": "Output: "
},
{
"code": null,
"e": 26329,
"s": 26191,
"text": "array([[[ 1, 2, 3],\n [10, 11, 12]],\n\n [[ 4, 5, 6],\n [13, 14, 15]],\n\n [[ 7, 8, 9],\n [16, 17, 18]]])"
},
{
"code": null,
"e": 26418,
"s": 26329,
"text": "Or by equating axis to 2 the concatenation is done along with the height as shown below."
},
{
"code": null,
"e": 26427,
"s": 26418,
"text": "Example:"
},
{
"code": null,
"e": 26435,
"s": 26427,
"text": "Python3"
},
{
"code": "# Program to concatenate two 2D arrays along# the heightimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operation# axis = 2 implies that it is being done# along the heightnp.stack((arr1, arr2), axis=2)",
"e": 26700,
"s": 26435,
"text": null
},
{
"code": null,
"e": 26708,
"s": 26700,
"text": "Output:"
},
{
"code": null,
"e": 26876,
"s": 26708,
"text": "array([[[ 1, 10],\n [ 2, 11],\n [ 3, 12]],\n\n [[ 4, 13],\n [ 5, 14],\n [ 6, 15]],\n\n [[ 7, 16],\n [ 8, 17],\n [ 9, 18]]])"
},
{
"code": null,
"e": 26949,
"s": 26876,
"text": "The hstack() function stacks the array horizontally i.e. along a column."
},
{
"code": null,
"e": 26958,
"s": 26949,
"text": "Example:"
},
{
"code": null,
"e": 26965,
"s": 26958,
"text": "Python"
},
{
"code": "# Program to concatenate two 2D arrays# horizontallyimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operationarr = np.hstack((arr1, arr2))",
"e": 27168,
"s": 26965,
"text": null
},
{
"code": null,
"e": 27176,
"s": 27168,
"text": "Output:"
},
{
"code": null,
"e": 27276,
"s": 27176,
"text": "array([[ 0, 1, 2, 10, 11, 12],\n [ 3, 4, 5, 13, 14, 15],\n [ 6, 7, 8, 16, 17, 18]])"
},
{
"code": null,
"e": 27341,
"s": 27276,
"text": "The vstack() function stacks arrays vertically i.e. along a row."
},
{
"code": null,
"e": 27350,
"s": 27341,
"text": "Example:"
},
{
"code": null,
"e": 27357,
"s": 27350,
"text": "Python"
},
{
"code": "# Program to concatenate two 2D arrays# verticallyimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operationarr = np.vstack((arr1, arr2))",
"e": 27557,
"s": 27357,
"text": null
},
{
"code": null,
"e": 27565,
"s": 27557,
"text": "Output:"
},
{
"code": null,
"e": 27692,
"s": 27565,
"text": "array([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n [10, 11, 12],\n [13, 14, 15],\n [16, 17, 18]])"
},
{
"code": null,
"e": 27804,
"s": 27692,
"text": "In the dstack() function, d stands for depth and the concatenations occur along with the height as shown below:"
},
{
"code": null,
"e": 27813,
"s": 27804,
"text": "Example:"
},
{
"code": null,
"e": 27820,
"s": 27813,
"text": "Python"
},
{
"code": "# Program to concatenate two 2D arrays# along the heightimport numpy as np arr1 = np.arange(1, 10).reshape(3, 3)arr2 = np.arange(10, 19).reshape(3, 3) # Concatenating operationarr = np.dstack((arr1, arr2))",
"e": 28026,
"s": 27820,
"text": null
},
{
"code": null,
"e": 28034,
"s": 28026,
"text": "Output:"
},
{
"code": null,
"e": 28202,
"s": 28034,
"text": "array([[[ 1, 10],\n [ 2, 11],\n [ 3, 12]],\n\n [[ 4, 13],\n [ 5, 14],\n [ 6, 15]],\n\n [[ 7, 16],\n [ 8, 17],\n [ 9, 18]]])"
},
{
"code": null,
"e": 28242,
"s": 28202,
"text": "Method 6: Using column_stack() function"
},
{
"code": null,
"e": 28407,
"s": 28242,
"text": "column_stack() function stacks the array horizontally i.e. along a column, it is usually used to concatenate id arrays into 2d arrays by joining them horizontally."
},
{
"code": null,
"e": 28415,
"s": 28407,
"text": "Python3"
},
{
"code": "import numpy array1 = numpy.array([[1, 2, 3, 4, 5],[20,30,40,50,60]])array2 = numpy.array([[6, 7, 8, 9, 10],[9,8,7,6,5]]) # Stack arrays horizontally.array1 = numpy.column_stack([array1, array2])print(array1)",
"e": 28625,
"s": 28415,
"text": null
},
{
"code": null,
"e": 28633,
"s": 28625,
"text": "Output:"
},
{
"code": null,
"e": 28701,
"s": 28633,
"text": "[[ 1 2 3 4 5 6 7 8 9 10]\n\n [20 30 40 50 60 9 8 7 6 5]]"
},
{
"code": null,
"e": 28718,
"s": 28701,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 28749,
"s": 28718,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 28762,
"s": 28749,
"text": "Python-numpy"
},
{
"code": null,
"e": 28769,
"s": 28762,
"text": "Python"
},
{
"code": null,
"e": 28867,
"s": 28769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28876,
"s": 28867,
"text": "Comments"
},
{
"code": null,
"e": 28889,
"s": 28876,
"text": "Old Comments"
},
{
"code": null,
"e": 28921,
"s": 28889,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28977,
"s": 28921,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29019,
"s": 28977,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29061,
"s": 29019,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29097,
"s": 29061,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29136,
"s": 29097,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29158,
"s": 29136,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29189,
"s": 29158,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29216,
"s": 29189,
"text": "Python Classes and Objects"
}
]
|
Multistage Graph (Shortest Path) - GeeksforGeeks | CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Practice for cracking any coding interview
Competitive Programming - A Complete Guide
Arrow operator -> in C/C++ with Examples
Top 10 Algorithms and Data Structures for Competitive Programming
Fast I/O for Competitive Programming
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
How to begin with Competitive Programming?
Algorithm Library | C++ Magicians STL Algorithm
7 Best Coding Challenge Websites in 2020
Formatted output in Java
What is Competitive Programming and How to Prepare for It?
How to overcome Time Limit Exceed(TLE)?
Understanding The Coin Change Problem With Dynamic Programming
Fast I/O in Java in Competitive Programming
Bitwise Hacks for Competitive Programming
Use of FLAG in programming
Python Input Methods for Competitive Programming
Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
Container with Most Water
How to prepare for ACM - ICPC?
C qsort() vs C++ sort()
Searching in a map using std::map functions in C++
Bit Tricks for Competitive Programming
Setting up Sublime Text for C++ Competitive Programming Environment
Ordered Set and GNU C++ PBDS
How can one become good at Data structures and Algorithms easily?
Reduce the string by removing K consecutive identical characters
Runtime Errors
Practice for cracking any coding interview
Competitive Programming - A Complete Guide
Arrow operator -> in C/C++ with Examples
Top 10 Algorithms and Data Structures for Competitive Programming
Fast I/O for Competitive Programming
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
How to begin with Competitive Programming?
Algorithm Library | C++ Magicians STL Algorithm
7 Best Coding Challenge Websites in 2020
Formatted output in Java
What is Competitive Programming and How to Prepare for It?
How to overcome Time Limit Exceed(TLE)?
Understanding The Coin Change Problem With Dynamic Programming
Fast I/O in Java in Competitive Programming
Bitwise Hacks for Competitive Programming
Use of FLAG in programming
Python Input Methods for Competitive Programming
Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
Container with Most Water
How to prepare for ACM - ICPC?
C qsort() vs C++ sort()
Searching in a map using std::map functions in C++
Bit Tricks for Competitive Programming
Setting up Sublime Text for C++ Competitive Programming Environment
Ordered Set and GNU C++ PBDS
How can one become good at Data structures and Algorithms easily?
Reduce the string by removing K consecutive identical characters
Runtime Errors
Difficulty Level :
Medium
A Multistage graph is a directed graph in which the nodes can be divided into a set of stages such that all edges are from a stage to next stage only (In other words there is no edge between vertices of same stage and from a vertex of current stage to previous stage).We are given a multistage graph, a source and a destination, we need to find shortest path from source to destination. By convention, we consider source at stage 1 and destination as last stage.Following is an example graph we will consider in this article :-
Now there are various strategies we can apply :-
The Brute force method of finding all possible paths between Source and Destination and then finding the minimum. That’s the WORST possible strategy.
Dijkstra’s Algorithm of Single Source shortest paths. This method will find shortest paths from source to all other nodes which is not required in this case. So it will take a lot of time and it doesn’t even use the SPECIAL feature that this MULTI-STAGE graph has.
Simple Greedy Method – At each node, choose the shortest outgoing path. If we apply this approach to the example graph give above we get the solution as 1 + 4 + 18 = 23. But a quick look at the graph will show much shorter paths available than 23. So the greedy method fails !
The best option is Dynamic Programming. So we need to find Optimal Sub-structure, Recursive Equations and Overlapping Sub-problems.
Optimal Substructure and Recursive Equation :- We define the notation :- M(x, y) as the minimum cost to T(target node) from Stage x, Node y.
Shortest distance from stage 1, node 0 to
destination, i.e., 7 is M(1, 0).
// From 0, we can go to 1 or 2 or 3 to
// reach 7.
M(1, 0) = min(1 + M(2, 1),
2 + M(2, 2),
5 + M(2, 3))
This means that our problem of 0 —> 7 is now sub-divided into 3 sub-problems :-
So if we have total 'n' stages and target
as T, then the stopping condition will be :-
M(n-1, i) = i ---> T + M(n, T) = i ---> T
Recursion Tree and Overlapping Sub-Problems:- So, the hierarchy of M(x, y) evaluations will look something like this :-
In M(i, j), i is stage number and
j is node number
M(1, 0)
/ | \
/ | \
M(2, 1) M(2, 2) M(2, 3)
/ \ / \ / \
M(3, 4) M(3, 5) M(3, 4) M(3, 5) M(3, 6) M(3, 6)
. . . . . .
. . . . . .
. . . . . .
So, here we have drawn a very small part of the Recursion Tree and we can already see Overlapping Sub-Problems. We can largely reduce the number of M(x, y) evaluations using Dynamic Programming.Implementation details: The below implementation assumes that nodes are numbered from 0 to N-1 from first stage (source) to last stage (destination). We also assume that the input graph is multistage.
C++
Java
Python3
C#
Javascript
// CPP program to find shortest distance// in a multistage graph.#include<bits/stdc++.h>using namespace std; #define N 8#define INF INT_MAX // Returns shortest distance from 0 to// N-1.int shortestDist(int graph[N][N]) { // dist[i] is going to store shortest // distance from node i to node N-1. int dist[N]; dist[N-1] = 0; // Calculating shortest path for // rest of the nodes for (int i = N-2 ; i >= 0 ; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (int j = i ; j < N ; j++) { // Reject if no edge exists if (graph[i][j] == INF) continue; // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = min(dist[i], graph[i][j] + dist[j]); } } return dist[0];} // Driver codeint main(){ // Graph stored in the form of an // adjacency Matrix int graph[N][N] = {{INF, 1, 2, 5, INF, INF, INF, INF}, {INF, INF, INF, INF, 4, 11, INF, INF}, {INF, INF, INF, INF, 9, 5, 16, INF}, {INF, INF, INF, INF, INF, INF, 2, INF}, {INF, INF, INF, INF, INF, INF, INF, 18}, {INF, INF, INF, INF, INF, INF, INF, 13}, {INF, INF, INF, INF, INF, INF, INF, 2}, {INF, INF, INF, INF, INF, INF, INF, INF}}; cout << shortestDist(graph); return 0;}
// Java program to find shortest distance// in a multistage graph.class GFG{ static int N = 8; static int INF = Integer.MAX_VALUE; // Returns shortest distance from 0 to // N-1. public static int shortestDist(int[][] graph) { // dist[i] is going to store shortest // distance from node i to node N-1. int[] dist = new int[N]; dist[N - 1] = 0; // Calculating shortest path for // rest of the nodes for (int i = N - 2; i >= 0; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (int j = i; j < N; j++) { // Reject if no edge exists if (graph[i][j] == INF) { continue; } // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = Math.min(dist[i], graph[i][j] + dist[j]); } } return dist[0]; } // Driver code public static void main(String[] args) { // Graph stored in the form of an // adjacency Matrix int[][] graph = new int[][]{{INF, 1, 2, 5, INF, INF, INF, INF}, {INF, INF, INF, INF, 4, 11, INF, INF}, {INF, INF, INF, INF, 9, 5, 16, INF}, {INF, INF, INF, INF, INF, INF, 2, INF}, {INF, INF, INF, INF, INF, INF, INF, 18}, {INF, INF, INF, INF, INF, INF, INF, 13}, {INF, INF, INF, INF, INF, INF, INF, 2}}; System.out.println(shortestDist(graph)); }} // This code has been contributed by 29AjayKumar
# Python3 program to find shortest# distance in a multistage graph. # Returns shortest distance from# 0 to N-1.def shortestDist(graph): global INF # dist[i] is going to store shortest # distance from node i to node N-1. dist = [0] * N dist[N - 1] = 0 # Calculating shortest path # for rest of the nodes for i in range(N - 2, -1, -1): # Initialize distance from # i to destination (N-1) dist[i] = INF # Check all nodes of next stages # to find shortest distance from # i to N-1. for j in range(N): # Reject if no edge exists if graph[i][j] == INF: continue # We apply recursive equation to # distance to target through j. # and compare with minimum # distance so far. dist[i] = min(dist[i], graph[i][j] + dist[j]) return dist[0] # Driver codeN = 8INF = 999999999999 # Graph stored in the form of an# adjacency Matrixgraph = [[INF, 1, 2, 5, INF, INF, INF, INF], [INF, INF, INF, INF, 4, 11, INF, INF], [INF, INF, INF, INF, 9, 5, 16, INF], [INF, INF, INF, INF, INF, INF, 2, INF], [INF, INF, INF, INF, INF, INF, INF, 18], [INF, INF, INF, INF, INF, INF, INF, 13], [INF, INF, INF, INF, INF, INF, INF, 2]] print(shortestDist(graph)) # This code is contributed by PranchalK
// C# program to find shortest distance// in a multistage graph.using System; class GFG{ static int N = 8; static int INF = int.MaxValue; // Returns shortest distance from 0 to // N-1. public static int shortestDist(int[,] graph) { // dist[i] is going to store shortest // distance from node i to node N-1. int[] dist = new int[N]; dist[N-1] = 0; // Calculating shortest path for // rest of the nodes for (int i = N-2 ; i >= 0 ; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (int j = i ; j < N ; j++) { // Reject if no edge exists if (graph[i,j] == INF) continue; // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = Math.Min(dist[i], graph[i,j] + dist[j]); } } return dist[0]; } // Driver code static void Main() { // Graph stored in the form of an // adjacency Matrix int[,] graph = new int[,] {{INF, 1, 2, 5, INF, INF, INF, INF}, {INF, INF, INF, INF, 4, 11, INF, INF}, {INF, INF, INF, INF, 9, 5, 16, INF}, {INF, INF, INF, INF, INF, INF, 2, INF}, {INF, INF, INF, INF, INF, INF, INF, 18}, {INF, INF, INF, INF, INF, INF, INF, 13}, {INF, INF, INF, INF, INF, INF, INF, 2}}; Console.Write(shortestDist(graph)); }} // This code is contributed by DrRoot_
<script> // JavaScript program to find shortest distance// in a multistage graph. let N = 8;let INF = Number.MAX_VALUE; // Returns shortest distance from 0 to // N-1.function shortestDist(graph){ // dist[i] is going to store shortest // distance from node i to node N-1. let dist = new Array(N); dist[N - 1] = 0; // Calculating shortest path for // rest of the nodes for (let i = N - 2; i >= 0; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (let j = i; j < N; j++) { // Reject if no edge exists if (graph[i][j] == INF) { continue; } // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = Math.min(dist[i], graph[i][j] + dist[j]); } } return dist[0];} let graph = [[INF, 1, 2, 5, INF, INF, INF, INF], [INF, INF, INF, INF, 4, 11, INF, INF], [INF, INF, INF, INF, 9, 5, 16, INF], [INF, INF, INF, INF, INF, INF, 2, INF], [INF, INF, INF, INF, INF, INF, INF, 18], [INF, INF, INF, INF, INF, INF, INF, 13], [INF, INF, INF, INF, INF, INF, INF, 2]];document.write(shortestDist(graph)); // This code is contributed by rag2127 </script>
9
Time Complexity : O(n2)
DrRoot_
PranchalKatiyar
29AjayKumar
prakhargupta540
raja11sep
rag2127
Competitive Programming
Dynamic Programming
Graph
Dynamic Programming
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
5 Best Books for Competitive Programming
5 Best Languages for Competitive Programming
Most important type of Algorithms
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23 | [
{
"code": null,
"e": 419,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses"
},
{
"code": null,
"e": 600,
"s": 419,
"text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 685,
"s": 600,
"text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More"
},
{
"code": null,
"e": 702,
"s": 685,
"text": "DSA Live Classes"
},
{
"code": null,
"e": 716,
"s": 702,
"text": "System Design"
},
{
"code": null,
"e": 741,
"s": 716,
"text": "Java Backend Development"
},
{
"code": null,
"e": 757,
"s": 741,
"text": "Full Stack LIVE"
},
{
"code": null,
"e": 770,
"s": 757,
"text": "Explore More"
},
{
"code": null,
"e": 842,
"s": 770,
"text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 858,
"s": 842,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 869,
"s": 858,
"text": "SDE Theory"
},
{
"code": null,
"e": 894,
"s": 869,
"text": "Must-Do Coding Questions"
},
{
"code": null,
"e": 907,
"s": 894,
"text": "Explore More"
},
{
"code": null,
"e": 1054,
"s": 907,
"text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1130,
"s": 1054,
"text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More"
},
{
"code": null,
"e": 1154,
"s": 1130,
"text": "Competitive Programming"
},
{
"code": null,
"e": 1179,
"s": 1154,
"text": "Data Structures with C++"
},
{
"code": null,
"e": 1192,
"s": 1179,
"text": "Data Science"
},
{
"code": null,
"e": 1205,
"s": 1192,
"text": "Explore More"
},
{
"code": null,
"e": 1265,
"s": 1205,
"text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1281,
"s": 1265,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 1285,
"s": 1281,
"text": "CIP"
},
{
"code": null,
"e": 1305,
"s": 1285,
"text": "JAVA / Python / C++"
},
{
"code": null,
"e": 1318,
"s": 1305,
"text": "Explore More"
},
{
"code": null,
"e": 1393,
"s": 1318,
"text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more"
},
{
"code": null,
"e": 1406,
"s": 1393,
"text": "School Guide"
},
{
"code": null,
"e": 1425,
"s": 1406,
"text": "Python Programming"
},
{
"code": null,
"e": 1444,
"s": 1425,
"text": "Learn To Make Apps"
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "Explore more"
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "All Courses"
},
{
"code": null,
"e": 3985,
"s": 1469,
"text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 4566,
"s": 3985,
"text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms"
},
{
"code": null,
"e": 4899,
"s": 4566,
"text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question"
},
{
"code": null,
"e": 4919,
"s": 4899,
"text": "Asymptotic Analysis"
},
{
"code": null,
"e": 4949,
"s": 4919,
"text": "Worst, Average and Best Cases"
},
{
"code": null,
"e": 4970,
"s": 4949,
"text": "Asymptotic Notations"
},
{
"code": null,
"e": 5006,
"s": 4970,
"text": "Little o and little omega notations"
},
{
"code": null,
"e": 5035,
"s": 5006,
"text": "Lower and Upper Bound Theory"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "Analysis of Loops"
},
{
"code": null,
"e": 5073,
"s": 5053,
"text": "Solving Recurrences"
},
{
"code": null,
"e": 5092,
"s": 5073,
"text": "Amortized Analysis"
},
{
"code": null,
"e": 5128,
"s": 5092,
"text": "What does 'Space Complexity' mean ?"
},
{
"code": null,
"e": 5157,
"s": 5128,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 5194,
"s": 5157,
"text": "Polynomial Time Approximation Scheme"
},
{
"code": null,
"e": 5221,
"s": 5194,
"text": "A Time Complexity Question"
},
{
"code": null,
"e": 5242,
"s": 5221,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 5261,
"s": 5242,
"text": "Sorting Algorithms"
},
{
"code": null,
"e": 5278,
"s": 5261,
"text": "Graph Algorithms"
},
{
"code": null,
"e": 5296,
"s": 5278,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5317,
"s": 5296,
"text": "Geometric Algorithms"
},
{
"code": null,
"e": 5330,
"s": 5317,
"text": "Mathematical"
},
{
"code": null,
"e": 5349,
"s": 5330,
"text": "Bitwise Algorithms"
},
{
"code": null,
"e": 5371,
"s": 5349,
"text": "Randomized Algorithms"
},
{
"code": null,
"e": 5389,
"s": 5371,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 5409,
"s": 5389,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5428,
"s": 5409,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5441,
"s": 5428,
"text": "Backtracking"
},
{
"code": null,
"e": 5458,
"s": 5441,
"text": "Branch and Bound"
},
{
"code": null,
"e": 5473,
"s": 5458,
"text": "All Algorithms"
},
{
"code": null,
"e": 5616,
"s": 5473,
"text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures"
},
{
"code": null,
"e": 5623,
"s": 5616,
"text": "Arrays"
},
{
"code": null,
"e": 5635,
"s": 5623,
"text": "Linked List"
},
{
"code": null,
"e": 5641,
"s": 5635,
"text": "Stack"
},
{
"code": null,
"e": 5647,
"s": 5641,
"text": "Queue"
},
{
"code": null,
"e": 5659,
"s": 5647,
"text": "Binary Tree"
},
{
"code": null,
"e": 5678,
"s": 5659,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5683,
"s": 5678,
"text": "Heap"
},
{
"code": null,
"e": 5691,
"s": 5683,
"text": "Hashing"
},
{
"code": null,
"e": 5697,
"s": 5691,
"text": "Graph"
},
{
"code": null,
"e": 5721,
"s": 5697,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5728,
"s": 5721,
"text": "Matrix"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Strings"
},
{
"code": null,
"e": 5756,
"s": 5736,
"text": "All Data Structures"
},
{
"code": null,
"e": 5976,
"s": 5756,
"text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes"
},
{
"code": null,
"e": 5996,
"s": 5976,
"text": "Company Preparation"
},
{
"code": null,
"e": 6007,
"s": 5996,
"text": "Top Topics"
},
{
"code": null,
"e": 6034,
"s": 6007,
"text": "Practice Company Questions"
},
{
"code": null,
"e": 6056,
"s": 6034,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6079,
"s": 6056,
"text": "Experienced Interviews"
},
{
"code": null,
"e": 6101,
"s": 6079,
"text": "Internship Interviews"
},
{
"code": null,
"e": 6126,
"s": 6101,
"text": "Competititve Programming"
},
{
"code": null,
"e": 6142,
"s": 6126,
"text": "Design Patterns"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6189,
"s": 6165,
"text": "Multiple Choice Quizzes"
},
{
"code": null,
"e": 6270,
"s": 6189,
"text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin"
},
{
"code": null,
"e": 6272,
"s": 6270,
"text": "C"
},
{
"code": null,
"e": 6276,
"s": 6272,
"text": "C++"
},
{
"code": null,
"e": 6281,
"s": 6276,
"text": "Java"
},
{
"code": null,
"e": 6288,
"s": 6281,
"text": "Python"
},
{
"code": null,
"e": 6291,
"s": 6288,
"text": "C#"
},
{
"code": null,
"e": 6302,
"s": 6291,
"text": "JavaScript"
},
{
"code": null,
"e": 6309,
"s": 6302,
"text": "jQuery"
},
{
"code": null,
"e": 6313,
"s": 6309,
"text": "SQL"
},
{
"code": null,
"e": 6317,
"s": 6313,
"text": "PHP"
},
{
"code": null,
"e": 6323,
"s": 6317,
"text": "Scala"
},
{
"code": null,
"e": 6328,
"s": 6323,
"text": "Perl"
},
{
"code": null,
"e": 6340,
"s": 6328,
"text": "Go Language"
},
{
"code": null,
"e": 6345,
"s": 6340,
"text": "HTML"
},
{
"code": null,
"e": 6349,
"s": 6345,
"text": "CSS"
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": "Kotlin"
},
{
"code": null,
"e": 6402,
"s": 6356,
"text": "ML & Data ScienceMachine LearningData Science"
},
{
"code": null,
"e": 6419,
"s": 6402,
"text": "Machine Learning"
},
{
"code": null,
"e": 6432,
"s": 6419,
"text": "Data Science"
},
{
"code": null,
"e": 6599,
"s": 6432,
"text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering"
},
{
"code": null,
"e": 6611,
"s": 6599,
"text": "Mathematics"
},
{
"code": null,
"e": 6628,
"s": 6611,
"text": "Operating System"
},
{
"code": null,
"e": 6633,
"s": 6628,
"text": "DBMS"
},
{
"code": null,
"e": 6651,
"s": 6633,
"text": "Computer Networks"
},
{
"code": null,
"e": 6690,
"s": 6651,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 6712,
"s": 6690,
"text": "Theory of Computation"
},
{
"code": null,
"e": 6728,
"s": 6712,
"text": "Compiler Design"
},
{
"code": null,
"e": 6742,
"s": 6728,
"text": "Digital Logic"
},
{
"code": null,
"e": 6763,
"s": 6742,
"text": "Software Engineering"
},
{
"code": null,
"e": 6938,
"s": 6763,
"text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS"
},
{
"code": null,
"e": 6966,
"s": 6938,
"text": "GATE Computer Science Notes"
},
{
"code": null,
"e": 6984,
"s": 6966,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 7006,
"s": 6984,
"text": "GATE CS Solved Papers"
},
{
"code": null,
"e": 7048,
"s": 7006,
"text": "GATE CS Original Papers and Official Keys"
},
{
"code": null,
"e": 7064,
"s": 7048,
"text": "GATE 2021 Dates"
},
{
"code": null,
"e": 7086,
"s": 7064,
"text": "GATE CS 2021 Syllabus"
},
{
"code": null,
"e": 7115,
"s": 7086,
"text": "Important Topics for GATE CS"
},
{
"code": null,
"e": 7189,
"s": 7115,
"text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP"
},
{
"code": null,
"e": 7194,
"s": 7189,
"text": "HTML"
},
{
"code": null,
"e": 7198,
"s": 7194,
"text": "CSS"
},
{
"code": null,
"e": 7209,
"s": 7198,
"text": "JavaScript"
},
{
"code": null,
"e": 7219,
"s": 7209,
"text": "AngularJS"
},
{
"code": null,
"e": 7227,
"s": 7219,
"text": "ReactJS"
},
{
"code": null,
"e": 7234,
"s": 7227,
"text": "NodeJS"
},
{
"code": null,
"e": 7244,
"s": 7234,
"text": "Bootstrap"
},
{
"code": null,
"e": 7251,
"s": 7244,
"text": "jQuery"
},
{
"code": null,
"e": 7255,
"s": 7251,
"text": "PHP"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Software DesignsSoftware Design PatternsSystem Design Tutorial"
},
{
"code": null,
"e": 7343,
"s": 7318,
"text": "Software Design Patterns"
},
{
"code": null,
"e": 7366,
"s": 7343,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 7923,
"s": 7366,
"text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 7942,
"s": 7923,
"text": "School Programming"
},
{
"code": null,
"e": 8034,
"s": 7942,
"text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus"
},
{
"code": null,
"e": 8048,
"s": 8034,
"text": "Number System"
},
{
"code": null,
"e": 8056,
"s": 8048,
"text": "Algebra"
},
{
"code": null,
"e": 8069,
"s": 8056,
"text": "Trigonometry"
},
{
"code": null,
"e": 8080,
"s": 8069,
"text": "Statistics"
},
{
"code": null,
"e": 8092,
"s": 8080,
"text": "Probability"
},
{
"code": null,
"e": 8101,
"s": 8092,
"text": "Geometry"
},
{
"code": null,
"e": 8113,
"s": 8101,
"text": "Mensuration"
},
{
"code": null,
"e": 8122,
"s": 8113,
"text": "Calculus"
},
{
"code": null,
"e": 8215,
"s": 8122,
"text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes"
},
{
"code": null,
"e": 8229,
"s": 8215,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8243,
"s": 8229,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8258,
"s": 8243,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8273,
"s": 8258,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 8288,
"s": 8273,
"text": "Class 12 Notes"
},
{
"code": null,
"e": 8417,
"s": 8288,
"text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8440,
"s": 8417,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8463,
"s": 8440,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8487,
"s": 8463,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8511,
"s": 8487,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8535,
"s": 8511,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8668,
"s": 8535,
"text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8691,
"s": 8668,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8714,
"s": 8691,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8738,
"s": 8714,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8762,
"s": 8738,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8786,
"s": 8762,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8867,
"s": 8786,
"text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 8881,
"s": 8867,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8895,
"s": 8881,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8910,
"s": 8895,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8925,
"s": 8910,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 9131,
"s": 8925,
"text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9242,
"s": 9131,
"text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9284,
"s": 9242,
"text": "ISRO CS Original Papers and Official Keys"
},
{
"code": null,
"e": 9306,
"s": 9284,
"text": "ISRO CS Solved Papers"
},
{
"code": null,
"e": 9351,
"s": 9306,
"text": "ISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9434,
"s": 9351,
"text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9460,
"s": 9434,
"text": "UGC NET CS Notes Paper II"
},
{
"code": null,
"e": 9487,
"s": 9460,
"text": "UGC NET CS Notes Paper III"
},
{
"code": null,
"e": 9512,
"s": 9487,
"text": "UGC NET CS Solved Papers"
},
{
"code": null,
"e": 9717,
"s": 9512,
"text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 9743,
"s": 9717,
"text": "Campus Ambassador Program"
},
{
"code": null,
"e": 9769,
"s": 9743,
"text": "School Ambassador Program"
},
{
"code": null,
"e": 9777,
"s": 9769,
"text": "Project"
},
{
"code": null,
"e": 9795,
"s": 9777,
"text": "Geek of the Month"
},
{
"code": null,
"e": 9820,
"s": 9795,
"text": "Campus Geek of the Month"
},
{
"code": null,
"e": 9837,
"s": 9820,
"text": "Placement Course"
},
{
"code": null,
"e": 9862,
"s": 9837,
"text": "Competititve Programming"
},
{
"code": null,
"e": 9875,
"s": 9862,
"text": "Testimonials"
},
{
"code": null,
"e": 9891,
"s": 9875,
"text": "Student Chapter"
},
{
"code": null,
"e": 9907,
"s": 9891,
"text": "Geek on the Top"
},
{
"code": null,
"e": 9918,
"s": 9907,
"text": "Internship"
},
{
"code": null,
"e": 9926,
"s": 9918,
"text": "Careers"
},
{
"code": null,
"e": 9965,
"s": 9926,
"text": "JobsApply for JobsPost a JobJOB-A-THON"
},
{
"code": null,
"e": 9980,
"s": 9965,
"text": "Apply for Jobs"
},
{
"code": null,
"e": 9991,
"s": 9980,
"text": "Post a Job"
},
{
"code": null,
"e": 10002,
"s": 9991,
"text": "JOB-A-THON"
},
{
"code": null,
"e": 10267,
"s": 10002,
"text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10284,
"s": 10267,
"text": "All DSA Problems"
},
{
"code": null,
"e": 10303,
"s": 10284,
"text": "Problem of the Day"
},
{
"code": null,
"e": 10337,
"s": 10303,
"text": "Interview Series: Weekly Contests"
},
{
"code": null,
"e": 10371,
"s": 10337,
"text": "Bi-Wizard Coding: School Contests"
},
{
"code": null,
"e": 10391,
"s": 10371,
"text": "Contests and Events"
},
{
"code": null,
"e": 10410,
"s": 10391,
"text": "Practice SDE Sheet"
},
{
"code": null,
"e": 10530,
"s": 10410,
"text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10552,
"s": 10530,
"text": "Top 50 Array Problems"
},
{
"code": null,
"e": 10575,
"s": 10552,
"text": "Top 50 String Problems"
},
{
"code": null,
"e": 10596,
"s": 10575,
"text": "Top 50 Tree Problems"
},
{
"code": null,
"e": 10618,
"s": 10596,
"text": "Top 50 Graph Problems"
},
{
"code": null,
"e": 10637,
"s": 10618,
"text": "Top 50 DP Problems"
},
{
"code": null,
"e": 10908,
"s": 10641,
"text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri"
},
{
"code": null,
"e": 10921,
"s": 10908,
"text": "Geeks Digest"
},
{
"code": null,
"e": 10929,
"s": 10921,
"text": "Quizzes"
},
{
"code": null,
"e": 10942,
"s": 10929,
"text": "Geeks Campus"
},
{
"code": null,
"e": 10957,
"s": 10942,
"text": "Gblog Articles"
},
{
"code": null,
"e": 10961,
"s": 10957,
"text": "IDE"
},
{
"code": null,
"e": 10975,
"s": 10961,
"text": "Campus Mantri"
},
{
"code": null,
"e": 10983,
"s": 10975,
"text": "Sign In"
},
{
"code": null,
"e": 10991,
"s": 10983,
"text": "Sign In"
},
{
"code": null,
"e": 10996,
"s": 10991,
"text": "Home"
},
{
"code": null,
"e": 11009,
"s": 10996,
"text": "Saved Videos"
},
{
"code": null,
"e": 11017,
"s": 11009,
"text": "Courses"
},
{
"code": null,
"e": 15482,
"s": 11017,
"text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 15536,
"s": 15482,
"text": "\nFor Working Professionals\n \n\n"
},
{
"code": null,
"e": 15659,
"s": 15536,
"text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n"
},
{
"code": null,
"e": 15678,
"s": 15659,
"text": "\nDSA Live Classes\n"
},
{
"code": null,
"e": 15694,
"s": 15678,
"text": "\nSystem Design\n"
},
{
"code": null,
"e": 15721,
"s": 15694,
"text": "\nJava Backend Development\n"
},
{
"code": null,
"e": 15739,
"s": 15721,
"text": "\nFull Stack LIVE\n"
},
{
"code": null,
"e": 15754,
"s": 15739,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15862,
"s": 15754,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n"
},
{
"code": null,
"e": 15880,
"s": 15862,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 15893,
"s": 15880,
"text": "\nSDE Theory\n"
},
{
"code": null,
"e": 15920,
"s": 15893,
"text": "\nMust-Do Coding Questions\n"
},
{
"code": null,
"e": 15935,
"s": 15920,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15976,
"s": 15935,
"text": "\nFor Students\n \n\n"
},
{
"code": null,
"e": 16088,
"s": 15976,
"text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n"
},
{
"code": null,
"e": 16114,
"s": 16088,
"text": "\nCompetitive Programming\n"
},
{
"code": null,
"e": 16141,
"s": 16114,
"text": "\nData Structures with C++\n"
},
{
"code": null,
"e": 16156,
"s": 16141,
"text": "\nData Science\n"
},
{
"code": null,
"e": 16171,
"s": 16156,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16267,
"s": 16171,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n"
},
{
"code": null,
"e": 16285,
"s": 16267,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 16291,
"s": 16285,
"text": "\nCIP\n"
},
{
"code": null,
"e": 16313,
"s": 16291,
"text": "\nJAVA / Python / C++\n"
},
{
"code": null,
"e": 16328,
"s": 16313,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16439,
"s": 16328,
"text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n"
},
{
"code": null,
"e": 16454,
"s": 16439,
"text": "\nSchool Guide\n"
},
{
"code": null,
"e": 16475,
"s": 16454,
"text": "\nPython Programming\n"
},
{
"code": null,
"e": 16496,
"s": 16475,
"text": "\nLearn To Make Apps\n"
},
{
"code": null,
"e": 16511,
"s": 16496,
"text": "\nExplore more\n"
},
{
"code": null,
"e": 16816,
"s": 16511,
"text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n"
},
{
"code": null,
"e": 16839,
"s": 16816,
"text": "\nSearching Algorithms\n"
},
{
"code": null,
"e": 16860,
"s": 16839,
"text": "\nSorting Algorithms\n"
},
{
"code": null,
"e": 16879,
"s": 16860,
"text": "\nGraph Algorithms\n"
},
{
"code": null,
"e": 16899,
"s": 16879,
"text": "\nPattern Searching\n"
},
{
"code": null,
"e": 16922,
"s": 16899,
"text": "\nGeometric Algorithms\n"
},
{
"code": null,
"e": 16937,
"s": 16922,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 16958,
"s": 16937,
"text": "\nBitwise Algorithms\n"
},
{
"code": null,
"e": 16982,
"s": 16958,
"text": "\nRandomized Algorithms\n"
},
{
"code": null,
"e": 17002,
"s": 16982,
"text": "\nGreedy Algorithms\n"
},
{
"code": null,
"e": 17024,
"s": 17002,
"text": "\nDynamic Programming\n"
},
{
"code": null,
"e": 17045,
"s": 17024,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 17060,
"s": 17045,
"text": "\nBacktracking\n"
},
{
"code": null,
"e": 17079,
"s": 17060,
"text": "\nBranch and Bound\n"
},
{
"code": null,
"e": 17096,
"s": 17079,
"text": "\nAll Algorithms\n"
},
{
"code": null,
"e": 17481,
"s": 17096,
"text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n"
},
{
"code": null,
"e": 17503,
"s": 17481,
"text": "\nAsymptotic Analysis\n"
},
{
"code": null,
"e": 17535,
"s": 17503,
"text": "\nWorst, Average and Best Cases\n"
},
{
"code": null,
"e": 17558,
"s": 17535,
"text": "\nAsymptotic Notations\n"
},
{
"code": null,
"e": 17596,
"s": 17558,
"text": "\nLittle o and little omega notations\n"
},
{
"code": null,
"e": 17627,
"s": 17596,
"text": "\nLower and Upper Bound Theory\n"
},
{
"code": null,
"e": 17647,
"s": 17627,
"text": "\nAnalysis of Loops\n"
},
{
"code": null,
"e": 17669,
"s": 17647,
"text": "\nSolving Recurrences\n"
},
{
"code": null,
"e": 17690,
"s": 17669,
"text": "\nAmortized Analysis\n"
},
{
"code": null,
"e": 17728,
"s": 17690,
"text": "\nWhat does 'Space Complexity' mean ?\n"
},
{
"code": null,
"e": 17759,
"s": 17728,
"text": "\nPseudo-polynomial Algorithms\n"
},
{
"code": null,
"e": 17798,
"s": 17759,
"text": "\nPolynomial Time Approximation Scheme\n"
},
{
"code": null,
"e": 17827,
"s": 17798,
"text": "\nA Time Complexity Question\n"
},
{
"code": null,
"e": 18024,
"s": 17827,
"text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n"
},
{
"code": null,
"e": 18033,
"s": 18024,
"text": "\nArrays\n"
},
{
"code": null,
"e": 18047,
"s": 18033,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 18055,
"s": 18047,
"text": "\nStack\n"
},
{
"code": null,
"e": 18063,
"s": 18055,
"text": "\nQueue\n"
},
{
"code": null,
"e": 18077,
"s": 18063,
"text": "\nBinary Tree\n"
},
{
"code": null,
"e": 18098,
"s": 18077,
"text": "\nBinary Search Tree\n"
},
{
"code": null,
"e": 18105,
"s": 18098,
"text": "\nHeap\n"
},
{
"code": null,
"e": 18115,
"s": 18105,
"text": "\nHashing\n"
},
{
"code": null,
"e": 18123,
"s": 18115,
"text": "\nGraph\n"
},
{
"code": null,
"e": 18149,
"s": 18123,
"text": "\nAdvanced Data Structure\n"
},
{
"code": null,
"e": 18158,
"s": 18149,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 18168,
"s": 18158,
"text": "\nStrings\n"
},
{
"code": null,
"e": 18190,
"s": 18168,
"text": "\nAll Data Structures\n"
},
{
"code": null,
"e": 18458,
"s": 18190,
"text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18480,
"s": 18458,
"text": "\nCompany Preparation\n"
},
{
"code": null,
"e": 18493,
"s": 18480,
"text": "\nTop Topics\n"
},
{
"code": null,
"e": 18522,
"s": 18493,
"text": "\nPractice Company Questions\n"
},
{
"code": null,
"e": 18546,
"s": 18522,
"text": "\nInterview Experiences\n"
},
{
"code": null,
"e": 18571,
"s": 18546,
"text": "\nExperienced Interviews\n"
},
{
"code": null,
"e": 18595,
"s": 18571,
"text": "\nInternship Interviews\n"
},
{
"code": null,
"e": 18622,
"s": 18595,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 18640,
"s": 18622,
"text": "\nDesign Patterns\n"
},
{
"code": null,
"e": 18665,
"s": 18640,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 18691,
"s": 18665,
"text": "\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18830,
"s": 18691,
"text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n"
},
{
"code": null,
"e": 18834,
"s": 18830,
"text": "\nC\n"
},
{
"code": null,
"e": 18840,
"s": 18834,
"text": "\nC++\n"
},
{
"code": null,
"e": 18847,
"s": 18840,
"text": "\nJava\n"
},
{
"code": null,
"e": 18856,
"s": 18847,
"text": "\nPython\n"
},
{
"code": null,
"e": 18861,
"s": 18856,
"text": "\nC#\n"
},
{
"code": null,
"e": 18874,
"s": 18861,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 18883,
"s": 18874,
"text": "\njQuery\n"
},
{
"code": null,
"e": 18889,
"s": 18883,
"text": "\nSQL\n"
},
{
"code": null,
"e": 18895,
"s": 18889,
"text": "\nPHP\n"
},
{
"code": null,
"e": 18903,
"s": 18895,
"text": "\nScala\n"
},
{
"code": null,
"e": 18910,
"s": 18903,
"text": "\nPerl\n"
},
{
"code": null,
"e": 18924,
"s": 18910,
"text": "\nGo Language\n"
},
{
"code": null,
"e": 18931,
"s": 18924,
"text": "\nHTML\n"
},
{
"code": null,
"e": 18937,
"s": 18931,
"text": "\nCSS\n"
},
{
"code": null,
"e": 18946,
"s": 18937,
"text": "\nKotlin\n"
},
{
"code": null,
"e": 19024,
"s": 18946,
"text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n"
},
{
"code": null,
"e": 19043,
"s": 19024,
"text": "\nMachine Learning\n"
},
{
"code": null,
"e": 19058,
"s": 19043,
"text": "\nData Science\n"
},
{
"code": null,
"e": 19271,
"s": 19058,
"text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n"
},
{
"code": null,
"e": 19285,
"s": 19271,
"text": "\nMathematics\n"
},
{
"code": null,
"e": 19304,
"s": 19285,
"text": "\nOperating System\n"
},
{
"code": null,
"e": 19311,
"s": 19304,
"text": "\nDBMS\n"
},
{
"code": null,
"e": 19331,
"s": 19311,
"text": "\nComputer Networks\n"
},
{
"code": null,
"e": 19372,
"s": 19331,
"text": "\nComputer Organization and Architecture\n"
},
{
"code": null,
"e": 19396,
"s": 19372,
"text": "\nTheory of Computation\n"
},
{
"code": null,
"e": 19414,
"s": 19396,
"text": "\nCompiler Design\n"
},
{
"code": null,
"e": 19430,
"s": 19414,
"text": "\nDigital Logic\n"
},
{
"code": null,
"e": 19453,
"s": 19430,
"text": "\nSoftware Engineering\n"
},
{
"code": null,
"e": 19670,
"s": 19453,
"text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19700,
"s": 19670,
"text": "\nGATE Computer Science Notes\n"
},
{
"code": null,
"e": 19720,
"s": 19700,
"text": "\nLast Minute Notes\n"
},
{
"code": null,
"e": 19744,
"s": 19720,
"text": "\nGATE CS Solved Papers\n"
},
{
"code": null,
"e": 19788,
"s": 19744,
"text": "\nGATE CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 19806,
"s": 19788,
"text": "\nGATE 2021 Dates\n"
},
{
"code": null,
"e": 19830,
"s": 19806,
"text": "\nGATE CS 2021 Syllabus\n"
},
{
"code": null,
"e": 19861,
"s": 19830,
"text": "\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19981,
"s": 19861,
"text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n"
},
{
"code": null,
"e": 19988,
"s": 19981,
"text": "\nHTML\n"
},
{
"code": null,
"e": 19994,
"s": 19988,
"text": "\nCSS\n"
},
{
"code": null,
"e": 20007,
"s": 19994,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 20019,
"s": 20007,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 20029,
"s": 20019,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 20038,
"s": 20029,
"text": "\nNodeJS\n"
},
{
"code": null,
"e": 20050,
"s": 20038,
"text": "\nBootstrap\n"
},
{
"code": null,
"e": 20059,
"s": 20050,
"text": "\njQuery\n"
},
{
"code": null,
"e": 20065,
"s": 20059,
"text": "\nPHP\n"
},
{
"code": null,
"e": 20160,
"s": 20065,
"text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20187,
"s": 20160,
"text": "\nSoftware Design Patterns\n"
},
{
"code": null,
"e": 20212,
"s": 20187,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20276,
"s": 20212,
"text": "\nSchool Learning\n \n\n\nSchool Programming\n"
},
{
"code": null,
"e": 20297,
"s": 20276,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 20433,
"s": 20297,
"text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n"
},
{
"code": null,
"e": 20449,
"s": 20433,
"text": "\nNumber System\n"
},
{
"code": null,
"e": 20459,
"s": 20449,
"text": "\nAlgebra\n"
},
{
"code": null,
"e": 20474,
"s": 20459,
"text": "\nTrigonometry\n"
},
{
"code": null,
"e": 20487,
"s": 20474,
"text": "\nStatistics\n"
},
{
"code": null,
"e": 20501,
"s": 20487,
"text": "\nProbability\n"
},
{
"code": null,
"e": 20512,
"s": 20501,
"text": "\nGeometry\n"
},
{
"code": null,
"e": 20526,
"s": 20512,
"text": "\nMensuration\n"
},
{
"code": null,
"e": 20537,
"s": 20526,
"text": "\nCalculus\n"
},
{
"code": null,
"e": 20668,
"s": 20537,
"text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n"
},
{
"code": null,
"e": 20684,
"s": 20668,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 20700,
"s": 20684,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 20717,
"s": 20700,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 20734,
"s": 20717,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 20751,
"s": 20734,
"text": "\nClass 12 Notes\n"
},
{
"code": null,
"e": 20918,
"s": 20751,
"text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20943,
"s": 20918,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 20968,
"s": 20943,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20994,
"s": 20968,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21020,
"s": 20994,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21046,
"s": 21020,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21217,
"s": 21046,
"text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21242,
"s": 21217,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 21267,
"s": 21242,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 21293,
"s": 21267,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21319,
"s": 21293,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21345,
"s": 21319,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21462,
"s": 21345,
"text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n"
},
{
"code": null,
"e": 21478,
"s": 21462,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 21494,
"s": 21478,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 21511,
"s": 21494,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 21528,
"s": 21511,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 21570,
"s": 21528,
"text": "\nCS Exams/PSUs\n \n\n"
},
{
"code": null,
"e": 21715,
"s": 21570,
"text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21759,
"s": 21715,
"text": "\nISRO CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 21783,
"s": 21759,
"text": "\nISRO CS Solved Papers\n"
},
{
"code": null,
"e": 21830,
"s": 21783,
"text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21947,
"s": 21830,
"text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 21975,
"s": 21947,
"text": "\nUGC NET CS Notes Paper II\n"
},
{
"code": null,
"e": 22004,
"s": 21975,
"text": "\nUGC NET CS Notes Paper III\n"
},
{
"code": null,
"e": 22031,
"s": 22004,
"text": "\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 22288,
"s": 22031,
"text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n"
},
{
"code": null,
"e": 22316,
"s": 22288,
"text": "\nCampus Ambassador Program\n"
},
{
"code": null,
"e": 22344,
"s": 22316,
"text": "\nSchool Ambassador Program\n"
},
{
"code": null,
"e": 22354,
"s": 22344,
"text": "\nProject\n"
},
{
"code": null,
"e": 22374,
"s": 22354,
"text": "\nGeek of the Month\n"
},
{
"code": null,
"e": 22401,
"s": 22374,
"text": "\nCampus Geek of the Month\n"
},
{
"code": null,
"e": 22420,
"s": 22401,
"text": "\nPlacement Course\n"
},
{
"code": null,
"e": 22447,
"s": 22420,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 22462,
"s": 22447,
"text": "\nTestimonials\n"
},
{
"code": null,
"e": 22480,
"s": 22462,
"text": "\nStudent Chapter\n"
},
{
"code": null,
"e": 22498,
"s": 22480,
"text": "\nGeek on the Top\n"
},
{
"code": null,
"e": 22511,
"s": 22498,
"text": "\nInternship\n"
},
{
"code": null,
"e": 22521,
"s": 22511,
"text": "\nCareers\n"
},
{
"code": null,
"e": 22679,
"s": 22521,
"text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22703,
"s": 22679,
"text": "\nTop 50 Array Problems\n"
},
{
"code": null,
"e": 22728,
"s": 22703,
"text": "\nTop 50 String Problems\n"
},
{
"code": null,
"e": 22751,
"s": 22728,
"text": "\nTop 50 Tree Problems\n"
},
{
"code": null,
"e": 22775,
"s": 22751,
"text": "\nTop 50 Graph Problems\n"
},
{
"code": null,
"e": 22796,
"s": 22775,
"text": "\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22834,
"s": 22796,
"text": "\nTutorials\n \n\n"
},
{
"code": null,
"e": 22907,
"s": 22834,
"text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 22924,
"s": 22907,
"text": "\nApply for Jobs\n"
},
{
"code": null,
"e": 22937,
"s": 22924,
"text": "\nPost a Job\n"
},
{
"code": null,
"e": 22950,
"s": 22937,
"text": "\nJOB-A-THON\n"
},
{
"code": null,
"e": 23136,
"s": 22950,
"text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23155,
"s": 23136,
"text": "\nAll DSA Problems\n"
},
{
"code": null,
"e": 23176,
"s": 23155,
"text": "\nProblem of the Day\n"
},
{
"code": null,
"e": 23212,
"s": 23176,
"text": "\nInterview Series: Weekly Contests\n"
},
{
"code": null,
"e": 23248,
"s": 23212,
"text": "\nBi-Wizard Coding: School Contests\n"
},
{
"code": null,
"e": 23270,
"s": 23248,
"text": "\nContests and Events\n"
},
{
"code": null,
"e": 23291,
"s": 23270,
"text": "\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23297,
"s": 23291,
"text": "GBlog"
},
{
"code": null,
"e": 23305,
"s": 23297,
"text": "Puzzles"
},
{
"code": null,
"e": 23318,
"s": 23305,
"text": "What's New ?"
},
{
"code": null,
"e": 23324,
"s": 23318,
"text": "Array"
},
{
"code": null,
"e": 23331,
"s": 23324,
"text": "Matrix"
},
{
"code": null,
"e": 23339,
"s": 23331,
"text": "Strings"
},
{
"code": null,
"e": 23347,
"s": 23339,
"text": "Hashing"
},
{
"code": null,
"e": 23359,
"s": 23347,
"text": "Linked List"
},
{
"code": null,
"e": 23365,
"s": 23359,
"text": "Stack"
},
{
"code": null,
"e": 23371,
"s": 23365,
"text": "Queue"
},
{
"code": null,
"e": 23383,
"s": 23371,
"text": "Binary Tree"
},
{
"code": null,
"e": 23402,
"s": 23383,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 23407,
"s": 23402,
"text": "Heap"
},
{
"code": null,
"e": 23413,
"s": 23407,
"text": "Graph"
},
{
"code": null,
"e": 23423,
"s": 23413,
"text": "Searching"
},
{
"code": null,
"e": 23431,
"s": 23423,
"text": "Sorting"
},
{
"code": null,
"e": 23448,
"s": 23431,
"text": "Divide & Conquer"
},
{
"code": null,
"e": 23461,
"s": 23448,
"text": "Mathematical"
},
{
"code": null,
"e": 23471,
"s": 23461,
"text": "Geometric"
},
{
"code": null,
"e": 23479,
"s": 23471,
"text": "Bitwise"
},
{
"code": null,
"e": 23486,
"s": 23479,
"text": "Greedy"
},
{
"code": null,
"e": 23499,
"s": 23486,
"text": "Backtracking"
},
{
"code": null,
"e": 23516,
"s": 23499,
"text": "Branch and Bound"
},
{
"code": null,
"e": 23536,
"s": 23516,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23554,
"s": 23536,
"text": "Pattern Searching"
},
{
"code": null,
"e": 23565,
"s": 23554,
"text": "Randomized"
},
{
"code": null,
"e": 23608,
"s": 23565,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 23651,
"s": 23608,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 23692,
"s": 23651,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 23758,
"s": 23692,
"text": "Top 10 Algorithms and Data Structures for Competitive Programming"
},
{
"code": null,
"e": 23795,
"s": 23758,
"text": "Fast I/O for Competitive Programming"
},
{
"code": null,
"e": 23822,
"s": 23795,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 23900,
"s": 23822,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 23938,
"s": 23900,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 23981,
"s": 23938,
"text": "How to begin with Competitive Programming?"
},
{
"code": null,
"e": 24029,
"s": 23981,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 24070,
"s": 24029,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 24095,
"s": 24070,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 24154,
"s": 24095,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 24194,
"s": 24154,
"text": "How to overcome Time Limit Exceed(TLE)?"
},
{
"code": null,
"e": 24257,
"s": 24194,
"text": "Understanding The Coin Change Problem With Dynamic Programming"
},
{
"code": null,
"e": 24301,
"s": 24257,
"text": "Fast I/O in Java in Competitive Programming"
},
{
"code": null,
"e": 24343,
"s": 24301,
"text": "Bitwise Hacks for Competitive Programming"
},
{
"code": null,
"e": 24370,
"s": 24343,
"text": "Use of FLAG in programming"
},
{
"code": null,
"e": 24419,
"s": 24370,
"text": "Python Input Methods for Competitive Programming"
},
{
"code": null,
"e": 24521,
"s": 24419,
"text": "Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)"
},
{
"code": null,
"e": 24547,
"s": 24521,
"text": "Container with Most Water"
},
{
"code": null,
"e": 24578,
"s": 24547,
"text": "How to prepare for ACM - ICPC?"
},
{
"code": null,
"e": 24602,
"s": 24578,
"text": "C qsort() vs C++ sort()"
},
{
"code": null,
"e": 24653,
"s": 24602,
"text": "Searching in a map using std::map functions in C++"
},
{
"code": null,
"e": 24692,
"s": 24653,
"text": "Bit Tricks for Competitive Programming"
},
{
"code": null,
"e": 24760,
"s": 24692,
"text": "Setting up Sublime Text for C++ Competitive Programming Environment"
},
{
"code": null,
"e": 24789,
"s": 24760,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 24855,
"s": 24789,
"text": "How can one become good at Data structures and Algorithms easily?"
},
{
"code": null,
"e": 24920,
"s": 24855,
"text": "Reduce the string by removing K consecutive identical characters"
},
{
"code": null,
"e": 24935,
"s": 24920,
"text": "Runtime Errors"
},
{
"code": null,
"e": 24978,
"s": 24935,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 25021,
"s": 24978,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 25062,
"s": 25021,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 25128,
"s": 25062,
"text": "Top 10 Algorithms and Data Structures for Competitive Programming"
},
{
"code": null,
"e": 25165,
"s": 25128,
"text": "Fast I/O for Competitive Programming"
},
{
"code": null,
"e": 25192,
"s": 25165,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 25270,
"s": 25192,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 25308,
"s": 25270,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 25351,
"s": 25308,
"text": "How to begin with Competitive Programming?"
},
{
"code": null,
"e": 25399,
"s": 25351,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 25440,
"s": 25399,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 25465,
"s": 25440,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 25524,
"s": 25465,
"text": "What is Competitive Programming and How to Prepare for It?"
},
{
"code": null,
"e": 25564,
"s": 25524,
"text": "How to overcome Time Limit Exceed(TLE)?"
},
{
"code": null,
"e": 25627,
"s": 25564,
"text": "Understanding The Coin Change Problem With Dynamic Programming"
},
{
"code": null,
"e": 25671,
"s": 25627,
"text": "Fast I/O in Java in Competitive Programming"
},
{
"code": null,
"e": 25713,
"s": 25671,
"text": "Bitwise Hacks for Competitive Programming"
},
{
"code": null,
"e": 25740,
"s": 25713,
"text": "Use of FLAG in programming"
},
{
"code": null,
"e": 25789,
"s": 25740,
"text": "Python Input Methods for Competitive Programming"
},
{
"code": null,
"e": 25891,
"s": 25789,
"text": "Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)"
},
{
"code": null,
"e": 25917,
"s": 25891,
"text": "Container with Most Water"
},
{
"code": null,
"e": 25948,
"s": 25917,
"text": "How to prepare for ACM - ICPC?"
},
{
"code": null,
"e": 25972,
"s": 25948,
"text": "C qsort() vs C++ sort()"
},
{
"code": null,
"e": 26023,
"s": 25972,
"text": "Searching in a map using std::map functions in C++"
},
{
"code": null,
"e": 26062,
"s": 26023,
"text": "Bit Tricks for Competitive Programming"
},
{
"code": null,
"e": 26130,
"s": 26062,
"text": "Setting up Sublime Text for C++ Competitive Programming Environment"
},
{
"code": null,
"e": 26159,
"s": 26130,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 26225,
"s": 26159,
"text": "How can one become good at Data structures and Algorithms easily?"
},
{
"code": null,
"e": 26290,
"s": 26225,
"text": "Reduce the string by removing K consecutive identical characters"
},
{
"code": null,
"e": 26305,
"s": 26290,
"text": "Runtime Errors"
},
{
"code": null,
"e": 26331,
"s": 26305,
"text": "Difficulty Level :\nMedium"
},
{
"code": null,
"e": 26861,
"s": 26331,
"text": "A Multistage graph is a directed graph in which the nodes can be divided into a set of stages such that all edges are from a stage to next stage only (In other words there is no edge between vertices of same stage and from a vertex of current stage to previous stage).We are given a multistage graph, a source and a destination, we need to find shortest path from source to destination. By convention, we consider source at stage 1 and destination as last stage.Following is an example graph we will consider in this article :- "
},
{
"code": null,
"e": 26912,
"s": 26863,
"text": "Now there are various strategies we can apply :-"
},
{
"code": null,
"e": 27062,
"s": 26912,
"text": "The Brute force method of finding all possible paths between Source and Destination and then finding the minimum. That’s the WORST possible strategy."
},
{
"code": null,
"e": 27327,
"s": 27062,
"text": "Dijkstra’s Algorithm of Single Source shortest paths. This method will find shortest paths from source to all other nodes which is not required in this case. So it will take a lot of time and it doesn’t even use the SPECIAL feature that this MULTI-STAGE graph has."
},
{
"code": null,
"e": 27604,
"s": 27327,
"text": "Simple Greedy Method – At each node, choose the shortest outgoing path. If we apply this approach to the example graph give above we get the solution as 1 + 4 + 18 = 23. But a quick look at the graph will show much shorter paths available than 23. So the greedy method fails !"
},
{
"code": null,
"e": 27736,
"s": 27604,
"text": "The best option is Dynamic Programming. So we need to find Optimal Sub-structure, Recursive Equations and Overlapping Sub-problems."
},
{
"code": null,
"e": 27879,
"s": 27736,
"text": "Optimal Substructure and Recursive Equation :- We define the notation :- M(x, y) as the minimum cost to T(target node) from Stage x, Node y. "
},
{
"code": null,
"e": 28102,
"s": 27879,
"text": "Shortest distance from stage 1, node 0 to \ndestination, i.e., 7 is M(1, 0).\n\n// From 0, we can go to 1 or 2 or 3 to\n// reach 7. \nM(1, 0) = min(1 + M(2, 1),\n 2 + M(2, 2),\n 5 + M(2, 3))"
},
{
"code": null,
"e": 28183,
"s": 28102,
"text": "This means that our problem of 0 —> 7 is now sub-divided into 3 sub-problems :- "
},
{
"code": null,
"e": 28313,
"s": 28183,
"text": "So if we have total 'n' stages and target\nas T, then the stopping condition will be :-\nM(n-1, i) = i ---> T + M(n, T) = i ---> T"
},
{
"code": null,
"e": 28434,
"s": 28313,
"text": "Recursion Tree and Overlapping Sub-Problems:- So, the hierarchy of M(x, y) evaluations will look something like this :- "
},
{
"code": null,
"e": 28924,
"s": 28434,
"text": "In M(i, j), i is stage number and\nj is node number\n\n M(1, 0)\n / | \\ \n / | \\ \n M(2, 1) M(2, 2) M(2, 3)\n / \\ / \\ / \\\nM(3, 4) M(3, 5) M(3, 4) M(3, 5) M(3, 6) M(3, 6)\n . . . . . .\n . . . . . .\n . . . . . ."
},
{
"code": null,
"e": 29321,
"s": 28924,
"text": "So, here we have drawn a very small part of the Recursion Tree and we can already see Overlapping Sub-Problems. We can largely reduce the number of M(x, y) evaluations using Dynamic Programming.Implementation details: The below implementation assumes that nodes are numbered from 0 to N-1 from first stage (source) to last stage (destination). We also assume that the input graph is multistage. "
},
{
"code": null,
"e": 29325,
"s": 29321,
"text": "C++"
},
{
"code": null,
"e": 29330,
"s": 29325,
"text": "Java"
},
{
"code": null,
"e": 29338,
"s": 29330,
"text": "Python3"
},
{
"code": null,
"e": 29341,
"s": 29338,
"text": "C#"
},
{
"code": null,
"e": 29352,
"s": 29341,
"text": "Javascript"
},
{
"code": "// CPP program to find shortest distance// in a multistage graph.#include<bits/stdc++.h>using namespace std; #define N 8#define INF INT_MAX // Returns shortest distance from 0 to// N-1.int shortestDist(int graph[N][N]) { // dist[i] is going to store shortest // distance from node i to node N-1. int dist[N]; dist[N-1] = 0; // Calculating shortest path for // rest of the nodes for (int i = N-2 ; i >= 0 ; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (int j = i ; j < N ; j++) { // Reject if no edge exists if (graph[i][j] == INF) continue; // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = min(dist[i], graph[i][j] + dist[j]); } } return dist[0];} // Driver codeint main(){ // Graph stored in the form of an // adjacency Matrix int graph[N][N] = {{INF, 1, 2, 5, INF, INF, INF, INF}, {INF, INF, INF, INF, 4, 11, INF, INF}, {INF, INF, INF, INF, 9, 5, 16, INF}, {INF, INF, INF, INF, INF, INF, 2, INF}, {INF, INF, INF, INF, INF, INF, INF, 18}, {INF, INF, INF, INF, INF, INF, INF, 13}, {INF, INF, INF, INF, INF, INF, INF, 2}, {INF, INF, INF, INF, INF, INF, INF, INF}}; cout << shortestDist(graph); return 0;}",
"e": 30941,
"s": 29352,
"text": null
},
{
"code": "// Java program to find shortest distance// in a multistage graph.class GFG{ static int N = 8; static int INF = Integer.MAX_VALUE; // Returns shortest distance from 0 to // N-1. public static int shortestDist(int[][] graph) { // dist[i] is going to store shortest // distance from node i to node N-1. int[] dist = new int[N]; dist[N - 1] = 0; // Calculating shortest path for // rest of the nodes for (int i = N - 2; i >= 0; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (int j = i; j < N; j++) { // Reject if no edge exists if (graph[i][j] == INF) { continue; } // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = Math.min(dist[i], graph[i][j] + dist[j]); } } return dist[0]; } // Driver code public static void main(String[] args) { // Graph stored in the form of an // adjacency Matrix int[][] graph = new int[][]{{INF, 1, 2, 5, INF, INF, INF, INF}, {INF, INF, INF, INF, 4, 11, INF, INF}, {INF, INF, INF, INF, 9, 5, 16, INF}, {INF, INF, INF, INF, INF, INF, 2, INF}, {INF, INF, INF, INF, INF, INF, INF, 18}, {INF, INF, INF, INF, INF, INF, INF, 13}, {INF, INF, INF, INF, INF, INF, INF, 2}}; System.out.println(shortestDist(graph)); }} // This code has been contributed by 29AjayKumar",
"e": 32774,
"s": 30941,
"text": null
},
{
"code": "# Python3 program to find shortest# distance in a multistage graph. # Returns shortest distance from# 0 to N-1.def shortestDist(graph): global INF # dist[i] is going to store shortest # distance from node i to node N-1. dist = [0] * N dist[N - 1] = 0 # Calculating shortest path # for rest of the nodes for i in range(N - 2, -1, -1): # Initialize distance from # i to destination (N-1) dist[i] = INF # Check all nodes of next stages # to find shortest distance from # i to N-1. for j in range(N): # Reject if no edge exists if graph[i][j] == INF: continue # We apply recursive equation to # distance to target through j. # and compare with minimum # distance so far. dist[i] = min(dist[i], graph[i][j] + dist[j]) return dist[0] # Driver codeN = 8INF = 999999999999 # Graph stored in the form of an# adjacency Matrixgraph = [[INF, 1, 2, 5, INF, INF, INF, INF], [INF, INF, INF, INF, 4, 11, INF, INF], [INF, INF, INF, INF, 9, 5, 16, INF], [INF, INF, INF, INF, INF, INF, 2, INF], [INF, INF, INF, INF, INF, INF, INF, 18], [INF, INF, INF, INF, INF, INF, INF, 13], [INF, INF, INF, INF, INF, INF, INF, 2]] print(shortestDist(graph)) # This code is contributed by PranchalK",
"e": 34201,
"s": 32774,
"text": null
},
{
"code": "// C# program to find shortest distance// in a multistage graph.using System; class GFG{ static int N = 8; static int INF = int.MaxValue; // Returns shortest distance from 0 to // N-1. public static int shortestDist(int[,] graph) { // dist[i] is going to store shortest // distance from node i to node N-1. int[] dist = new int[N]; dist[N-1] = 0; // Calculating shortest path for // rest of the nodes for (int i = N-2 ; i >= 0 ; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (int j = i ; j < N ; j++) { // Reject if no edge exists if (graph[i,j] == INF) continue; // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = Math.Min(dist[i], graph[i,j] + dist[j]); } } return dist[0]; } // Driver code static void Main() { // Graph stored in the form of an // adjacency Matrix int[,] graph = new int[,] {{INF, 1, 2, 5, INF, INF, INF, INF}, {INF, INF, INF, INF, 4, 11, INF, INF}, {INF, INF, INF, INF, 9, 5, 16, INF}, {INF, INF, INF, INF, INF, INF, 2, INF}, {INF, INF, INF, INF, INF, INF, INF, 18}, {INF, INF, INF, INF, INF, INF, INF, 13}, {INF, INF, INF, INF, INF, INF, INF, 2}}; Console.Write(shortestDist(graph)); }} // This code is contributed by DrRoot_",
"e": 36074,
"s": 34201,
"text": null
},
{
"code": "<script> // JavaScript program to find shortest distance// in a multistage graph. let N = 8;let INF = Number.MAX_VALUE; // Returns shortest distance from 0 to // N-1.function shortestDist(graph){ // dist[i] is going to store shortest // distance from node i to node N-1. let dist = new Array(N); dist[N - 1] = 0; // Calculating shortest path for // rest of the nodes for (let i = N - 2; i >= 0; i--) { // Initialize distance from i to // destination (N-1) dist[i] = INF; // Check all nodes of next stages // to find shortest distance from // i to N-1. for (let j = i; j < N; j++) { // Reject if no edge exists if (graph[i][j] == INF) { continue; } // We apply recursive equation to // distance to target through j. // and compare with minimum distance // so far. dist[i] = Math.min(dist[i], graph[i][j] + dist[j]); } } return dist[0];} let graph = [[INF, 1, 2, 5, INF, INF, INF, INF], [INF, INF, INF, INF, 4, 11, INF, INF], [INF, INF, INF, INF, 9, 5, 16, INF], [INF, INF, INF, INF, INF, INF, 2, INF], [INF, INF, INF, INF, INF, INF, INF, 18], [INF, INF, INF, INF, INF, INF, INF, 13], [INF, INF, INF, INF, INF, INF, INF, 2]];document.write(shortestDist(graph)); // This code is contributed by rag2127 </script>",
"e": 37689,
"s": 36074,
"text": null
},
{
"code": null,
"e": 37691,
"s": 37689,
"text": "9"
},
{
"code": null,
"e": 37718,
"s": 37693,
"text": "Time Complexity : O(n2) "
},
{
"code": null,
"e": 37726,
"s": 37718,
"text": "DrRoot_"
},
{
"code": null,
"e": 37742,
"s": 37726,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 37754,
"s": 37742,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37770,
"s": 37754,
"text": "prakhargupta540"
},
{
"code": null,
"e": 37780,
"s": 37770,
"text": "raja11sep"
},
{
"code": null,
"e": 37788,
"s": 37780,
"text": "rag2127"
},
{
"code": null,
"e": 37812,
"s": 37788,
"text": "Competitive Programming"
},
{
"code": null,
"e": 37832,
"s": 37812,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37838,
"s": 37832,
"text": "Graph"
},
{
"code": null,
"e": 37858,
"s": 37838,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37864,
"s": 37858,
"text": "Graph"
},
{
"code": null,
"e": 37962,
"s": 37864,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38008,
"s": 37962,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 38066,
"s": 38008,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 38107,
"s": 38066,
"text": "5 Best Books for Competitive Programming"
},
{
"code": null,
"e": 38152,
"s": 38107,
"text": "5 Best Languages for Competitive Programming"
},
{
"code": null,
"e": 38186,
"s": 38152,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 38215,
"s": 38186,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 38245,
"s": 38215,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38277,
"s": 38245,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 38311,
"s": 38277,
"text": "Longest Common Subsequence | DP-4"
}
]
|
How to get the number of dimensions of a matrix using NumPy in Python? - GeeksforGeeks | 03 Mar, 2021
In this article, we will discuss how to get the number of dimensions of a matrix using NumPy. It can be found using the ndim parameter of the ndarray() method.
Syntax: no_of_dimensions = numpy.ndarray.ndim
Approach:
Create an n-dimensional matrix using numpy package.
Use ndim attribute available with numpy array as numpy_array_name.ndim to get the number of dimensions.
Alternatively, we can use shape attribute to get the size of each dimension and then use len() function for the number of dimensions.
Use numpy.array() function to convert a list to numpy array and use one of the above two ways to get the number of dimensions.
Example 1:
Python3
import numpy as np x = np.arange(12).reshape((3, 4)) print(x.ndim)
Output:
2
Example 2:
Python3
import numpy as np # create numpy arrays# 1-d numpy array_1darr = np.arange(4) # 2-d numpy array_2darr = np.arange(15).reshape((5, 3)) # 3-d numpy array_3darr = np.arange(18).reshape((3, 2, 3)) # printing the type of value obtained using # attribute 'ndim'print("Type of value obtained: ", type(_1darr.ndim)) # printing the dimensions of each numpy arrayprint("Dimensions in _1darr are: ", _1darr.ndim)print("Dimensions in _2darr are: ", _2darr.ndim)print("Dimensions in _3darr are: ", _3darr.ndim) # numpy_arr.shape is the number of elements in# each dimension numpy_arr.shape returns a tuple# len() of the returned tuple is also gives number# of dimensionsprint("Dimensions in _3darr are: ", len(_3darr.shape)) # Use numpy.array() function to convert a list to# numpy array__1darr = np.array([5, 4, 1, 3, 2])__2darr = np.array([[5, 4],[1,2], [4,5]])print("Dimensions in __1darr are: ", __1darr.ndim)print("Dimensions in __2darr are: ", __2darr.ndim)
Output:
Type of value obtained: <class 'int'>
Dimensions in _1darr are: 1
Dimensions in _2darr are: 2
Dimensions in _3darr are: 3
Dimensions in _3darr are: 3
Dimensions in __1darr are: 1
Dimensions in __2darr are: 2
Picked
Python numpy-ndarray
Python-numpy
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 25697,
"s": 25537,
"text": "In this article, we will discuss how to get the number of dimensions of a matrix using NumPy. It can be found using the ndim parameter of the ndarray() method."
},
{
"code": null,
"e": 25743,
"s": 25697,
"text": "Syntax: no_of_dimensions = numpy.ndarray.ndim"
},
{
"code": null,
"e": 25753,
"s": 25743,
"text": "Approach:"
},
{
"code": null,
"e": 25805,
"s": 25753,
"text": "Create an n-dimensional matrix using numpy package."
},
{
"code": null,
"e": 25909,
"s": 25805,
"text": "Use ndim attribute available with numpy array as numpy_array_name.ndim to get the number of dimensions."
},
{
"code": null,
"e": 26043,
"s": 25909,
"text": "Alternatively, we can use shape attribute to get the size of each dimension and then use len() function for the number of dimensions."
},
{
"code": null,
"e": 26170,
"s": 26043,
"text": "Use numpy.array() function to convert a list to numpy array and use one of the above two ways to get the number of dimensions."
},
{
"code": null,
"e": 26182,
"s": 26170,
"text": "Example 1: "
},
{
"code": null,
"e": 26190,
"s": 26182,
"text": "Python3"
},
{
"code": "import numpy as np x = np.arange(12).reshape((3, 4)) print(x.ndim)",
"e": 26263,
"s": 26190,
"text": null
},
{
"code": null,
"e": 26271,
"s": 26263,
"text": "Output:"
},
{
"code": null,
"e": 26273,
"s": 26271,
"text": "2"
},
{
"code": null,
"e": 26284,
"s": 26273,
"text": "Example 2:"
},
{
"code": null,
"e": 26292,
"s": 26284,
"text": "Python3"
},
{
"code": "import numpy as np # create numpy arrays# 1-d numpy array_1darr = np.arange(4) # 2-d numpy array_2darr = np.arange(15).reshape((5, 3)) # 3-d numpy array_3darr = np.arange(18).reshape((3, 2, 3)) # printing the type of value obtained using # attribute 'ndim'print(\"Type of value obtained: \", type(_1darr.ndim)) # printing the dimensions of each numpy arrayprint(\"Dimensions in _1darr are: \", _1darr.ndim)print(\"Dimensions in _2darr are: \", _2darr.ndim)print(\"Dimensions in _3darr are: \", _3darr.ndim) # numpy_arr.shape is the number of elements in# each dimension numpy_arr.shape returns a tuple# len() of the returned tuple is also gives number# of dimensionsprint(\"Dimensions in _3darr are: \", len(_3darr.shape)) # Use numpy.array() function to convert a list to# numpy array__1darr = np.array([5, 4, 1, 3, 2])__2darr = np.array([[5, 4],[1,2], [4,5]])print(\"Dimensions in __1darr are: \", __1darr.ndim)print(\"Dimensions in __2darr are: \", __2darr.ndim)",
"e": 27266,
"s": 26292,
"text": null
},
{
"code": null,
"e": 27274,
"s": 27266,
"text": "Output:"
},
{
"code": null,
"e": 27489,
"s": 27274,
"text": "Type of value obtained: <class 'int'>\nDimensions in _1darr are: 1\nDimensions in _2darr are: 2\nDimensions in _3darr are: 3\nDimensions in _3darr are: 3\nDimensions in __1darr are: 1\nDimensions in __2darr are: 2"
},
{
"code": null,
"e": 27496,
"s": 27489,
"text": "Picked"
},
{
"code": null,
"e": 27517,
"s": 27496,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 27530,
"s": 27517,
"text": "Python-numpy"
},
{
"code": null,
"e": 27554,
"s": 27530,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27561,
"s": 27554,
"text": "Python"
},
{
"code": null,
"e": 27580,
"s": 27561,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27678,
"s": 27580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27710,
"s": 27678,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27752,
"s": 27710,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27794,
"s": 27752,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27821,
"s": 27794,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27877,
"s": 27821,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27899,
"s": 27877,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27938,
"s": 27899,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27969,
"s": 27938,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27998,
"s": 27969,
"text": "Create a directory in Python"
}
]
|
Microsoft Interview Experience for Internship - GeeksforGeeks | 14 Sep, 2020
Recently Microsoft visited our campus for internships. They had a coding round which was followed by 3 interviews ( 2 technical and 1 HR).
Online Test: It was conducted on mettl and we had 90 minutes to solve 3 questions. Questions were shuffled for everyone but were fairly easy.
Given a string we need to return a string in which each character should be increased by 3 units. Eg.adz -> dgc
The a becomes d, d becomes g and z becomes c. The only trick here was that we just had to complete the given function and they passed the string as a character pointer and so you need to see how to traverse a string represented as a character pointer.Convert an infix expression to postfix expression.Given a string in form of num1+num2=num3 in which one of them is X we need to find the value of X.Eg. Input : 5+X=7
Output: X= 2
Input : 7+2=X
Output: X=9
So this was basically an implementation based question and we just needed to find out of which one of them was X and accordingly find the answer.
Given a string we need to return a string in which each character should be increased by 3 units. Eg.adz -> dgc
The a becomes d, d becomes g and z becomes c. The only trick here was that we just had to complete the given function and they passed the string as a character pointer and so you need to see how to traverse a string represented as a character pointer.
Given a string we need to return a string in which each character should be increased by 3 units.
Eg.
adz -> dgc
The a becomes d, d becomes g and z becomes c. The only trick here was that we just had to complete the given function and they passed the string as a character pointer and so you need to see how to traverse a string represented as a character pointer.
Convert an infix expression to postfix expression.
Convert an infix expression to postfix expression.
Given a string in form of num1+num2=num3 in which one of them is X we need to find the value of X.Eg. Input : 5+X=7
Output: X= 2
Input : 7+2=X
Output: X=9
So this was basically an implementation based question and we just needed to find out of which one of them was X and accordingly find the answer.
Given a string in form of num1+num2=num3 in which one of them is X we need to find the value of X.
Eg.
Input : 5+X=7
Output: X= 2
Input : 7+2=X
Output: X=9
So this was basically an implementation based question and we just needed to find out of which one of them was X and accordingly find the answer.
48 students were selected for the interviews.
Round 1: I was asked 3 questions in this round. The questions were pretty easy.
Find the max and min element at any point in a stack. I was asked to code it. I tried to keep the interview interactive by telling him my approach as I wrote the code. I was asked to do a few dry runs, and he seemed satisfied with my approach.Reverse a string. We discussed the stack question for about 20 minutes and I told him I will use a stack to reverse it, and he didn’t ask me to optimize it.Mirror a given Binary Tree. I first told him my approach that we will use post-order traversal and then he asked me to code it.
Find the max and min element at any point in a stack. I was asked to code it. I tried to keep the interview interactive by telling him my approach as I wrote the code. I was asked to do a few dry runs, and he seemed satisfied with my approach.
Reverse a string. We discussed the stack question for about 20 minutes and I told him I will use a stack to reverse it, and he didn’t ask me to optimize it.
Mirror a given Binary Tree. I first told him my approach that we will use post-order traversal and then he asked me to code it.
I answered all the questions, so I was pretty confident that I will be selected for the next round.
Round 2: I was asked just 2 questions in this round.
Find the diameter of a tree (No. of nodes on the longest path in a tree). I had seen this question before and knew the solution so I just told him my approach and we did a few dry runs on sample inputs before proceeding to the next question.Given a number N we need to convert N to 1 by performing a minimum no of operations. The allowed operations are:Subtract 1 from a number.Divide the number by 2.Divide the number by 3.Eg.Input: 10
Output: 3
10->9->3->1
So at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach. C++C++#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}Output:3
Find the diameter of a tree (No. of nodes on the longest path in a tree). I had seen this question before and knew the solution so I just told him my approach and we did a few dry runs on sample inputs before proceeding to the next question.
Given a number N we need to convert N to 1 by performing a minimum no of operations. The allowed operations are:Subtract 1 from a number.Divide the number by 2.Divide the number by 3.Eg.Input: 10
Output: 3
10->9->3->1
So at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach. C++C++#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}Output:3
Subtract 1 from a number.
Divide the number by 2.
Divide the number by 3.Eg.Input: 10
Output: 3
10->9->3->1
So at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach. C++C++#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}Output:3
Eg.
Input: 10
Output: 3
10->9->3->1
So at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach.
C++
#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}
Output:
3
Round 3(HR): So it started with questions like tell me about yourself. I was prepared for this question and I kept the focus on my coding skills. For me, it was a mix of HR and technical round.
So, he asked me questions on Doubly Linked List. Given a pointer to a random node of a doubly linked list. Delete the node.
We discussed all the edge cases involved, and he just asked me to code it mentally and tell him each line. He seemed satisfied. Then he asked me why I wanted to work at Microsoft. It was followed by questions on OOPS and Hashing.
He asked me what was the implementation of hashing in real life and how hashing is implemented internally. I was able to answer this but I didn’t know the technical terms. Finally, he asked me if I had any questions for him. Never give a no as an answer to this question as it shows that you are not interested in knowing about the company.
Verdict – Selected
Microsoft
On-Campus
Internship
Interview Experiences
Microsoft
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
Zoho Interview Experience (Off-Campus ) 2022
Resume Writing For Internship
HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN | [
{
"code": null,
"e": 26605,
"s": 26577,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 26744,
"s": 26605,
"text": "Recently Microsoft visited our campus for internships. They had a coding round which was followed by 3 interviews ( 2 technical and 1 HR)."
},
{
"code": null,
"e": 26886,
"s": 26744,
"text": "Online Test: It was conducted on mettl and we had 90 minutes to solve 3 questions. Questions were shuffled for everyone but were fairly easy."
},
{
"code": null,
"e": 27601,
"s": 26886,
"text": "Given a string we need to return a string in which each character should be increased by 3 units. Eg.adz -> dgc\nThe a becomes d, d becomes g and z becomes c. The only trick here was that we just had to complete the given function and they passed the string as a character pointer and so you need to see how to traverse a string represented as a character pointer.Convert an infix expression to postfix expression.Given a string in form of num1+num2=num3 in which one of them is X we need to find the value of X.Eg. Input : 5+X=7 \nOutput: X= 2\nInput : 7+2=X\nOutput: X=9\nSo this was basically an implementation based question and we just needed to find out of which one of them was X and accordingly find the answer."
},
{
"code": null,
"e": 27965,
"s": 27601,
"text": "Given a string we need to return a string in which each character should be increased by 3 units. Eg.adz -> dgc\nThe a becomes d, d becomes g and z becomes c. The only trick here was that we just had to complete the given function and they passed the string as a character pointer and so you need to see how to traverse a string represented as a character pointer."
},
{
"code": null,
"e": 28064,
"s": 27965,
"text": "Given a string we need to return a string in which each character should be increased by 3 units. "
},
{
"code": null,
"e": 28068,
"s": 28064,
"text": "Eg."
},
{
"code": null,
"e": 28080,
"s": 28068,
"text": "adz -> dgc\n"
},
{
"code": null,
"e": 28332,
"s": 28080,
"text": "The a becomes d, d becomes g and z becomes c. The only trick here was that we just had to complete the given function and they passed the string as a character pointer and so you need to see how to traverse a string represented as a character pointer."
},
{
"code": null,
"e": 28383,
"s": 28332,
"text": "Convert an infix expression to postfix expression."
},
{
"code": null,
"e": 28434,
"s": 28383,
"text": "Convert an infix expression to postfix expression."
},
{
"code": null,
"e": 28736,
"s": 28434,
"text": "Given a string in form of num1+num2=num3 in which one of them is X we need to find the value of X.Eg. Input : 5+X=7 \nOutput: X= 2\nInput : 7+2=X\nOutput: X=9\nSo this was basically an implementation based question and we just needed to find out of which one of them was X and accordingly find the answer."
},
{
"code": null,
"e": 28835,
"s": 28736,
"text": "Given a string in form of num1+num2=num3 in which one of them is X we need to find the value of X."
},
{
"code": null,
"e": 28840,
"s": 28835,
"text": "Eg. "
},
{
"code": null,
"e": 28895,
"s": 28840,
"text": "Input : 5+X=7 \nOutput: X= 2\nInput : 7+2=X\nOutput: X=9\n"
},
{
"code": null,
"e": 29041,
"s": 28895,
"text": "So this was basically an implementation based question and we just needed to find out of which one of them was X and accordingly find the answer."
},
{
"code": null,
"e": 29087,
"s": 29041,
"text": "48 students were selected for the interviews."
},
{
"code": null,
"e": 29167,
"s": 29087,
"text": "Round 1: I was asked 3 questions in this round. The questions were pretty easy."
},
{
"code": null,
"e": 29694,
"s": 29167,
"text": "Find the max and min element at any point in a stack. I was asked to code it. I tried to keep the interview interactive by telling him my approach as I wrote the code. I was asked to do a few dry runs, and he seemed satisfied with my approach.Reverse a string. We discussed the stack question for about 20 minutes and I told him I will use a stack to reverse it, and he didn’t ask me to optimize it.Mirror a given Binary Tree. I first told him my approach that we will use post-order traversal and then he asked me to code it."
},
{
"code": null,
"e": 29938,
"s": 29694,
"text": "Find the max and min element at any point in a stack. I was asked to code it. I tried to keep the interview interactive by telling him my approach as I wrote the code. I was asked to do a few dry runs, and he seemed satisfied with my approach."
},
{
"code": null,
"e": 30095,
"s": 29938,
"text": "Reverse a string. We discussed the stack question for about 20 minutes and I told him I will use a stack to reverse it, and he didn’t ask me to optimize it."
},
{
"code": null,
"e": 30223,
"s": 30095,
"text": "Mirror a given Binary Tree. I first told him my approach that we will use post-order traversal and then he asked me to code it."
},
{
"code": null,
"e": 30323,
"s": 30223,
"text": "I answered all the questions, so I was pretty confident that I will be selected for the next round."
},
{
"code": null,
"e": 30377,
"s": 30323,
"text": "Round 2: I was asked just 2 questions in this round. "
},
{
"code": null,
"e": 31369,
"s": 30377,
"text": "Find the diameter of a tree (No. of nodes on the longest path in a tree). I had seen this question before and knew the solution so I just told him my approach and we did a few dry runs on sample inputs before proceeding to the next question.Given a number N we need to convert N to 1 by performing a minimum no of operations. The allowed operations are:Subtract 1 from a number.Divide the number by 2.Divide the number by 3.Eg.Input: 10 \nOutput: 3\n10->9->3->1\nSo at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach. C++C++#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}Output:3"
},
{
"code": null,
"e": 31611,
"s": 31369,
"text": "Find the diameter of a tree (No. of nodes on the longest path in a tree). I had seen this question before and knew the solution so I just told him my approach and we did a few dry runs on sample inputs before proceeding to the next question."
},
{
"code": null,
"e": 32362,
"s": 31611,
"text": "Given a number N we need to convert N to 1 by performing a minimum no of operations. The allowed operations are:Subtract 1 from a number.Divide the number by 2.Divide the number by 3.Eg.Input: 10 \nOutput: 3\n10->9->3->1\nSo at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach. C++C++#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}Output:3"
},
{
"code": null,
"e": 32388,
"s": 32362,
"text": "Subtract 1 from a number."
},
{
"code": null,
"e": 32412,
"s": 32388,
"text": "Divide the number by 2."
},
{
"code": null,
"e": 33003,
"s": 32412,
"text": "Divide the number by 3.Eg.Input: 10 \nOutput: 3\n10->9->3->1\nSo at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach. C++C++#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}Output:3"
},
{
"code": null,
"e": 33007,
"s": 33003,
"text": "Eg."
},
{
"code": null,
"e": 33041,
"s": 33007,
"text": "Input: 10 \nOutput: 3\n10->9->3->1\n"
},
{
"code": null,
"e": 33218,
"s": 33041,
"text": "So at first, I was trying to generalize the solution by taking different cases. The interviewer asked me to change my approach and I thought of a Dynamic Programming approach. "
},
{
"code": null,
"e": 33222,
"s": 33218,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ int n = 10; int dp[n + 1]; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = min(dp[i], 1 + dp[i / 2]); if(i % 3 == 0) dp[i] = min(dp[i], 1 + dp[i / 3]); } cout<<dp[n]<<endl;}",
"e": 33564,
"s": 33222,
"text": null
},
{
"code": null,
"e": 33572,
"s": 33564,
"text": "Output:"
},
{
"code": null,
"e": 33574,
"s": 33572,
"text": "3"
},
{
"code": null,
"e": 33769,
"s": 33574,
"text": "Round 3(HR): So it started with questions like tell me about yourself. I was prepared for this question and I kept the focus on my coding skills. For me, it was a mix of HR and technical round. "
},
{
"code": null,
"e": 33893,
"s": 33769,
"text": "So, he asked me questions on Doubly Linked List. Given a pointer to a random node of a doubly linked list. Delete the node."
},
{
"code": null,
"e": 34124,
"s": 33893,
"text": "We discussed all the edge cases involved, and he just asked me to code it mentally and tell him each line. He seemed satisfied. Then he asked me why I wanted to work at Microsoft. It was followed by questions on OOPS and Hashing."
},
{
"code": null,
"e": 34465,
"s": 34124,
"text": "He asked me what was the implementation of hashing in real life and how hashing is implemented internally. I was able to answer this but I didn’t know the technical terms. Finally, he asked me if I had any questions for him. Never give a no as an answer to this question as it shows that you are not interested in knowing about the company."
},
{
"code": null,
"e": 34484,
"s": 34465,
"text": "Verdict – Selected"
},
{
"code": null,
"e": 34494,
"s": 34484,
"text": "Microsoft"
},
{
"code": null,
"e": 34504,
"s": 34494,
"text": "On-Campus"
},
{
"code": null,
"e": 34515,
"s": 34504,
"text": "Internship"
},
{
"code": null,
"e": 34537,
"s": 34515,
"text": "Interview Experiences"
},
{
"code": null,
"e": 34547,
"s": 34537,
"text": "Microsoft"
},
{
"code": null,
"e": 34645,
"s": 34547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34717,
"s": 34645,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 34794,
"s": 34717,
"text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)"
},
{
"code": null,
"e": 34839,
"s": 34794,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 34869,
"s": 34839,
"text": "Resume Writing For Internship"
},
{
"code": null,
"e": 34950,
"s": 34869,
"text": "HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022"
},
{
"code": null,
"e": 34977,
"s": 34950,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 35037,
"s": 34977,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 35088,
"s": 35037,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 35130,
"s": 35088,
"text": "Amazon AWS Interview Experience for SDE-1"
}
]
|
FileSystem isOpen() method in Java with Examples - GeeksforGeeks | 03 Dec, 2019
The isOpen() method of a FileSystem class is used to return true if file system is open. This method is very helpful to know filesystem is open or not. File systems created by the default provider are always open.
Syntax:
public abstract boolean isOpen()
Parameters: This method accepts nothing.
Return value: This method returns true if, and only if, this file system is open.
Below programs illustrate the isOpen() method:Program 1:
// Java program to demonstrate// FileSystem.isOpen() method import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create the object of Path Path path = Paths.get( "C:\\Movies\\document.txt"); // get FileSystem object FileSystem fs = path.getFileSystem(); // apply isOpen() methods boolean answer = fs.isOpen(); // print System.out.println("isOpen: " + answer); }}
Output:
Program 2:
// Java program to demonstrate// FileSystem.isOpen() method import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create the object of Path Path path = Paths.get( "E:// Tutorials// file.txt"); // get FileSystem object FileSystem fs = path.getFileSystem(); // apply isOpen() methods boolean answer = fs.isOpen(); // print System.out.println(fs + " is Open: " + answer); }}
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/FileSystem.html#isOpen()
Java-FileSystem
Java-Functions
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 25851,
"s": 25823,
"text": "\n03 Dec, 2019"
},
{
"code": null,
"e": 26065,
"s": 25851,
"text": "The isOpen() method of a FileSystem class is used to return true if file system is open. This method is very helpful to know filesystem is open or not. File systems created by the default provider are always open."
},
{
"code": null,
"e": 26073,
"s": 26065,
"text": "Syntax:"
},
{
"code": null,
"e": 26107,
"s": 26073,
"text": "public abstract boolean isOpen()\n"
},
{
"code": null,
"e": 26148,
"s": 26107,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 26230,
"s": 26148,
"text": "Return value: This method returns true if, and only if, this file system is open."
},
{
"code": null,
"e": 26287,
"s": 26230,
"text": "Below programs illustrate the isOpen() method:Program 1:"
},
{
"code": "// Java program to demonstrate// FileSystem.isOpen() method import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create the object of Path Path path = Paths.get( \"C:\\\\Movies\\\\document.txt\"); // get FileSystem object FileSystem fs = path.getFileSystem(); // apply isOpen() methods boolean answer = fs.isOpen(); // print System.out.println(\"isOpen: \" + answer); }}",
"e": 26849,
"s": 26287,
"text": null
},
{
"code": null,
"e": 26857,
"s": 26849,
"text": "Output:"
},
{
"code": null,
"e": 26868,
"s": 26857,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// FileSystem.isOpen() method import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // create the object of Path Path path = Paths.get( \"E:// Tutorials// file.txt\"); // get FileSystem object FileSystem fs = path.getFileSystem(); // apply isOpen() methods boolean answer = fs.isOpen(); // print System.out.println(fs + \" is Open: \" + answer); }}",
"e": 27438,
"s": 26868,
"text": null
},
{
"code": null,
"e": 27532,
"s": 27438,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/FileSystem.html#isOpen()"
},
{
"code": null,
"e": 27548,
"s": 27532,
"text": "Java-FileSystem"
},
{
"code": null,
"e": 27563,
"s": 27548,
"text": "Java-Functions"
},
{
"code": null,
"e": 27585,
"s": 27563,
"text": "java.nio.file package"
},
{
"code": null,
"e": 27590,
"s": 27585,
"text": "Java"
},
{
"code": null,
"e": 27595,
"s": 27590,
"text": "Java"
},
{
"code": null,
"e": 27693,
"s": 27595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27744,
"s": 27693,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27759,
"s": 27744,
"text": "Stream In Java"
},
{
"code": null,
"e": 27778,
"s": 27759,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27809,
"s": 27778,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27827,
"s": 27809,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27859,
"s": 27827,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27879,
"s": 27859,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27911,
"s": 27879,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27935,
"s": 27911,
"text": "Singleton Class in Java"
}
]
|
CSS Animation and @Keyframes Property - GeeksforGeeks | 03 Jun, 2020
CSS allows the animation of HTML elements without using JavaScript. An animation lets an element systematically and with proper timing, change from one style to another. You can change whatever CSS properties you want, end number of times, as you want it. To use CSS animation, you must first specify some @keyframes for the animation. @keyframes will describe which styles that element will have at specific times.
We will be using a basic example such as the animation of a battery charging.
The @keyframes property has the option to divide the animation time into parts/percentage and perform an activity that is specified for that part of the whole duration of the animation. the @keyframes property is given to each animation according to the name of that animation. It allows you to run the animation infinitely as well.
Here, is a simple CSS block that explains the usage of @keyframes:
Example: Usage of @keyframes in a background-color change.
<!DOCTYPE html><html> <head> <title> CSS Animation and @Keyframes Property </title> <style> div { width: 200px; height: 200px; margin: 200px; border-radius: 100px; background-color: red; animation: circle 8s infinite; } @keyframes circle { 0% { background-color: red; } 25% { background-color: yellow; } 50% { background-color: blue; } 100% { background-color: green; } } </style></head> <body> <div></div></body> </html>
Output:
Note: While using @keyframes, there are some guidelines that are set in place for you to create a smooth and working animation. Guidelines such as, make sure you make the transitions smooth and specify when the style change will happen in percent or with the keywords “from” and “to”, which is the same as 0% and 100%. 0% is when the animation is going to start, 100% is when the animation is completed. For the best browser support, i.e. to make sure the animation is supported in all browsers throughout the internet, be sure to always define both the 0% and the 100% selectors.
The animation for the charging of a battery is important, as it helps you to understand just how the @keyframes property will help you to time your animation in perfect intervals and hence help make the transitions smooth. The charging of the battery is used to explain how you can set various animations within the given time-period by specifying the percentage of division, exactly how in the example the battery charges from 0-25% then from 25-50% and so on.
<!DOCTYPE html><html> <head> <title> CSS Animation and @Keyframes Property </title> <style> body { background-color: #fff; } .battery { height: 140px; width: 321px; border: 5px solid #000; border-radius: 7px; position: absolute; margin: auto; left: 0; right: 0; bottom: 0; top: 0; } .top { height: 40px; width: 25px; background-color: #000; position: relative; left: 325px; top: 52px; border-radius: 0 3px 3px 0; } .charge1, .charge2, .charge3, .charge4 { width: 75px; height: 130px; background-color: #3BC700; position: relative; opacity: 0; } .charge1 { margin: 9px 2px 3px 6px; bottom: 44px; animation: charge-1 2s infinite; } .charge2 { margin: 9px 9px 3px 9px; bottom: 183px; left: 75px; animation: charge-2 2s infinite; } .charge3 { margin: 9px 9px 3px 12px; bottom: 322px; left: 150px; animation: charge-3 2s infinite; } .charge4 { margin: 9px 2px 3px 15px; bottom: 461px; left: 225px; animation: charge-4 2s infinite; } @keyframes charge-1 { 25%, 100% { opacity: 1; } } @keyframes charge-2 { 0%, 25% { opacity: 0; } 50%, 100% { opacity: 1; } } @keyframes charge-3 { 0%, 50% { opacity: 0; } 75%, 100% { opacity: 1; } } @keyframes charge-4 { 0%, 75% { opacity: 0; } 100% { opacity: 1; } } </style></head> <body> <div class="battery"> <div class="top"></div> <div class="charge1"></div> <div class="charge2"></div> <div class="charge3"></div> <div class="charge4"></div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 27039,
"s": 26621,
"text": "CSS allows the animation of HTML elements without using JavaScript. An animation lets an element systematically and with proper timing, change from one style to another. You can change whatever CSS properties you want, end number of times, as you want it. To use CSS animation, you must first specify some @keyframes for the animation. @keyframes will describe which styles that element will have at specific times. "
},
{
"code": null,
"e": 27119,
"s": 27039,
"text": "We will be using a basic example such as the animation of a battery charging. "
},
{
"code": null,
"e": 27453,
"s": 27119,
"text": "The @keyframes property has the option to divide the animation time into parts/percentage and perform an activity that is specified for that part of the whole duration of the animation. the @keyframes property is given to each animation according to the name of that animation. It allows you to run the animation infinitely as well. "
},
{
"code": null,
"e": 27521,
"s": 27453,
"text": "Here, is a simple CSS block that explains the usage of @keyframes: "
},
{
"code": null,
"e": 27580,
"s": 27521,
"text": "Example: Usage of @keyframes in a background-color change."
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Animation and @Keyframes Property </title> <style> div { width: 200px; height: 200px; margin: 200px; border-radius: 100px; background-color: red; animation: circle 8s infinite; } @keyframes circle { 0% { background-color: red; } 25% { background-color: yellow; } 50% { background-color: blue; } 100% { background-color: green; } } </style></head> <body> <div></div></body> </html>",
"e": 28283,
"s": 27580,
"text": null
},
{
"code": null,
"e": 28292,
"s": 28283,
"text": "Output:\n"
},
{
"code": null,
"e": 28873,
"s": 28292,
"text": "Note: While using @keyframes, there are some guidelines that are set in place for you to create a smooth and working animation. Guidelines such as, make sure you make the transitions smooth and specify when the style change will happen in percent or with the keywords “from” and “to”, which is the same as 0% and 100%. 0% is when the animation is going to start, 100% is when the animation is completed. For the best browser support, i.e. to make sure the animation is supported in all browsers throughout the internet, be sure to always define both the 0% and the 100% selectors."
},
{
"code": null,
"e": 29335,
"s": 28873,
"text": "The animation for the charging of a battery is important, as it helps you to understand just how the @keyframes property will help you to time your animation in perfect intervals and hence help make the transitions smooth. The charging of the battery is used to explain how you can set various animations within the given time-period by specifying the percentage of division, exactly how in the example the battery charges from 0-25% then from 25-50% and so on."
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS Animation and @Keyframes Property </title> <style> body { background-color: #fff; } .battery { height: 140px; width: 321px; border: 5px solid #000; border-radius: 7px; position: absolute; margin: auto; left: 0; right: 0; bottom: 0; top: 0; } .top { height: 40px; width: 25px; background-color: #000; position: relative; left: 325px; top: 52px; border-radius: 0 3px 3px 0; } .charge1, .charge2, .charge3, .charge4 { width: 75px; height: 130px; background-color: #3BC700; position: relative; opacity: 0; } .charge1 { margin: 9px 2px 3px 6px; bottom: 44px; animation: charge-1 2s infinite; } .charge2 { margin: 9px 9px 3px 9px; bottom: 183px; left: 75px; animation: charge-2 2s infinite; } .charge3 { margin: 9px 9px 3px 12px; bottom: 322px; left: 150px; animation: charge-3 2s infinite; } .charge4 { margin: 9px 2px 3px 15px; bottom: 461px; left: 225px; animation: charge-4 2s infinite; } @keyframes charge-1 { 25%, 100% { opacity: 1; } } @keyframes charge-2 { 0%, 25% { opacity: 0; } 50%, 100% { opacity: 1; } } @keyframes charge-3 { 0%, 50% { opacity: 0; } 75%, 100% { opacity: 1; } } @keyframes charge-4 { 0%, 75% { opacity: 0; } 100% { opacity: 1; } } </style></head> <body> <div class=\"battery\"> <div class=\"top\"></div> <div class=\"charge1\"></div> <div class=\"charge2\"></div> <div class=\"charge3\"></div> <div class=\"charge4\"></div> </div></body> </html>",
"e": 31766,
"s": 29335,
"text": null
},
{
"code": null,
"e": 31775,
"s": 31766,
"text": "Output:\n"
},
{
"code": null,
"e": 31912,
"s": 31775,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 31921,
"s": 31912,
"text": "CSS-Misc"
},
{
"code": null,
"e": 31931,
"s": 31921,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31935,
"s": 31931,
"text": "CSS"
},
{
"code": null,
"e": 31940,
"s": 31935,
"text": "HTML"
},
{
"code": null,
"e": 31957,
"s": 31940,
"text": "Web Technologies"
},
{
"code": null,
"e": 31984,
"s": 31957,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31989,
"s": 31984,
"text": "HTML"
},
{
"code": null,
"e": 32087,
"s": 31989,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32124,
"s": 32087,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32163,
"s": 32124,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32192,
"s": 32163,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32234,
"s": 32192,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32269,
"s": 32234,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 32329,
"s": 32269,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32382,
"s": 32329,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 32443,
"s": 32382,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 32493,
"s": 32443,
"text": "How to Insert Form Data into Database using PHP ?"
}
]
|
Data Structures | Binary Trees | Question 15 - GeeksforGeeks | 28 Jun, 2021
In a complete k-ary tree, every internal node has exactly k children or no child. The number of leaves in such a tree with n internal nodes is:(A) nk(B) (n – 1) k+ 1(C) n( k – 1) + 1(D) n(k – 1)Answer: (C)Explanation: For an k-ary tree where each node has k children or no children, following relation holdsL = (k-1)*n + 1
Where L is the number of leaf nodes and n is the number of internal nodes.since its a complete k tree, so every internal node will have K childLet us see following for example
o
/ | \
o o o
/ | \ / | \ / | \
o o o o o o o o o
k = 3
Number of internal nodes n = 4
Number of leaf nodes = (k-1)*n + 1
= (3-1)*4 + 1
= 9
Quiz of this Question
mehreena741
Binary Trees Quiz
Data Structures
Data Structures-Binary Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Linked List | Question 5
Data Structures | Tree Traversals | Question 4
Data Structures | Linked List | Question 6
Data Structures | Graph | Question 9
FIFO vs LIFO approach in Programming
Introduction to Data Structures
Data Structures | Stack | Question 1
Binary Search Tree | Set 3 (Iterative Delete)
Advantages of vector over array in C++
Program to create Custom Vector Class in C++ | [
{
"code": null,
"e": 26251,
"s": 26223,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26574,
"s": 26251,
"text": "In a complete k-ary tree, every internal node has exactly k children or no child. The number of leaves in such a tree with n internal nodes is:(A) nk(B) (n – 1) k+ 1(C) n( k – 1) + 1(D) n(k – 1)Answer: (C)Explanation: For an k-ary tree where each node has k children or no children, following relation holdsL = (k-1)*n + 1"
},
{
"code": null,
"e": 26750,
"s": 26574,
"text": "Where L is the number of leaf nodes and n is the number of internal nodes.since its a complete k tree, so every internal node will have K childLet us see following for example"
},
{
"code": null,
"e": 27032,
"s": 26750,
"text": " o\n / | \\\n o o o\n / | \\ / | \\ / | \\\n o o o o o o o o o\n \n\nk = 3\nNumber of internal nodes n = 4\nNumber of leaf nodes = (k-1)*n + 1\n = (3-1)*4 + 1\n = 9 "
},
{
"code": null,
"e": 27054,
"s": 27032,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 27066,
"s": 27054,
"text": "mehreena741"
},
{
"code": null,
"e": 27084,
"s": 27066,
"text": "Binary Trees Quiz"
},
{
"code": null,
"e": 27100,
"s": 27084,
"text": "Data Structures"
},
{
"code": null,
"e": 27129,
"s": 27100,
"text": "Data Structures-Binary Trees"
},
{
"code": null,
"e": 27145,
"s": 27129,
"text": "Data Structures"
},
{
"code": null,
"e": 27161,
"s": 27145,
"text": "Data Structures"
},
{
"code": null,
"e": 27259,
"s": 27161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27302,
"s": 27259,
"text": "Data Structures | Linked List | Question 5"
},
{
"code": null,
"e": 27349,
"s": 27302,
"text": "Data Structures | Tree Traversals | Question 4"
},
{
"code": null,
"e": 27392,
"s": 27349,
"text": "Data Structures | Linked List | Question 6"
},
{
"code": null,
"e": 27429,
"s": 27392,
"text": "Data Structures | Graph | Question 9"
},
{
"code": null,
"e": 27466,
"s": 27429,
"text": "FIFO vs LIFO approach in Programming"
},
{
"code": null,
"e": 27498,
"s": 27466,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 27535,
"s": 27498,
"text": "Data Structures | Stack | Question 1"
},
{
"code": null,
"e": 27581,
"s": 27535,
"text": "Binary Search Tree | Set 3 (Iterative Delete)"
},
{
"code": null,
"e": 27620,
"s": 27581,
"text": "Advantages of vector over array in C++"
}
]
|
HCF of array of fractions (or rational numbers) - GeeksforGeeks | 14 Jul, 2021
Given a fraction series. Find the H.C.F of a given fraction series. Examples:
Input : [{2, 5}, {8, 9}, {16, 81}, {10, 27}]
Output : 2, 405
Explanation : 2/405 is the largest number that
divides all 2/5, 8/9, 16/81 and 10/27.
Input : [{9, 10}, {12, 25}, {18, 35}, {21, 40}]
Output : 3, 1400
Approach:
Find the H.C.F of numerators. Find the L.C.M of denominators. Calculate fraction of H.C.F/L.C.M. Reduce the fraction to Lowest Fraction.
C++
Java
Python3
C#
Javascript
// CPP program to find HCF of array of// rational numbers (fractions).#include <iostream>using namespace std; // hcf of two numberint gcd(int a, int b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesint findHcf(int** arr, int size){ int ans = arr[0][0]; for (int i = 1; i < size; i++) ans = gcd(ans, arr[i][0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesint findLcm(int** arr, int size){ // ans contains LCM of arr[0][1], ..arr[i][1] int ans = arr[0][1]; for (int i = 1; i < size; i++) ans = (((arr[i][1] * ans)) / (gcd(arr[i][1], ans))); // return lcm of denominator return (ans);} // Core Functionint* hcfOfFraction(int** arr, int size){ // found hcf of numerator int hcf_of_num = findHcf(arr, size); // found lcm of denominator int lcm_of_deno = findLcm(arr, size); int* result = new int[2]; result[0] = hcf_of_num; result[1] = lcm_of_deno; for (int i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Main functionint main(){ int size = 4; int** arr = new int*[size]; // Initialize the every row // with size 2 (1 for numerator // and 2 for denominator) for (int i = 0; i < size; i++) arr[i] = new int[2]; arr[0][0] = 9; arr[0][1] = 10; arr[1][0] = 12; arr[1][1] = 25; arr[2][0] = 18; arr[2][1] = 35; arr[3][0] = 21; arr[3][1] = 40; // function for calculate the result int* result = hcfOfFraction(arr, size); // print the result cout << result[0] << ", " << result[1] << endl; return 0;}
// Java program to find HCF of array of// rational numbers (fractions).class GFG{ // hcf of two numberstatic int gcd(int a, int b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesstatic int findHcf(int [][]arr, int size){ int ans = arr[0][0]; for (int i = 1; i < size; i++) ans = gcd(ans, arr[i][0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesstatic int findLcm(int[][] arr, int size){ // ans contains LCM of arr[0][1], ..arr[i][1] int ans = arr[0][1]; for (int i = 1; i < size; i++) ans = (((arr[i][1] * ans)) / (gcd(arr[i][1], ans))); // return lcm of denominator return (ans);} // Core Functionstatic int[] hcfOfFraction(int[][] arr, int size){ // found hcf of numerator int hcf_of_num = findHcf(arr, size); // found lcm of denominator int lcm_of_deno = findLcm(arr, size); int[] result = new int[2]; result[0] = hcf_of_num; result[1] = lcm_of_deno; for (int i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Driver codepublic static void main(String[] args){ int size = 4; int[][] arr = new int[size][size]; // Initialize the every row // with size 2 (1 for numerator // and 2 for denominator) for (int i = 0; i < size; i++) arr[i] = new int[2]; arr[0][0] = 9; arr[0][1] = 10; arr[1][0] = 12; arr[1][1] = 25; arr[2][0] = 18; arr[2][1] = 35; arr[3][0] = 21; arr[3][1] = 40; // function for calculate the result int[] result = hcfOfFraction(arr, size); // print the result System.out.println(result[0] + ", " + result[1]); }} /* This code contributed by PrinciRaj1992 */
# Python 3 program to find HCF of array offrom math import gcd # find hcf of numerator seriesdef findHcf(arr, size): ans = arr[0][0] for i in range(1, size, 1): ans = gcd(ans, arr[i][0]) # return hcf of numerator return (ans) # find lcm of denominator seriesdef findLcm(arr, size): # ans contains LCM of arr[0][1], ..arr[i][1] ans = arr[0][1] for i in range(1, size, 1): ans = int((((arr[i][1] * ans)) / (gcd(arr[i][1], ans)))) # return lcm of denominator return (ans) # Core Functiondef hcfOfFraction(arr, size): # found hcf of numerator hcf_of_num = findHcf(arr, size) # found lcm of denominator lcm_of_deno = findLcm(arr, size) result = [0 for i in range(2)] result[0] = hcf_of_num result[1] = lcm_of_deno i = int(result[0] / 2) while(i > 1): if ((result[1] % i == 0) and (result[0] % i == 0)): result[1] = int(result[1] / i) result[0] = (result[0] / i) # return result return (result) # Driver Codeif __name__ == '__main__': size = 4 arr = [0 for i in range(size)] # Initialize the every row # with size 2 (1 for numerator # and 2 for denominator) for i in range(size): arr[i] = [0 for i in range(2)] arr[0][0] = 9 arr[0][1] = 10 arr[1][0] = 12 arr[1][1] = 25 arr[2][0] = 18 arr[2][1] = 35 arr[3][0] = 21 arr[3][1] = 40 # function for calculate the result result = hcfOfFraction(arr, size) # print the result print(result[0], ",", result[1]) # This code is contributed by# Surendra_Gangwar
// C# program to find HCF of array of// rational numbers (fractions).using System; class GFG{ // hcf of two numberstatic int gcd(int a, int b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesstatic int findHcf(int [,]arr, int size){ int ans = arr[0, 0]; for (int i = 1; i < size; i++) ans = gcd(ans, arr[i, 0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesstatic int findLcm(int[,] arr, int size){ // ans contains LCM of arr[0,1], ..arr[i,1] int ans = arr[0,1]; for (int i = 1; i < size; i++) ans = (((arr[i, 1] * ans)) / (gcd(arr[i, 1], ans))); // return lcm of denominator return (ans);} // Core Functionstatic int[] hcfOfFraction(int[,] arr, int size){ // found hcf of numerator int hcf_of_num = findHcf(arr, size); // found lcm of denominator int lcm_of_deno = findLcm(arr, size); int[] result = new int[2]; result[0] = hcf_of_num; result[1] = lcm_of_deno; for (int i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Driver codepublic static void Main(String[] args){ int size = 4; int[,] arr = new int[size, size]; // Initialize the every row // with size 2 (1 for numerator // and 2 for denominator) arr[0, 0] = 9; arr[0, 1] = 10; arr[1, 0] = 12; arr[1, 1] = 25; arr[2, 0] = 18; arr[2, 1] = 35; arr[3, 0] = 21; arr[3, 1] = 40; // function for calculate the result int[] result = hcfOfFraction(arr, size); // print the result Console.WriteLine(result[0] + ", " + result[1]); }} // This code has been contributed by 29AjayKumar
<script>// Javascript program to find HCF of array of// rational numbers (fractions). // hcf of two numberfunction gcd(a,b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesfunction findHcf(arr,size){ let ans = arr[0][0]; for (let i = 1; i < size; i++) ans = gcd(ans, arr[i][0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesfunction findLcm(arr,size){ // ans contains LCM of arr[0][1], ..arr[i][1] let ans = arr[0][1]; for (let i = 1; i < size; i++) ans = Math.floor(((arr[i][1] * ans)) / (gcd(arr[i][1], ans))); // return lcm of denominator return (ans);} // Core Functionfunction hcfOfFraction(arr,size){ // found hcf of numerator let hcf_of_num = findHcf(arr, size); // found lcm of denominator let lcm_of_deno = findLcm(arr, size); let result = new Array(2); result[0] = hcf_of_num; result[1] = lcm_of_deno; for (let i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Driver codelet size = 4;let arr = new Array(size); // Initialize the every row// with size 2 (1 for numerator// and 2 for denominator)for (let i = 0; i < size; i++) arr[i] = new Array(2); arr[0][0] = 9;arr[0][1] = 10;arr[1][0] = 12;arr[1][1] = 25;arr[2][0] = 18;arr[2][1] = 35;arr[3][0] = 21;arr[3][1] = 40; // function for calculate the resultlet result = hcfOfFraction(arr, size); // print the resultdocument.write(result[0] + ", " + result[1]+"<br>"); // This code is contributed by rag2127</script>
Output:
3, 1400
princiraj1992
29AjayKumar
SURENDRA_GANGWAR
rag2127
GCD-LCM
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Python | Using 2D arrays/lists the right way
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26055,
"s": 26027,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 26135,
"s": 26055,
"text": "Given a fraction series. Find the H.C.F of a given fraction series. Examples: "
},
{
"code": null,
"e": 26350,
"s": 26135,
"text": "Input : [{2, 5}, {8, 9}, {16, 81}, {10, 27}]\nOutput : 2, 405 \nExplanation : 2/405 is the largest number that\ndivides all 2/5, 8/9, 16/81 and 10/27.\n\nInput : [{9, 10}, {12, 25}, {18, 35}, {21, 40}]\nOutput : 3, 1400"
},
{
"code": null,
"e": 26364,
"s": 26352,
"text": "Approach: "
},
{
"code": null,
"e": 26503,
"s": 26364,
"text": "Find the H.C.F of numerators. Find the L.C.M of denominators. Calculate fraction of H.C.F/L.C.M. Reduce the fraction to Lowest Fraction. "
},
{
"code": null,
"e": 26509,
"s": 26505,
"text": "C++"
},
{
"code": null,
"e": 26514,
"s": 26509,
"text": "Java"
},
{
"code": null,
"e": 26522,
"s": 26514,
"text": "Python3"
},
{
"code": null,
"e": 26525,
"s": 26522,
"text": "C#"
},
{
"code": null,
"e": 26536,
"s": 26525,
"text": "Javascript"
},
{
"code": "// CPP program to find HCF of array of// rational numbers (fractions).#include <iostream>using namespace std; // hcf of two numberint gcd(int a, int b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesint findHcf(int** arr, int size){ int ans = arr[0][0]; for (int i = 1; i < size; i++) ans = gcd(ans, arr[i][0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesint findLcm(int** arr, int size){ // ans contains LCM of arr[0][1], ..arr[i][1] int ans = arr[0][1]; for (int i = 1; i < size; i++) ans = (((arr[i][1] * ans)) / (gcd(arr[i][1], ans))); // return lcm of denominator return (ans);} // Core Functionint* hcfOfFraction(int** arr, int size){ // found hcf of numerator int hcf_of_num = findHcf(arr, size); // found lcm of denominator int lcm_of_deno = findLcm(arr, size); int* result = new int[2]; result[0] = hcf_of_num; result[1] = lcm_of_deno; for (int i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Main functionint main(){ int size = 4; int** arr = new int*[size]; // Initialize the every row // with size 2 (1 for numerator // and 2 for denominator) for (int i = 0; i < size; i++) arr[i] = new int[2]; arr[0][0] = 9; arr[0][1] = 10; arr[1][0] = 12; arr[1][1] = 25; arr[2][0] = 18; arr[2][1] = 35; arr[3][0] = 21; arr[3][1] = 40; // function for calculate the result int* result = hcfOfFraction(arr, size); // print the result cout << result[0] << \", \" << result[1] << endl; return 0;}",
"e": 28352,
"s": 26536,
"text": null
},
{
"code": "// Java program to find HCF of array of// rational numbers (fractions).class GFG{ // hcf of two numberstatic int gcd(int a, int b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesstatic int findHcf(int [][]arr, int size){ int ans = arr[0][0]; for (int i = 1; i < size; i++) ans = gcd(ans, arr[i][0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesstatic int findLcm(int[][] arr, int size){ // ans contains LCM of arr[0][1], ..arr[i][1] int ans = arr[0][1]; for (int i = 1; i < size; i++) ans = (((arr[i][1] * ans)) / (gcd(arr[i][1], ans))); // return lcm of denominator return (ans);} // Core Functionstatic int[] hcfOfFraction(int[][] arr, int size){ // found hcf of numerator int hcf_of_num = findHcf(arr, size); // found lcm of denominator int lcm_of_deno = findLcm(arr, size); int[] result = new int[2]; result[0] = hcf_of_num; result[1] = lcm_of_deno; for (int i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Driver codepublic static void main(String[] args){ int size = 4; int[][] arr = new int[size][size]; // Initialize the every row // with size 2 (1 for numerator // and 2 for denominator) for (int i = 0; i < size; i++) arr[i] = new int[2]; arr[0][0] = 9; arr[0][1] = 10; arr[1][0] = 12; arr[1][1] = 25; arr[2][0] = 18; arr[2][1] = 35; arr[3][0] = 21; arr[3][1] = 40; // function for calculate the result int[] result = hcfOfFraction(arr, size); // print the result System.out.println(result[0] + \", \" + result[1]); }} /* This code contributed by PrinciRaj1992 */",
"e": 30240,
"s": 28352,
"text": null
},
{
"code": "# Python 3 program to find HCF of array offrom math import gcd # find hcf of numerator seriesdef findHcf(arr, size): ans = arr[0][0] for i in range(1, size, 1): ans = gcd(ans, arr[i][0]) # return hcf of numerator return (ans) # find lcm of denominator seriesdef findLcm(arr, size): # ans contains LCM of arr[0][1], ..arr[i][1] ans = arr[0][1] for i in range(1, size, 1): ans = int((((arr[i][1] * ans)) / (gcd(arr[i][1], ans)))) # return lcm of denominator return (ans) # Core Functiondef hcfOfFraction(arr, size): # found hcf of numerator hcf_of_num = findHcf(arr, size) # found lcm of denominator lcm_of_deno = findLcm(arr, size) result = [0 for i in range(2)] result[0] = hcf_of_num result[1] = lcm_of_deno i = int(result[0] / 2) while(i > 1): if ((result[1] % i == 0) and (result[0] % i == 0)): result[1] = int(result[1] / i) result[0] = (result[0] / i) # return result return (result) # Driver Codeif __name__ == '__main__': size = 4 arr = [0 for i in range(size)] # Initialize the every row # with size 2 (1 for numerator # and 2 for denominator) for i in range(size): arr[i] = [0 for i in range(2)] arr[0][0] = 9 arr[0][1] = 10 arr[1][0] = 12 arr[1][1] = 25 arr[2][0] = 18 arr[2][1] = 35 arr[3][0] = 21 arr[3][1] = 40 # function for calculate the result result = hcfOfFraction(arr, size) # print the result print(result[0], \",\", result[1]) # This code is contributed by# Surendra_Gangwar",
"e": 31856,
"s": 30240,
"text": null
},
{
"code": "// C# program to find HCF of array of// rational numbers (fractions).using System; class GFG{ // hcf of two numberstatic int gcd(int a, int b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesstatic int findHcf(int [,]arr, int size){ int ans = arr[0, 0]; for (int i = 1; i < size; i++) ans = gcd(ans, arr[i, 0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesstatic int findLcm(int[,] arr, int size){ // ans contains LCM of arr[0,1], ..arr[i,1] int ans = arr[0,1]; for (int i = 1; i < size; i++) ans = (((arr[i, 1] * ans)) / (gcd(arr[i, 1], ans))); // return lcm of denominator return (ans);} // Core Functionstatic int[] hcfOfFraction(int[,] arr, int size){ // found hcf of numerator int hcf_of_num = findHcf(arr, size); // found lcm of denominator int lcm_of_deno = findLcm(arr, size); int[] result = new int[2]; result[0] = hcf_of_num; result[1] = lcm_of_deno; for (int i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Driver codepublic static void Main(String[] args){ int size = 4; int[,] arr = new int[size, size]; // Initialize the every row // with size 2 (1 for numerator // and 2 for denominator) arr[0, 0] = 9; arr[0, 1] = 10; arr[1, 0] = 12; arr[1, 1] = 25; arr[2, 0] = 18; arr[2, 1] = 35; arr[3, 0] = 21; arr[3, 1] = 40; // function for calculate the result int[] result = hcfOfFraction(arr, size); // print the result Console.WriteLine(result[0] + \", \" + result[1]); }} // This code has been contributed by 29AjayKumar",
"e": 33691,
"s": 31856,
"text": null
},
{
"code": "<script>// Javascript program to find HCF of array of// rational numbers (fractions). // hcf of two numberfunction gcd(a,b){ if (a % b == 0) return b; else return (gcd(b, a % b));} // find hcf of numerator seriesfunction findHcf(arr,size){ let ans = arr[0][0]; for (let i = 1; i < size; i++) ans = gcd(ans, arr[i][0]); // return hcf of numerator return (ans);} // find lcm of denominator seriesfunction findLcm(arr,size){ // ans contains LCM of arr[0][1], ..arr[i][1] let ans = arr[0][1]; for (let i = 1; i < size; i++) ans = Math.floor(((arr[i][1] * ans)) / (gcd(arr[i][1], ans))); // return lcm of denominator return (ans);} // Core Functionfunction hcfOfFraction(arr,size){ // found hcf of numerator let hcf_of_num = findHcf(arr, size); // found lcm of denominator let lcm_of_deno = findLcm(arr, size); let result = new Array(2); result[0] = hcf_of_num; result[1] = lcm_of_deno; for (let i = result[0] / 2; i > 1; i--) { if ((result[1] % i == 0) && (result[0] % i == 0)) { result[1] /= i; result[0] /= i; } } // return result return (result);} // Driver codelet size = 4;let arr = new Array(size); // Initialize the every row// with size 2 (1 for numerator// and 2 for denominator)for (let i = 0; i < size; i++) arr[i] = new Array(2); arr[0][0] = 9;arr[0][1] = 10;arr[1][0] = 12;arr[1][1] = 25;arr[2][0] = 18;arr[2][1] = 35;arr[3][0] = 21;arr[3][1] = 40; // function for calculate the resultlet result = hcfOfFraction(arr, size); // print the resultdocument.write(result[0] + \", \" + result[1]+\"<br>\"); // This code is contributed by rag2127</script>",
"e": 35416,
"s": 33691,
"text": null
},
{
"code": null,
"e": 35426,
"s": 35416,
"text": "Output: "
},
{
"code": null,
"e": 35434,
"s": 35426,
"text": "3, 1400"
},
{
"code": null,
"e": 35450,
"s": 35436,
"text": "princiraj1992"
},
{
"code": null,
"e": 35462,
"s": 35450,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35479,
"s": 35462,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 35487,
"s": 35479,
"text": "rag2127"
},
{
"code": null,
"e": 35495,
"s": 35487,
"text": "GCD-LCM"
},
{
"code": null,
"e": 35502,
"s": 35495,
"text": "Arrays"
},
{
"code": null,
"e": 35515,
"s": 35502,
"text": "Mathematical"
},
{
"code": null,
"e": 35522,
"s": 35515,
"text": "Arrays"
},
{
"code": null,
"e": 35535,
"s": 35522,
"text": "Mathematical"
},
{
"code": null,
"e": 35633,
"s": 35535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35656,
"s": 35633,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 35688,
"s": 35656,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35702,
"s": 35688,
"text": "Linear Search"
},
{
"code": null,
"e": 35723,
"s": 35702,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 35768,
"s": 35723,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 35798,
"s": 35768,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35858,
"s": 35798,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35873,
"s": 35858,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35916,
"s": 35873,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
fill_n() function in C++ STL with examples - GeeksforGeeks | 11 Oct, 2019
The fill_n() function in C++ STL is used to fill some default values in a container. The fill_n() function is used to fill values upto first n positions from a starting position. It accepts an iterator begin and the number of positions n as arguments and fills the first n position starting from the position pointed by begin with the given value.
Syntax:
void fill_n(iterator begin, int n, type value);
Parameters:
begin: The function will start filling values from the position pointed by the iterator begin.
n: This parameter denotes the number of positions to be filled starting from the position pointed by first parameter begin.
value: This parameter denotes the value to be filled by the function in the container.
Return Value: This function does not returns any value.
Below program illustrate the fill_n() function in C++ STL:
// C++ program to demonstrate working of fil_n()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize first four values // to 7 fill_n(vect.begin(), 4, 7); for (int i = 0; i < vect.size(); i++) cout << ' ' << vect[i]; cout << '\n'; // calling fill to initialize 3 elements from // "begin()+3" with value 4 fill_n(vect.begin() + 3, 3, 4); for (int i = 0; i < vect.size(); i++) cout << ' ' << vect[i]; cout << '\n'; return 0;}
7 7 7 7 0 0 0 0
7 7 7 4 4 4 0 0
Reference: http://www.cplusplus.com/reference/algorithm/fill_n/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++ | [
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 25691,
"s": 25343,
"text": "The fill_n() function in C++ STL is used to fill some default values in a container. The fill_n() function is used to fill values upto first n positions from a starting position. It accepts an iterator begin and the number of positions n as arguments and fills the first n position starting from the position pointed by begin with the given value."
},
{
"code": null,
"e": 25699,
"s": 25691,
"text": "Syntax:"
},
{
"code": null,
"e": 25748,
"s": 25699,
"text": "void fill_n(iterator begin, int n, type value);\n"
},
{
"code": null,
"e": 25760,
"s": 25748,
"text": "Parameters:"
},
{
"code": null,
"e": 25855,
"s": 25760,
"text": "begin: The function will start filling values from the position pointed by the iterator begin."
},
{
"code": null,
"e": 25979,
"s": 25855,
"text": "n: This parameter denotes the number of positions to be filled starting from the position pointed by first parameter begin."
},
{
"code": null,
"e": 26066,
"s": 25979,
"text": "value: This parameter denotes the value to be filled by the function in the container."
},
{
"code": null,
"e": 26122,
"s": 26066,
"text": "Return Value: This function does not returns any value."
},
{
"code": null,
"e": 26181,
"s": 26122,
"text": "Below program illustrate the fill_n() function in C++ STL:"
},
{
"code": "// C++ program to demonstrate working of fil_n()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize first four values // to 7 fill_n(vect.begin(), 4, 7); for (int i = 0; i < vect.size(); i++) cout << ' ' << vect[i]; cout << '\\n'; // calling fill to initialize 3 elements from // \"begin()+3\" with value 4 fill_n(vect.begin() + 3, 3, 4); for (int i = 0; i < vect.size(); i++) cout << ' ' << vect[i]; cout << '\\n'; return 0;}",
"e": 26721,
"s": 26181,
"text": null
},
{
"code": null,
"e": 26755,
"s": 26721,
"text": "7 7 7 7 0 0 0 0\n 7 7 7 4 4 4 0 0\n"
},
{
"code": null,
"e": 26819,
"s": 26755,
"text": "Reference: http://www.cplusplus.com/reference/algorithm/fill_n/"
},
{
"code": null,
"e": 26833,
"s": 26819,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26837,
"s": 26833,
"text": "C++"
},
{
"code": null,
"e": 26841,
"s": 26837,
"text": "CPP"
},
{
"code": null,
"e": 26939,
"s": 26841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26967,
"s": 26939,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26987,
"s": 26967,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27011,
"s": 26987,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27044,
"s": 27011,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27069,
"s": 27044,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27113,
"s": 27069,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27158,
"s": 27113,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27182,
"s": 27158,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 27235,
"s": 27182,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
]
|
Python | Ways to convert Boolean values to integer - GeeksforGeeks | 10 Sep, 2021
Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task.Method #1: Using int() method
Python3
# Python code to demonstrate# to convert boolean value to integer # Initialising Valuesbool_val = True # Printing initial Valuesprint("Initial value", bool_val) # Converting boolean to integerbool_val = int(bool_val == True) # Printing resultprint("Resultant value", bool_val)
Initial value True
Resultant value 1
Method #2: Using Naive Approach
Python3
# Python code to demonstrate# to convert boolean# value to integer # Initialising Valuesbool_val = True # Printing initial Valuesprint("Initial value", bool_val) # Converting boolean to integerif bool_val: bool_val = 1else: bool_val = 0# Printing resultprint("Resultant value", bool_val)
Initial value True
Resultant value 1
Method #3: Using numpy In case where boolean list is present
Python3
# Python code to demonstrate# to convert boolean# value to integer import numpy# Initialising Valuesbool_val = numpy.array([True, False]) # Printing initial Valuesprint("Initial values", bool_val) # Converting boolean to integerbool_val = numpy.multiply(bool_val, 1)# Printing resultprint("Resultant values", str(bool_val))
Initial values [ True False]
Resultant values [1 0]
Method #4: Using map() in case where boolean list is present
Python3
# Python code to demonstrate# to convert boolean# value to integer # Initialising Valuesbool_val = [True, False] # Printing initial Valuesprint("Initial value", bool_val) # Converting boolean to integerbool_val = list(map(int, bool_val)) # Printing resultprint("Resultant value", str(bool_val))
Initial value [True, False]
Resultant value [1, 0]
sagartomar9927
anikakapoor
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25411,
"s": 25383,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 25606,
"s": 25411,
"text": "Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task.Method #1: Using int() method "
},
{
"code": null,
"e": 25614,
"s": 25606,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to convert boolean value to integer # Initialising Valuesbool_val = True # Printing initial Valuesprint(\"Initial value\", bool_val) # Converting boolean to integerbool_val = int(bool_val == True) # Printing resultprint(\"Resultant value\", bool_val) ",
"e": 25901,
"s": 25614,
"text": null
},
{
"code": null,
"e": 25938,
"s": 25901,
"text": "Initial value True\nResultant value 1"
},
{
"code": null,
"e": 25976,
"s": 25940,
"text": " Method #2: Using Naive Approach "
},
{
"code": null,
"e": 25984,
"s": 25976,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to convert boolean# value to integer # Initialising Valuesbool_val = True # Printing initial Valuesprint(\"Initial value\", bool_val) # Converting boolean to integerif bool_val: bool_val = 1else: bool_val = 0# Printing resultprint(\"Resultant value\", bool_val) ",
"e": 26288,
"s": 25984,
"text": null
},
{
"code": null,
"e": 26325,
"s": 26288,
"text": "Initial value True\nResultant value 1"
},
{
"code": null,
"e": 26392,
"s": 26327,
"text": " Method #3: Using numpy In case where boolean list is present "
},
{
"code": null,
"e": 26400,
"s": 26392,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to convert boolean# value to integer import numpy# Initialising Valuesbool_val = numpy.array([True, False]) # Printing initial Valuesprint(\"Initial values\", bool_val) # Converting boolean to integerbool_val = numpy.multiply(bool_val, 1)# Printing resultprint(\"Resultant values\", str(bool_val))",
"e": 26726,
"s": 26400,
"text": null
},
{
"code": null,
"e": 26778,
"s": 26726,
"text": "Initial values [ True False]\nResultant values [1 0]"
},
{
"code": null,
"e": 26845,
"s": 26780,
"text": " Method #4: Using map() in case where boolean list is present "
},
{
"code": null,
"e": 26853,
"s": 26845,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to convert boolean# value to integer # Initialising Valuesbool_val = [True, False] # Printing initial Valuesprint(\"Initial value\", bool_val) # Converting boolean to integerbool_val = list(map(int, bool_val)) # Printing resultprint(\"Resultant value\", str(bool_val))",
"e": 27150,
"s": 26853,
"text": null
},
{
"code": null,
"e": 27201,
"s": 27150,
"text": "Initial value [True, False]\nResultant value [1, 0]"
},
{
"code": null,
"e": 27218,
"s": 27203,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27230,
"s": 27218,
"text": "anikakapoor"
},
{
"code": null,
"e": 27237,
"s": 27230,
"text": "Python"
},
{
"code": null,
"e": 27253,
"s": 27237,
"text": "Python Programs"
},
{
"code": null,
"e": 27351,
"s": 27253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27369,
"s": 27351,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27404,
"s": 27369,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27436,
"s": 27404,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27458,
"s": 27436,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27500,
"s": 27458,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27543,
"s": 27500,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27582,
"s": 27543,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27628,
"s": 27582,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27666,
"s": 27628,
"text": "Python | Convert a list to dictionary"
}
]
|
Find closest smaller value for every element in array - GeeksforGeeks | 04 Feb, 2022
Given an array of integers, find the closest smaller element for every element. If there is no smaller element then print -1
Examples:
Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 6, -1, 10, 5, 12, 11
Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 5 -1 10 5 12 11
A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest smaller element. Time complexity of this solution is O(n*n)
A better solution is to use sorting. We sort all elements, then for every element, traverse toward left until we find a smaller element (Note that there can be multiple occurrences of an element).
An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest smaller operations in O(Log n) time.
C++
Java
Python3
C#
Javascript
// C++ program to find closest smaller value for// every array element#include <bits/stdc++.h>using namespace std; void closestSmaller(int arr[], int n){ // Insert all array elements into a TreeSet set<int> ts; for (int i = 0; i < n; i++) ts.insert(arr[i]); // Find largest smaller element for every // array element for (int i = 0; i < n; i++) { auto smaller = ts.lower_bound(arr[i]); if (smaller == ts.begin()) cout << -1 << " "; else cout << *(--smaller) << " "; }} // Driver Codeint main(){ int arr[] = {10, 5, 11, 6, 20, 12}; int n = sizeof(arr) / sizeof(arr[0]); closestSmaller(arr, n); return 0;} // This code is contributed by// sanjeev2552
// Java program to find closest smaller value for// every array elementimport java.util.*; class TreeSetDemo { public static void closestSmaller(int[] arr) { // Insert all array elements into a TreeSet TreeSet<Integer> ts = new TreeSet<Integer>(); for (int i = 0; i < arr.length; i++) ts.add(arr[i]); // Find largest smaller element for every // array element for (int i = 0; i < arr.length; i++) { Integer smaller = ts.lower(arr[i]); if (smaller == null) System.out.print(-1 + " "); else System.out.print(smaller + " "); } } public static void main(String[] args) { int[] arr = { 10, 5, 11, 6, 20, 12 }; closestSmaller(arr); }}
# Python3 program to find closest smaller value# for every array elementimport bisect def closestSmaller(arr, n): # Insert all array elements into a TreeSet ts = set() for i in range(n): ts.add(arr[i]) # Find largest smaller element for every # array element for i in range(n): smaller = bisect.bisect_left(list(ts), arr[i]) if (smaller == 0): print(-1, end = " ") else: print((list(ts)[smaller - 1]), end = " ") smaller -= 1 # Driver Codearr = [ 10, 5, 11, 6, 20, 12 ]n = len(arr) closestSmaller(arr, n) # This code is contributed by rohitsingh07052
// C# program to find closest smaller value for// every array elementusing System;using System.Linq;using System.Collections.Generic; public class TreeSetDemo { public static void closestSmaller(int[] arr) { // Insert all array elements into a TreeSet SortedSet<int> ts = new SortedSet<int>(); for (int i = 0; i < arr.Length; i++) ts.Add(arr[i]); // Find largest smaller element for every // array element for (int i = 0; i < arr.Length; i++) { int smaller = lower_bound(ts, arr[i]); if (smaller == 0) Console.Write(-1 + " "); else Console.Write(smaller + " "); } } public static int lower_bound(SortedSet<int> s, int val) { List<int> temp = new List<int>(); temp.AddRange(s); temp.Sort(); temp.Reverse(); if (temp.IndexOf(val) + 1 == temp.Count) return -1; return temp[temp.IndexOf(val) + 1]; } public static void Main(String[] args) { int[] arr = { 10, 5, 11, 6, 20, 12 }; closestSmaller(arr); }} // This code is contributed by Rajput-Ji
<script>// javascript program to find closest smaller value for// every array elementclass TreeSetDemo { function closestSmaller(arr) { // Insert all array elements into a TreeSet var ts = new Set(); for (i = 0; i < arr.length; i++) ts.add(arr[i]); // Find largest smaller element for every // array element for (i = 0; i < arr.length; i++) { var smaller = upper_bound(ts, arr[i]); if (smaller == null) document.write(-1 + " "); else document.write(smaller + " "); } } function upper_bound(s, val) { let temp = [...s]; temp.sort((a, b) => b - a); return temp[temp.indexOf(val) + 1]; } var arr = [ 10, 5, 11, 6, 20, 12 ]; closestSmaller(arr); // This code is contributed by Rajput-Ji</script>
6 -1 10 5 12 11
Time Complexity : O(n Log n)
sanjeev2552
rohitsingh07052
Rajput-Ji
java-treeset
Self-Balancing-BST
Arrays
Binary Search Tree
Java Programs
Arrays
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Construct BST from given preorder traversal | Set 1 | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n04 Feb, 2022"
},
{
"code": null,
"e": 26166,
"s": 26041,
"text": "Given an array of integers, find the closest smaller element for every element. If there is no smaller element then print -1"
},
{
"code": null,
"e": 26177,
"s": 26166,
"text": "Examples: "
},
{
"code": null,
"e": 26247,
"s": 26177,
"text": "Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 6, -1, 10, 5, 12, 11 "
},
{
"code": null,
"e": 26315,
"s": 26247,
"text": "Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 5 -1 10 5 12 11 "
},
{
"code": null,
"e": 26529,
"s": 26315,
"text": "A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest smaller element. Time complexity of this solution is O(n*n)"
},
{
"code": null,
"e": 26726,
"s": 26529,
"text": "A better solution is to use sorting. We sort all elements, then for every element, traverse toward left until we find a smaller element (Note that there can be multiple occurrences of an element)."
},
{
"code": null,
"e": 26922,
"s": 26726,
"text": "An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest smaller operations in O(Log n) time."
},
{
"code": null,
"e": 26926,
"s": 26922,
"text": "C++"
},
{
"code": null,
"e": 26931,
"s": 26926,
"text": "Java"
},
{
"code": null,
"e": 26939,
"s": 26931,
"text": "Python3"
},
{
"code": null,
"e": 26942,
"s": 26939,
"text": "C#"
},
{
"code": null,
"e": 26953,
"s": 26942,
"text": "Javascript"
},
{
"code": "// C++ program to find closest smaller value for// every array element#include <bits/stdc++.h>using namespace std; void closestSmaller(int arr[], int n){ // Insert all array elements into a TreeSet set<int> ts; for (int i = 0; i < n; i++) ts.insert(arr[i]); // Find largest smaller element for every // array element for (int i = 0; i < n; i++) { auto smaller = ts.lower_bound(arr[i]); if (smaller == ts.begin()) cout << -1 << \" \"; else cout << *(--smaller) << \" \"; }} // Driver Codeint main(){ int arr[] = {10, 5, 11, 6, 20, 12}; int n = sizeof(arr) / sizeof(arr[0]); closestSmaller(arr, n); return 0;} // This code is contributed by// sanjeev2552",
"e": 27691,
"s": 26953,
"text": null
},
{
"code": "// Java program to find closest smaller value for// every array elementimport java.util.*; class TreeSetDemo { public static void closestSmaller(int[] arr) { // Insert all array elements into a TreeSet TreeSet<Integer> ts = new TreeSet<Integer>(); for (int i = 0; i < arr.length; i++) ts.add(arr[i]); // Find largest smaller element for every // array element for (int i = 0; i < arr.length; i++) { Integer smaller = ts.lower(arr[i]); if (smaller == null) System.out.print(-1 + \" \"); else System.out.print(smaller + \" \"); } } public static void main(String[] args) { int[] arr = { 10, 5, 11, 6, 20, 12 }; closestSmaller(arr); }}",
"e": 28477,
"s": 27691,
"text": null
},
{
"code": "# Python3 program to find closest smaller value# for every array elementimport bisect def closestSmaller(arr, n): # Insert all array elements into a TreeSet ts = set() for i in range(n): ts.add(arr[i]) # Find largest smaller element for every # array element for i in range(n): smaller = bisect.bisect_left(list(ts), arr[i]) if (smaller == 0): print(-1, end = \" \") else: print((list(ts)[smaller - 1]), end = \" \") smaller -= 1 # Driver Codearr = [ 10, 5, 11, 6, 20, 12 ]n = len(arr) closestSmaller(arr, n) # This code is contributed by rohitsingh07052",
"e": 29127,
"s": 28477,
"text": null
},
{
"code": "// C# program to find closest smaller value for// every array elementusing System;using System.Linq;using System.Collections.Generic; public class TreeSetDemo { public static void closestSmaller(int[] arr) { // Insert all array elements into a TreeSet SortedSet<int> ts = new SortedSet<int>(); for (int i = 0; i < arr.Length; i++) ts.Add(arr[i]); // Find largest smaller element for every // array element for (int i = 0; i < arr.Length; i++) { int smaller = lower_bound(ts, arr[i]); if (smaller == 0) Console.Write(-1 + \" \"); else Console.Write(smaller + \" \"); } } public static int lower_bound(SortedSet<int> s, int val) { List<int> temp = new List<int>(); temp.AddRange(s); temp.Sort(); temp.Reverse(); if (temp.IndexOf(val) + 1 == temp.Count) return -1; return temp[temp.IndexOf(val) + 1]; } public static void Main(String[] args) { int[] arr = { 10, 5, 11, 6, 20, 12 }; closestSmaller(arr); }} // This code is contributed by Rajput-Ji",
"e": 30164,
"s": 29127,
"text": null
},
{
"code": "<script>// javascript program to find closest smaller value for// every array elementclass TreeSetDemo { function closestSmaller(arr) { // Insert all array elements into a TreeSet var ts = new Set(); for (i = 0; i < arr.length; i++) ts.add(arr[i]); // Find largest smaller element for every // array element for (i = 0; i < arr.length; i++) { var smaller = upper_bound(ts, arr[i]); if (smaller == null) document.write(-1 + \" \"); else document.write(smaller + \" \"); } } function upper_bound(s, val) { let temp = [...s]; temp.sort((a, b) => b - a); return temp[temp.indexOf(val) + 1]; } var arr = [ 10, 5, 11, 6, 20, 12 ]; closestSmaller(arr); // This code is contributed by Rajput-Ji</script>",
"e": 31048,
"s": 30164,
"text": null
},
{
"code": null,
"e": 31064,
"s": 31048,
"text": "6 -1 10 5 12 11"
},
{
"code": null,
"e": 31096,
"s": 31066,
"text": "Time Complexity : O(n Log n) "
},
{
"code": null,
"e": 31108,
"s": 31096,
"text": "sanjeev2552"
},
{
"code": null,
"e": 31124,
"s": 31108,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 31134,
"s": 31124,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31147,
"s": 31134,
"text": "java-treeset"
},
{
"code": null,
"e": 31166,
"s": 31147,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 31173,
"s": 31166,
"text": "Arrays"
},
{
"code": null,
"e": 31192,
"s": 31173,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 31206,
"s": 31192,
"text": "Java Programs"
},
{
"code": null,
"e": 31213,
"s": 31206,
"text": "Arrays"
},
{
"code": null,
"e": 31232,
"s": 31213,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 31330,
"s": 31232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31357,
"s": 31330,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 31388,
"s": 31357,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 31413,
"s": 31388,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31451,
"s": 31413,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31472,
"s": 31451,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31522,
"s": 31472,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 31551,
"s": 31522,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 31587,
"s": 31551,
"text": "Binary Search Tree | Set 2 (Delete)"
},
{
"code": null,
"e": 31637,
"s": 31587,
"text": "A program to check if a binary tree is BST or not"
}
]
|
K-ary Heap - GeeksforGeeks | 17 Dec, 2021
Prerequisite – Binary Heap
K-ary heaps are a generalization of binary heap(K=2) in which each node have K children instead of 2. Just like binary heap, it follows two properties:1) Nearly complete binary tree, with all levels having maximum number of nodes except the last, which is filled in left to right manner.2) Like Binary Heap, it can be divided into two categories: (a) Max k-ary heap (key at root is greater than all descendants and same is recursively true for all nodes). (b) Min k-ary heap (key at root is lesser than all descendants and same is recursively true for all nodes)
Examples:
3-ary max heap - root node is maximum
of all nodes
10
/ | \
7 9 8
/ | \ /
4 6 5 7
3-ary min heap -root node is minimum
of all nodes
10
/ | \
12 11 13
/ | \
14 15 18
The height of a complete k-ary tree with n-nodes is given by logkn.Applications of K-ary Heap:
K-ary heap when used in the implementation of priority queue allows faster decrease key operation as compared to binary heap ( O(log2n)) for binary heap vs O(logkn) for K-ary heap). Nevertheless, it causes the complexity of extractMin() operation to increase to O(k log kn) as compared to the complexity of O(log2n) when using binary heaps for priority queue. This allows K-ary heap to be more efficient in algorithms where decrease priority operations are more common than extractMin() operation.Example: Dijkstra’s algorithm for single source shortest path and Prim’s algorithm for minimum spanning tree
K-ary heap has better memory cache behaviour than a binary heap which allows them to run more quickly in practice, although it has a larger worst case running time of both extractMin() and delete() operation (both being O(k log kn) ).
Implementation Assuming 0 based indexing of array, an array represents a K-ary heap such that for any node we consider:
Parent of the node at index i (except root node) is located at index (i-1)/k
Children of the node at index i are at indices (k*i)+1 , (k*i)+2 .... (k*i)+k
The last non-leaf node of a heap of size n is located at index (n-2)/k
buildHeap() : Builds a heap from an input array. This function runs a loop starting from the last non-leaf node all the way upto the root node, calling a function restoreDown(also known as maHeapify) for each index that restores the passed index at the correct position of the heap by shifting the node down in the K-ary heap building it in a bottom up manner. Why do we start the loop from the last non-leaf node ? Because all the nodes after that are leaf nodes which will trivially satisfy the heap property as they don’t have any children and hence, are already roots of a K-ary max heap.restoreDown() (or maxHeapify) : Used to maintain heap property. It runs a loop where it finds the maximum of all the node’s children, compares it with its own value and swaps if the max(value of all children) > (value at node). It repeats this step until the node is restored into its original position in the heap.extractMax() : Extracting the root node. A k-ary max heap stores the largest element in its root. It returns the root node, copies last node to the first, calls restore down on the first node thus maintaining the heap property.insert() : Inserting a node into the heap This can be achieved by inserting the node at the last position and calling restoreUp() on the given index to restore the node at its proper position in the heap. restoreUp() iteratively compares a given node with its parent, since in a max heap the parent is always greater than or equal to its children nodes, the node is swapped with its parent only when its key is greater than the parent.Combining the above, following is the C++ implementation of K-ary heap.
CPP
// C++ program to demonstrate all operations of// k-ary Heap#include<bits/stdc++.h> using namespace std; // function to heapify (or restore the max- heap// property). This is used to build a k-ary heap// and in extractMin()// att[] -- Array that stores heap// len -- Size of array// index -- index of element to be restored// (or heapified)void restoreDown(int arr[], int len, int index, int k){ // child array to store indexes of all // the children of given node int child[k+1]; while (1) { // child[i]=-1 if the node is a leaf // children (no children) for (int i=1; i<=k; i++) child[i] = ((k*index + i) < len) ? (k*index + i) : -1; // max_child stores the maximum child and // max_child_index holds its index int max_child = -1, max_child_index ; // loop to find the maximum of all // the children of a given node for (int i=1; i<=k; i++) { if (child[i] != -1 && arr[child[i]] > max_child) { max_child_index = child[i]; max_child = arr[child[i]]; } } // leaf node if (max_child == -1) break; // swap only if the key of max_child_index // is greater than the key of node if (arr[index] < arr[max_child_index]) swap(arr[index], arr[max_child_index]); index = max_child_index; }} // Restores a given node up in the heap. This is used// in decreaseKey() and insert()void restoreUp(int arr[], int index, int k){ // parent stores the index of the parent variable // of the node int parent = (index-1)/k; // Loop should only run till root node in case the // element inserted is the maximum restore up will // send it to the root node while (parent>=0) { if (arr[index] > arr[parent]) { swap(arr[index], arr[parent]); index = parent; parent = (index -1)/k; } // node has been restored at the correct position else break; }} // Function to build a heap of arr[0..n-1] and value of k.void buildHeap(int arr[], int n, int k){ // Heapify all internal nodes starting from last // non-leaf node all the way upto the root node // and calling restore down on each for (int i= (n-1)/k; i>=0; i--) restoreDown(arr, n, i, k);} // Function to insert a value in a heap. Parameters are// the array, size of heap, value k and the element to// be insertedvoid insert(int arr[], int* n, int k, int elem){ // Put the new element in the last position arr[*n] = elem; // Increase heap size by 1 *n = *n+1; // Call restoreUp on the last index restoreUp(arr, *n-1, k);} // Function that returns the key of root node of// the heap and then restores the heap property// of the remaining nodesint extractMax(int arr[], int* n, int k){ // Stores the key of root node to be returned int max = arr[0]; // Copy the last node's key to the root node arr[0] = arr[*n-1]; // Decrease heap size by 1 *n = *n-1; // Call restoreDown on the root node to restore // it to the correct position in the heap restoreDown(arr, *n, 0, k); return max;} // Driver programint main(){ const int capacity = 100; int arr[capacity] = {4, 5, 6, 7, 8, 9, 10}; int n = 7; int k = 3; buildHeap(arr, n, k); printf("Built Heap : \n"); for (int i=0; i<n; i++) printf("%d ", arr[i]); int element = 3; insert(arr, &n, k, element); printf("\n\nHeap after insertion of %d: \n", element); for (int i=0; i<n; i++) printf("%d ", arr[i]); printf("\n\nExtracted max is %d", extractMax(arr, &n, k)); printf("\n\nHeap after extract max: \n"); for (int i=0; i<n; i++) printf("%d ", arr[i]); return 0;}
Output
Built Heap :
10 9 6 7 8 4 5
Heap after insertion of 3:
10 9 6 7 8 4 5 3
Extracted max is 10
Heap after extract max:
9 8 6 7 3 4 5
Time Complexity Analysis
For a k-ary heap, with n nodes the maximum height of the given heap will be logkn. So restoreUp() run for maximum of logkn times (as at every iteration the node is shifted one level up is case of restoreUp() or one level down in case of restoreDown).
restoreDown() calls itself recursively for k children. So time complexity of this functions is O(k logkn).
Insert and decreaseKey() operations call restoreUp() once. So complexity is O(logkn).
Since extractMax() calls restoreDown() once, its complexity O(k logkn)
Time complexity of build heap is O(n) (Analysis is similar to binary heap)
This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Amey Pawar
MohitRohatgi
avtarkumar719
Heap
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
K'th Smallest/Largest Element in Unsorted Array | Set 1
k largest(or smallest) elements in an array
Building Heap from Array
Insertion and Deletion in Heaps
Sliding Window Maximum (Maximum of all subarrays of size k)
Max Heap in Java
Priority Queue in Python
Priority Queue using Binary Heap
Merge k sorted arrays | Set 1 | [
{
"code": null,
"e": 39003,
"s": 38975,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 39032,
"s": 39003,
"text": "Prerequisite – Binary Heap "
},
{
"code": null,
"e": 39596,
"s": 39032,
"text": "K-ary heaps are a generalization of binary heap(K=2) in which each node have K children instead of 2. Just like binary heap, it follows two properties:1) Nearly complete binary tree, with all levels having maximum number of nodes except the last, which is filled in left to right manner.2) Like Binary Heap, it can be divided into two categories: (a) Max k-ary heap (key at root is greater than all descendants and same is recursively true for all nodes). (b) Min k-ary heap (key at root is lesser than all descendants and same is recursively true for all nodes) "
},
{
"code": null,
"e": 39607,
"s": 39596,
"text": "Examples: "
},
{
"code": null,
"e": 39873,
"s": 39607,
"text": "3-ary max heap - root node is maximum\n of all nodes\n 10\n / | \\\n 7 9 8\n / | \\ /\n4 6 5 7\n\n\n3-ary min heap -root node is minimum \n of all nodes\n 10\n / | \\\n 12 11 13\n / | \\\n14 15 18 "
},
{
"code": null,
"e": 39969,
"s": 39873,
"text": "The height of a complete k-ary tree with n-nodes is given by logkn.Applications of K-ary Heap: "
},
{
"code": null,
"e": 40575,
"s": 39969,
"text": "K-ary heap when used in the implementation of priority queue allows faster decrease key operation as compared to binary heap ( O(log2n)) for binary heap vs O(logkn) for K-ary heap). Nevertheless, it causes the complexity of extractMin() operation to increase to O(k log kn) as compared to the complexity of O(log2n) when using binary heaps for priority queue. This allows K-ary heap to be more efficient in algorithms where decrease priority operations are more common than extractMin() operation.Example: Dijkstra’s algorithm for single source shortest path and Prim’s algorithm for minimum spanning tree"
},
{
"code": null,
"e": 40810,
"s": 40575,
"text": "K-ary heap has better memory cache behaviour than a binary heap which allows them to run more quickly in practice, although it has a larger worst case running time of both extractMin() and delete() operation (both being O(k log kn) )."
},
{
"code": null,
"e": 40931,
"s": 40810,
"text": "Implementation Assuming 0 based indexing of array, an array represents a K-ary heap such that for any node we consider: "
},
{
"code": null,
"e": 41008,
"s": 40931,
"text": "Parent of the node at index i (except root node) is located at index (i-1)/k"
},
{
"code": null,
"e": 41086,
"s": 41008,
"text": "Children of the node at index i are at indices (k*i)+1 , (k*i)+2 .... (k*i)+k"
},
{
"code": null,
"e": 41157,
"s": 41086,
"text": "The last non-leaf node of a heap of size n is located at index (n-2)/k"
},
{
"code": null,
"e": 42798,
"s": 41157,
"text": "buildHeap() : Builds a heap from an input array. This function runs a loop starting from the last non-leaf node all the way upto the root node, calling a function restoreDown(also known as maHeapify) for each index that restores the passed index at the correct position of the heap by shifting the node down in the K-ary heap building it in a bottom up manner. Why do we start the loop from the last non-leaf node ? Because all the nodes after that are leaf nodes which will trivially satisfy the heap property as they don’t have any children and hence, are already roots of a K-ary max heap.restoreDown() (or maxHeapify) : Used to maintain heap property. It runs a loop where it finds the maximum of all the node’s children, compares it with its own value and swaps if the max(value of all children) > (value at node). It repeats this step until the node is restored into its original position in the heap.extractMax() : Extracting the root node. A k-ary max heap stores the largest element in its root. It returns the root node, copies last node to the first, calls restore down on the first node thus maintaining the heap property.insert() : Inserting a node into the heap This can be achieved by inserting the node at the last position and calling restoreUp() on the given index to restore the node at its proper position in the heap. restoreUp() iteratively compares a given node with its parent, since in a max heap the parent is always greater than or equal to its children nodes, the node is swapped with its parent only when its key is greater than the parent.Combining the above, following is the C++ implementation of K-ary heap."
},
{
"code": null,
"e": 42802,
"s": 42798,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate all operations of// k-ary Heap#include<bits/stdc++.h> using namespace std; // function to heapify (or restore the max- heap// property). This is used to build a k-ary heap// and in extractMin()// att[] -- Array that stores heap// len -- Size of array// index -- index of element to be restored// (or heapified)void restoreDown(int arr[], int len, int index, int k){ // child array to store indexes of all // the children of given node int child[k+1]; while (1) { // child[i]=-1 if the node is a leaf // children (no children) for (int i=1; i<=k; i++) child[i] = ((k*index + i) < len) ? (k*index + i) : -1; // max_child stores the maximum child and // max_child_index holds its index int max_child = -1, max_child_index ; // loop to find the maximum of all // the children of a given node for (int i=1; i<=k; i++) { if (child[i] != -1 && arr[child[i]] > max_child) { max_child_index = child[i]; max_child = arr[child[i]]; } } // leaf node if (max_child == -1) break; // swap only if the key of max_child_index // is greater than the key of node if (arr[index] < arr[max_child_index]) swap(arr[index], arr[max_child_index]); index = max_child_index; }} // Restores a given node up in the heap. This is used// in decreaseKey() and insert()void restoreUp(int arr[], int index, int k){ // parent stores the index of the parent variable // of the node int parent = (index-1)/k; // Loop should only run till root node in case the // element inserted is the maximum restore up will // send it to the root node while (parent>=0) { if (arr[index] > arr[parent]) { swap(arr[index], arr[parent]); index = parent; parent = (index -1)/k; } // node has been restored at the correct position else break; }} // Function to build a heap of arr[0..n-1] and value of k.void buildHeap(int arr[], int n, int k){ // Heapify all internal nodes starting from last // non-leaf node all the way upto the root node // and calling restore down on each for (int i= (n-1)/k; i>=0; i--) restoreDown(arr, n, i, k);} // Function to insert a value in a heap. Parameters are// the array, size of heap, value k and the element to// be insertedvoid insert(int arr[], int* n, int k, int elem){ // Put the new element in the last position arr[*n] = elem; // Increase heap size by 1 *n = *n+1; // Call restoreUp on the last index restoreUp(arr, *n-1, k);} // Function that returns the key of root node of// the heap and then restores the heap property// of the remaining nodesint extractMax(int arr[], int* n, int k){ // Stores the key of root node to be returned int max = arr[0]; // Copy the last node's key to the root node arr[0] = arr[*n-1]; // Decrease heap size by 1 *n = *n-1; // Call restoreDown on the root node to restore // it to the correct position in the heap restoreDown(arr, *n, 0, k); return max;} // Driver programint main(){ const int capacity = 100; int arr[capacity] = {4, 5, 6, 7, 8, 9, 10}; int n = 7; int k = 3; buildHeap(arr, n, k); printf(\"Built Heap : \\n\"); for (int i=0; i<n; i++) printf(\"%d \", arr[i]); int element = 3; insert(arr, &n, k, element); printf(\"\\n\\nHeap after insertion of %d: \\n\", element); for (int i=0; i<n; i++) printf(\"%d \", arr[i]); printf(\"\\n\\nExtracted max is %d\", extractMax(arr, &n, k)); printf(\"\\n\\nHeap after extract max: \\n\"); for (int i=0; i<n; i++) printf(\"%d \", arr[i]); return 0;}",
"e": 46737,
"s": 42802,
"text": null
},
{
"code": null,
"e": 46745,
"s": 46737,
"text": "Output "
},
{
"code": null,
"e": 46884,
"s": 46745,
"text": "Built Heap : \n10 9 6 7 8 4 5 \n\nHeap after insertion of 3: \n10 9 6 7 8 4 5 3 \n\nExtracted max is 10\n\nHeap after extract max: \n9 8 6 7 3 4 5 "
},
{
"code": null,
"e": 46910,
"s": 46884,
"text": "Time Complexity Analysis "
},
{
"code": null,
"e": 47161,
"s": 46910,
"text": "For a k-ary heap, with n nodes the maximum height of the given heap will be logkn. So restoreUp() run for maximum of logkn times (as at every iteration the node is shifted one level up is case of restoreUp() or one level down in case of restoreDown)."
},
{
"code": null,
"e": 47268,
"s": 47161,
"text": "restoreDown() calls itself recursively for k children. So time complexity of this functions is O(k logkn)."
},
{
"code": null,
"e": 47354,
"s": 47268,
"text": "Insert and decreaseKey() operations call restoreUp() once. So complexity is O(logkn)."
},
{
"code": null,
"e": 47425,
"s": 47354,
"text": "Since extractMax() calls restoreDown() once, its complexity O(k logkn)"
},
{
"code": null,
"e": 47500,
"s": 47425,
"text": "Time complexity of build heap is O(n) (Analysis is similar to binary heap)"
},
{
"code": null,
"e": 47765,
"s": 47500,
"text": "This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 47889,
"s": 47765,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 47900,
"s": 47889,
"text": "Amey Pawar"
},
{
"code": null,
"e": 47913,
"s": 47900,
"text": "MohitRohatgi"
},
{
"code": null,
"e": 47927,
"s": 47913,
"text": "avtarkumar719"
},
{
"code": null,
"e": 47932,
"s": 47927,
"text": "Heap"
},
{
"code": null,
"e": 47937,
"s": 47932,
"text": "Heap"
},
{
"code": null,
"e": 48035,
"s": 47937,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48066,
"s": 48035,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 48122,
"s": 48066,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 48166,
"s": 48122,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 48191,
"s": 48166,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 48223,
"s": 48191,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 48283,
"s": 48223,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
},
{
"code": null,
"e": 48300,
"s": 48283,
"text": "Max Heap in Java"
},
{
"code": null,
"e": 48325,
"s": 48300,
"text": "Priority Queue in Python"
},
{
"code": null,
"e": 48358,
"s": 48325,
"text": "Priority Queue using Binary Heap"
}
]
|
PGP - Authentication and Confidentiality - GeeksforGeeks | 07 Mar, 2022
In 2013, when the NSA (United States National Security Agency) scandal was leaked to the public, people started to opt for the services which can provide them a strong privacy for their data. Among the services people opted for, most particularly for Emails, were different plug-ins and extensions for their browsers. Interestingly, among the various plug-ins and extensions that people started to use, there were two main programs that were solely responsible for the complete email security that the people needed. One was S/MIME which we will see later and the other was PGP.
As said, PGP (Pretty Good Privacy), is a popular program that is used to provide confidentiality and authentication services for electronic mail and file storage. It was designed by Phil Zimmermann way back in 1991. He designed it in such a way, that the best cryptographic algorithms such as RSA, Diffie-Hellman key exchange, DSS are used for the public-key encryption (or) asymmetric encryption; CAST-128, 3DES, IDEA are used for symmetric encryption and SHA-1 is used for hashing purposes. PGP software is an open source one and is not dependent on either of the OS (Operating System) or the processor. The application is based on a few commands which are very easy to use.
The following are the services offered by PGP:
1. Authentication
2. Confidentiality
3. Compression
4. Email Compatibility
5. Segmentation
In this article, we will see about Authentication and Confidentiality.
1. Authentication: Authentication basically means something that is used to validate something as true or real. To login into some sites sometimes we give our account name and password, that is an authentication verification procedure.
In the email world, checking the authenticity of an email is nothing but to check whether it actually came from the person it says. In emails, authentication has to be checked as there are some people who spoof the emails or some spams and sometimes it can cause a lot of inconvenience. The Authentication service in PGP is provided as follows:
As shown in the above figure, the Hash Function (H) calculates the Hash Value of the message. For the hashing purpose, SHA-1 is used and it produces a 160 bit output hash value. Then, using the sender’s private key (KPa), it is encrypted and it’s called as Digital Signature. The Message is then appended to the signature. All the process happened till now, is sometimes described as signing the message . Then the message is compressed to reduce the transmission overhead and is sent over to the receiver.
At the receiver’s end, the data is decompressed and the message, signature are obtained. The signature is then decrypted using the sender’s public key(PUa) and the hash value is obtained. The message is again passed to hash function and it’s hash value is calculated and obtained.
Both the values, one from signature and another from the recent output of hash function are compared and if both are same, it means that the email is actually sent from a known one and is legit, else it means that it’s not a legit one.
2. Confidentiality: Sometimes we see some packages labelled as ‘Confidential’, which means that those packages are not meant for all the people and only selected persons can see them. The same applies to the email confidentiality as well. Here, in the email service, only the sender and the receiver should be able to read the message, that means the contents have to be kept secret from every other person, except for those two.
PGP provides that Confidentiality service in the following manner:
The message is first compressed and a 128 bit session key (Ks), generated by the PGP, is used to encrypt the message through symmetric encryption. Then, the session key (Ks) itself gets encrypted through public key encryption (EP) using receiver’s public key(KUb) . Both the encrypted entities are now concatenated and sent to the receiver.
As you can see, the original message was compressed and then encrypted initially and hence even if any one could get hold of the traffic, he cannot read the contents as they are not in readable form and they can only read them if they had the session key (Ks). Even though session key is transmitted to the receiver and hence, is in the traffic, it is in encrypted form and only the receiver’s private key (KPb)can be used to decrypt that and thus our message would be completely safe.
At the receiver’s end, the encrypted session key is decrypted using receiver’s private key (KPb) and the message is decrypted with the obtained session key. Then, the message is decompressed to obtain the original message (M).
RSA algorithm is used for the public-key encryption and for the symmetric key encryption, CAST-128(or IDEA or 3DES) is used.
Practically, both the Authentication and Confidentiality services are provided in parallel as follows :
Note: M – Message H – Hash Function Ks – A random Session Key created for Symmetric Encryption purpose DP – Public-Key Decryption Algorithm EP – Public-Key Encryption Algorithm DC – Asymmetric Encryption Algorithm EC – Symmetric Encryption Algorithm KPb – A private key of user B used in Public-key encryption process KPa – A private key of user A used in Public-key encryption process PUa – A public key of user A used in Public-key encryption process PUb – A public key of user B used in Public-key encryption process || – Concatenation Z – Compression Function Z-1 – Decompression Function
tsp2121999
tharun435
ManasChhabra2
Network-security
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
TCP Server-Client implementation in C
Differences between IPv4 and IPv6
Types of Network Topology
Socket Programming in Python
TCP 3-Way Handshake Process
Types of Transmission Media
UDP Server-Client implementation in C
User Datagram Protocol (UDP)
Hamming Code in Computer Network | [
{
"code": null,
"e": 25773,
"s": 25745,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 26353,
"s": 25773,
"text": "In 2013, when the NSA (United States National Security Agency) scandal was leaked to the public, people started to opt for the services which can provide them a strong privacy for their data. Among the services people opted for, most particularly for Emails, were different plug-ins and extensions for their browsers. Interestingly, among the various plug-ins and extensions that people started to use, there were two main programs that were solely responsible for the complete email security that the people needed. One was S/MIME which we will see later and the other was PGP. "
},
{
"code": null,
"e": 27031,
"s": 26353,
"text": "As said, PGP (Pretty Good Privacy), is a popular program that is used to provide confidentiality and authentication services for electronic mail and file storage. It was designed by Phil Zimmermann way back in 1991. He designed it in such a way, that the best cryptographic algorithms such as RSA, Diffie-Hellman key exchange, DSS are used for the public-key encryption (or) asymmetric encryption; CAST-128, 3DES, IDEA are used for symmetric encryption and SHA-1 is used for hashing purposes. PGP software is an open source one and is not dependent on either of the OS (Operating System) or the processor. The application is based on a few commands which are very easy to use. "
},
{
"code": null,
"e": 27080,
"s": 27031,
"text": "The following are the services offered by PGP: "
},
{
"code": null,
"e": 27172,
"s": 27080,
"text": "1. Authentication\n2. Confidentiality\n3. Compression\n4. Email Compatibility\n5. Segmentation "
},
{
"code": null,
"e": 27244,
"s": 27172,
"text": "In this article, we will see about Authentication and Confidentiality. "
},
{
"code": null,
"e": 27481,
"s": 27244,
"text": "1. Authentication: Authentication basically means something that is used to validate something as true or real. To login into some sites sometimes we give our account name and password, that is an authentication verification procedure. "
},
{
"code": null,
"e": 27827,
"s": 27481,
"text": "In the email world, checking the authenticity of an email is nothing but to check whether it actually came from the person it says. In emails, authentication has to be checked as there are some people who spoof the emails or some spams and sometimes it can cause a lot of inconvenience. The Authentication service in PGP is provided as follows: "
},
{
"code": null,
"e": 28337,
"s": 27829,
"text": "As shown in the above figure, the Hash Function (H) calculates the Hash Value of the message. For the hashing purpose, SHA-1 is used and it produces a 160 bit output hash value. Then, using the sender’s private key (KPa), it is encrypted and it’s called as Digital Signature. The Message is then appended to the signature. All the process happened till now, is sometimes described as signing the message . Then the message is compressed to reduce the transmission overhead and is sent over to the receiver. "
},
{
"code": null,
"e": 28619,
"s": 28337,
"text": "At the receiver’s end, the data is decompressed and the message, signature are obtained. The signature is then decrypted using the sender’s public key(PUa) and the hash value is obtained. The message is again passed to hash function and it’s hash value is calculated and obtained. "
},
{
"code": null,
"e": 28856,
"s": 28619,
"text": "Both the values, one from signature and another from the recent output of hash function are compared and if both are same, it means that the email is actually sent from a known one and is legit, else it means that it’s not a legit one. "
},
{
"code": null,
"e": 29287,
"s": 28856,
"text": "2. Confidentiality: Sometimes we see some packages labelled as ‘Confidential’, which means that those packages are not meant for all the people and only selected persons can see them. The same applies to the email confidentiality as well. Here, in the email service, only the sender and the receiver should be able to read the message, that means the contents have to be kept secret from every other person, except for those two. "
},
{
"code": null,
"e": 29355,
"s": 29287,
"text": "PGP provides that Confidentiality service in the following manner: "
},
{
"code": null,
"e": 29699,
"s": 29357,
"text": "The message is first compressed and a 128 bit session key (Ks), generated by the PGP, is used to encrypt the message through symmetric encryption. Then, the session key (Ks) itself gets encrypted through public key encryption (EP) using receiver’s public key(KUb) . Both the encrypted entities are now concatenated and sent to the receiver. "
},
{
"code": null,
"e": 30186,
"s": 29699,
"text": "As you can see, the original message was compressed and then encrypted initially and hence even if any one could get hold of the traffic, he cannot read the contents as they are not in readable form and they can only read them if they had the session key (Ks). Even though session key is transmitted to the receiver and hence, is in the traffic, it is in encrypted form and only the receiver’s private key (KPb)can be used to decrypt that and thus our message would be completely safe. "
},
{
"code": null,
"e": 30414,
"s": 30186,
"text": "At the receiver’s end, the encrypted session key is decrypted using receiver’s private key (KPb) and the message is decrypted with the obtained session key. Then, the message is decompressed to obtain the original message (M). "
},
{
"code": null,
"e": 30540,
"s": 30414,
"text": "RSA algorithm is used for the public-key encryption and for the symmetric key encryption, CAST-128(or IDEA or 3DES) is used. "
},
{
"code": null,
"e": 30645,
"s": 30540,
"text": "Practically, both the Authentication and Confidentiality services are provided in parallel as follows : "
},
{
"code": null,
"e": 31241,
"s": 30647,
"text": "Note: M – Message H – Hash Function Ks – A random Session Key created for Symmetric Encryption purpose DP – Public-Key Decryption Algorithm EP – Public-Key Encryption Algorithm DC – Asymmetric Encryption Algorithm EC – Symmetric Encryption Algorithm KPb – A private key of user B used in Public-key encryption process KPa – A private key of user A used in Public-key encryption process PUa – A public key of user A used in Public-key encryption process PUb – A public key of user B used in Public-key encryption process || – Concatenation Z – Compression Function Z-1 – Decompression Function "
},
{
"code": null,
"e": 31252,
"s": 31241,
"text": "tsp2121999"
},
{
"code": null,
"e": 31262,
"s": 31252,
"text": "tharun435"
},
{
"code": null,
"e": 31276,
"s": 31262,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 31293,
"s": 31276,
"text": "Network-security"
},
{
"code": null,
"e": 31311,
"s": 31293,
"text": "Computer Networks"
},
{
"code": null,
"e": 31329,
"s": 31311,
"text": "Computer Networks"
},
{
"code": null,
"e": 31427,
"s": 31329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31459,
"s": 31427,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 31497,
"s": 31459,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 31531,
"s": 31497,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 31557,
"s": 31531,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 31586,
"s": 31557,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 31614,
"s": 31586,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 31642,
"s": 31614,
"text": "Types of Transmission Media"
},
{
"code": null,
"e": 31680,
"s": 31642,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 31709,
"s": 31680,
"text": "User Datagram Protocol (UDP)"
}
]
|
Reverse a string in Julia - reverse() Method - GeeksforGeeks | 26 Mar, 2020
The reverse() is an inbuilt function in julia which is used to return the reverse of the specified string.
Syntax:reverse(s::AbstractString)
Parameters:
a::AbstractString: Specified string
Returns: It returns the reverse of the specified string.
Example 1:
# Julia program to illustrate # the use of String reverse() method # Getting the reverse of the specified stringprintln(reverse("GFG"))println(reverse("gfg"))println(reverse("Geeks"))println(reverse("GeeksforGeeks"))
Output:
GFG
gfg
skeeG
skeeGrofskeeG
Example 2:
# Julia program to illustrate # the use of String reverse() method # Getting the reverse of the specified stringprintln(reverse("123"))println(reverse("5"))println(reverse("@#"))println(reverse("^&*"))
Output:
321
5
#@
*&^
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Creating array with repeated elements in Julia - repeat() Method
Manipulating matrices in Julia
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method | [
{
"code": null,
"e": 25787,
"s": 25759,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 25894,
"s": 25787,
"text": "The reverse() is an inbuilt function in julia which is used to return the reverse of the specified string."
},
{
"code": null,
"e": 25928,
"s": 25894,
"text": "Syntax:reverse(s::AbstractString)"
},
{
"code": null,
"e": 25940,
"s": 25928,
"text": "Parameters:"
},
{
"code": null,
"e": 25976,
"s": 25940,
"text": "a::AbstractString: Specified string"
},
{
"code": null,
"e": 26033,
"s": 25976,
"text": "Returns: It returns the reverse of the specified string."
},
{
"code": null,
"e": 26044,
"s": 26033,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of String reverse() method # Getting the reverse of the specified stringprintln(reverse(\"GFG\"))println(reverse(\"gfg\"))println(reverse(\"Geeks\"))println(reverse(\"GeeksforGeeks\"))",
"e": 26262,
"s": 26044,
"text": null
},
{
"code": null,
"e": 26270,
"s": 26262,
"text": "Output:"
},
{
"code": null,
"e": 26299,
"s": 26270,
"text": "GFG\ngfg\nskeeG\nskeeGrofskeeG\n"
},
{
"code": null,
"e": 26310,
"s": 26299,
"text": "Example 2:"
},
{
"code": "# Julia program to illustrate # the use of String reverse() method # Getting the reverse of the specified stringprintln(reverse(\"123\"))println(reverse(\"5\"))println(reverse(\"@#\"))println(reverse(\"^&*\"))",
"e": 26513,
"s": 26310,
"text": null
},
{
"code": null,
"e": 26521,
"s": 26513,
"text": "Output:"
},
{
"code": null,
"e": 26535,
"s": 26521,
"text": "321\n5\n#@\n*&^\n"
},
{
"code": null,
"e": 26541,
"s": 26535,
"text": "Julia"
},
{
"code": null,
"e": 26639,
"s": 26541,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26656,
"s": 26639,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 26716,
"s": 26656,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 26789,
"s": 26716,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 26823,
"s": 26789,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 26854,
"s": 26823,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 26915,
"s": 26854,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 26980,
"s": 26915,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 27011,
"s": 26980,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 27031,
"s": 27011,
"text": "while loop in Julia"
}
]
|
Minimize number of cuts required to break N length stick into N unit length sticks - GeeksforGeeks | 31 Mar, 2021
Given an integer N denoting the length of a given stick, the task is to minimize the time required to split the stick into pieces of unit length, given that, a single cut is possible for any portion of stick at any instance of time.
Examples:
Input: N = 100 Output: 7 Explanation: (100 units) —> (2 portions of 50 units) —> (4 portions of 25 units) —> (4 portions of 12 units, 4 portions of 13 units) —> (12 portions of 6 units, 4 portions of 7 units) —> (28 portions of 3 units, 4 portions of 4 units) —> (28 portions of 1 unit, 36 portions of 2 units) —> (100 portions of 1 unit)
Input: N = 65 Output: 7 Explanation: (65 units) —> (1 portion of 32 units, 1 portion of 33 units) —> (3 portions of 16 units, 1 portion of 17 units) —> (7 portions of 8 units, 1 portions of 9 units) —> (15 portions of 4 units, 1 portion of 5 units) —> (31 portions of 2 units, 1 portions of 3 units) —> (63 portions of 1 unit, 1 portion of 2 units) —> (65 portions of 1 unit)
Approach: Since we can cut any portion of the stick once at a particular instance of time, we need to maximize the portions after every cut. So, we will cut the stick into two parts of the longest possible length with the first cut. In the next instance, further cut both the obtained parts into two longest parts each in the next cut. Repeat this until N unit pieces are obtained.
Illustration: N = 100 1st Cut: (50) + (50) 2nd Cut: (25) + (25) + (25) + (25) 3rd Cut: (12) + (13) + (12) + (13) + (12) + (13) + (12) + (13) 4th Cut: (6) + (6) + (6) + (7) + (6) + (6) + (6) + (7) + (6) + (6) + (6) + (7) + (6) + (6) + (6) + (7) 5th Cut: (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) + (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) + (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) + (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) 6th Cut: 28 portions of 1 unit, 36 portions of 2 units 7th Cut: 100 portions of 1 unit
Hence, the minimum time required to split an N length stick into 1 unit pieces is ceil(log2N).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find minimum// time required to split a// stick of N length into// unit pieces #include <bits/stdc++.h>using namespace std; // Function to return the// minimum time required// to split stick of N into// length into unit piecesint min_time_to_cut(int N){ if (N == 0) return 0; // Return the minimum // unit of time required return ceil(log2(N));}// Driver Codeint main(){ int N = 100; cout << min_time_to_cut(N); return 0;}
// Java program to find minimum// time required to split a// stick of N length into// unit piecesimport java.lang.*; class GFG{ // Function to return the// minimum time required// to split stick of N into// length into unit piecesstatic int min_time_to_cut(int N){ if (N == 0) return 0; // Return the minimum // unit of time required return (int)Math.ceil(Math.log(N) / Math.log(2));} // Driver Codepublic static void main(String[] args){ int N = 100; System.out.print(min_time_to_cut(N));}} // This code is contributed by rock_cool
# Python3 program to find minimum# time required to split a stick# of N length into unit piecesimport math # Function to return the# minimum time required# to split stick of N into# length into unit piecesdef min_time_to_cut(N): if (N == 0): return 0 # Return the minimum # unit of time required return int(math.log2(N)) + 1 # Driver CodeN = 100 print(min_time_to_cut(N)) # This code is contributed by Vishal Maurya
// C# program to find minimum// time required to split a// stick of N length into// unit piecesusing System;class GFG{ // Function to return the// minimum time required// to split stick of N into// length into unit piecesstatic int min_time_to_cut(int N){ if (N == 0) return 0; // Return the minimum // unit of time required return (int)Math.Ceiling(Math.Log(N) / Math.Log(2));} // Driver Codepublic static void Main(){ int N = 100; Console.Write(min_time_to_cut(N));}} // This code is contributed by Code_Mech
<script> // Javascript program to find minimum// time required to split a stick of// N length into unit pieces // Function to return the// minimum time required// to split stick of N into// length into unit piecesfunction min_time_to_cut(N){ if (N == 0) return 0; // Return the minimum // unit of time required return Math.ceil(Math.log(N) / Math.log(2));} // Driver codelet N = 100; document.write(min_time_to_cut(N)); // This code is contributed by divyesh072019 </script>
7
Time Complexity: O (1) Auxiliary Space: O (1)
vishu2908
rock_cool
Code_Mech
divyesh072019
interview-preparation
Mathematical
Pattern Searching
Puzzles
Mathematical
Pattern Searching
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Operators in C / C++
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Naive algorithm for Pattern Searching
Boyer Moore Algorithm for Pattern Searching | [
{
"code": null,
"e": 26475,
"s": 26447,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 26708,
"s": 26475,
"text": "Given an integer N denoting the length of a given stick, the task is to minimize the time required to split the stick into pieces of unit length, given that, a single cut is possible for any portion of stick at any instance of time."
},
{
"code": null,
"e": 26720,
"s": 26708,
"text": "Examples: "
},
{
"code": null,
"e": 27059,
"s": 26720,
"text": "Input: N = 100 Output: 7 Explanation: (100 units) —> (2 portions of 50 units) —> (4 portions of 25 units) —> (4 portions of 12 units, 4 portions of 13 units) —> (12 portions of 6 units, 4 portions of 7 units) —> (28 portions of 3 units, 4 portions of 4 units) —> (28 portions of 1 unit, 36 portions of 2 units) —> (100 portions of 1 unit)"
},
{
"code": null,
"e": 27438,
"s": 27059,
"text": "Input: N = 65 Output: 7 Explanation: (65 units) —> (1 portion of 32 units, 1 portion of 33 units) —> (3 portions of 16 units, 1 portion of 17 units) —> (7 portions of 8 units, 1 portions of 9 units) —> (15 portions of 4 units, 1 portion of 5 units) —> (31 portions of 2 units, 1 portions of 3 units) —> (63 portions of 1 unit, 1 portion of 2 units) —> (65 portions of 1 unit) "
},
{
"code": null,
"e": 27821,
"s": 27438,
"text": "Approach: Since we can cut any portion of the stick once at a particular instance of time, we need to maximize the portions after every cut. So, we will cut the stick into two parts of the longest possible length with the first cut. In the next instance, further cut both the obtained parts into two longest parts each in the next cut. Repeat this until N unit pieces are obtained. "
},
{
"code": null,
"e": 28353,
"s": 27821,
"text": "Illustration: N = 100 1st Cut: (50) + (50) 2nd Cut: (25) + (25) + (25) + (25) 3rd Cut: (12) + (13) + (12) + (13) + (12) + (13) + (12) + (13) 4th Cut: (6) + (6) + (6) + (7) + (6) + (6) + (6) + (7) + (6) + (6) + (6) + (7) + (6) + (6) + (6) + (7) 5th Cut: (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) + (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) + (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) + (3) + (3) + (3) + (3) + (3) + (3) + (3) + (4) 6th Cut: 28 portions of 1 unit, 36 portions of 2 units 7th Cut: 100 portions of 1 unit "
},
{
"code": null,
"e": 28448,
"s": 28353,
"text": "Hence, the minimum time required to split an N length stick into 1 unit pieces is ceil(log2N)."
},
{
"code": null,
"e": 28501,
"s": 28448,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28505,
"s": 28501,
"text": "C++"
},
{
"code": null,
"e": 28510,
"s": 28505,
"text": "Java"
},
{
"code": null,
"e": 28518,
"s": 28510,
"text": "Python3"
},
{
"code": null,
"e": 28521,
"s": 28518,
"text": "C#"
},
{
"code": null,
"e": 28532,
"s": 28521,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum// time required to split a// stick of N length into// unit pieces #include <bits/stdc++.h>using namespace std; // Function to return the// minimum time required// to split stick of N into// length into unit piecesint min_time_to_cut(int N){ if (N == 0) return 0; // Return the minimum // unit of time required return ceil(log2(N));}// Driver Codeint main(){ int N = 100; cout << min_time_to_cut(N); return 0;}",
"e": 29001,
"s": 28532,
"text": null
},
{
"code": "// Java program to find minimum// time required to split a// stick of N length into// unit piecesimport java.lang.*; class GFG{ // Function to return the// minimum time required// to split stick of N into// length into unit piecesstatic int min_time_to_cut(int N){ if (N == 0) return 0; // Return the minimum // unit of time required return (int)Math.ceil(Math.log(N) / Math.log(2));} // Driver Codepublic static void main(String[] args){ int N = 100; System.out.print(min_time_to_cut(N));}} // This code is contributed by rock_cool",
"e": 29597,
"s": 29001,
"text": null
},
{
"code": "# Python3 program to find minimum# time required to split a stick# of N length into unit piecesimport math # Function to return the# minimum time required# to split stick of N into# length into unit piecesdef min_time_to_cut(N): if (N == 0): return 0 # Return the minimum # unit of time required return int(math.log2(N)) + 1 # Driver CodeN = 100 print(min_time_to_cut(N)) # This code is contributed by Vishal Maurya",
"e": 30046,
"s": 29597,
"text": null
},
{
"code": "// C# program to find minimum// time required to split a// stick of N length into// unit piecesusing System;class GFG{ // Function to return the// minimum time required// to split stick of N into// length into unit piecesstatic int min_time_to_cut(int N){ if (N == 0) return 0; // Return the minimum // unit of time required return (int)Math.Ceiling(Math.Log(N) / Math.Log(2));} // Driver Codepublic static void Main(){ int N = 100; Console.Write(min_time_to_cut(N));}} // This code is contributed by Code_Mech",
"e": 30623,
"s": 30046,
"text": null
},
{
"code": "<script> // Javascript program to find minimum// time required to split a stick of// N length into unit pieces // Function to return the// minimum time required// to split stick of N into// length into unit piecesfunction min_time_to_cut(N){ if (N == 0) return 0; // Return the minimum // unit of time required return Math.ceil(Math.log(N) / Math.log(2));} // Driver codelet N = 100; document.write(min_time_to_cut(N)); // This code is contributed by divyesh072019 </script>",
"e": 31146,
"s": 30623,
"text": null
},
{
"code": null,
"e": 31148,
"s": 31146,
"text": "7"
},
{
"code": null,
"e": 31197,
"s": 31150,
"text": "Time Complexity: O (1) Auxiliary Space: O (1) "
},
{
"code": null,
"e": 31207,
"s": 31197,
"text": "vishu2908"
},
{
"code": null,
"e": 31217,
"s": 31207,
"text": "rock_cool"
},
{
"code": null,
"e": 31227,
"s": 31217,
"text": "Code_Mech"
},
{
"code": null,
"e": 31241,
"s": 31227,
"text": "divyesh072019"
},
{
"code": null,
"e": 31263,
"s": 31241,
"text": "interview-preparation"
},
{
"code": null,
"e": 31276,
"s": 31263,
"text": "Mathematical"
},
{
"code": null,
"e": 31294,
"s": 31276,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31302,
"s": 31294,
"text": "Puzzles"
},
{
"code": null,
"e": 31315,
"s": 31302,
"text": "Mathematical"
},
{
"code": null,
"e": 31333,
"s": 31315,
"text": "Pattern Searching"
},
{
"code": null,
"e": 31341,
"s": 31333,
"text": "Puzzles"
},
{
"code": null,
"e": 31439,
"s": 31341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31482,
"s": 31439,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31516,
"s": 31482,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 31589,
"s": 31516,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 31632,
"s": 31589,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 31653,
"s": 31632,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 31689,
"s": 31653,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31732,
"s": 31689,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31774,
"s": 31732,
"text": "Check if a string is substring of another"
},
{
"code": null,
"e": 31812,
"s": 31774,
"text": "Naive algorithm for Pattern Searching"
}
]
|
\hfil - Tex Command | \hfil - Used to set horizontal alignment in matrices and arrays.
{ \hfil }
\hfil command is used to set horizontal alignment in matrices and arrays.
\begin{matrix}
xxxxxx & xxxxxx & xxxxxx \cr
ab & \hfil ab & ab\hfil\cr
\end{matrix}
xxxxxxxxxxxxxxxxxxababab
\begin{matrix}
xxxxxx & xxxxxx & xxxxxx \cr
ab & \hfil ab & ab\hfil\cr
\end{matrix}
xxxxxxxxxxxxxxxxxxababab
\begin{matrix}
xxxxxx & xxxxxx & xxxxxx \cr
ab & \hfil ab & ab\hfil\cr
\end{matrix}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8051,
"s": 7986,
"text": "\\hfil - Used to set horizontal alignment in matrices and arrays."
},
{
"code": null,
"e": 8061,
"s": 8051,
"text": "{ \\hfil }"
},
{
"code": null,
"e": 8135,
"s": 8061,
"text": "\\hfil command is used to set horizontal alignment in matrices and arrays."
},
{
"code": null,
"e": 8249,
"s": 8135,
"text": "\n\\begin{matrix}\nxxxxxx & xxxxxx & xxxxxx \\cr\nab & \\hfil ab & ab\\hfil\\cr\n\\end{matrix}\n\nxxxxxxxxxxxxxxxxxxababab\n\n\n"
},
{
"code": null,
"e": 8361,
"s": 8249,
"text": "\\begin{matrix}\nxxxxxx & xxxxxx & xxxxxx \\cr\nab & \\hfil ab & ab\\hfil\\cr\n\\end{matrix}\n\nxxxxxxxxxxxxxxxxxxababab\n\n"
},
{
"code": null,
"e": 8445,
"s": 8361,
"text": "\\begin{matrix}\nxxxxxx & xxxxxx & xxxxxx \\cr\nab & \\hfil ab & ab\\hfil\\cr\n\\end{matrix}"
},
{
"code": null,
"e": 8477,
"s": 8445,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8490,
"s": 8477,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8523,
"s": 8490,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8536,
"s": 8523,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8568,
"s": 8536,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8604,
"s": 8568,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8639,
"s": 8604,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8656,
"s": 8639,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8689,
"s": 8656,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8703,
"s": 8689,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8735,
"s": 8703,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8750,
"s": 8735,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8757,
"s": 8750,
"text": " Print"
},
{
"code": null,
"e": 8768,
"s": 8757,
"text": " Add Notes"
}
]
|
Create new functionality with __getattribute__ | by Alexander Bailey | Towards Data Science | As a child of a class, it’s hard to take back control from your parent. You might think that once your parent has given you some functionality, that’s it and there’s nothing you can do to change it but that’s not that case!
We’re going to consider an example where we want to use the functionality given to us by a parent but we want to do something before or after a parent method is called. This is going to be particularly useful if you're inheriting from a class defined in a module that isn’t yours.
To understand how to achieve this, we need an understanding of how Python calls a class method.
Consider the following class:
class Person: def set_name(self,name): self.name = nameclass Worker(Person): def set_occupation(self,job): self.occupation = jobxander = Worker()
So xander is an instance of Worker. When we run xander.set_name("Xander"), two things happen.
The class calls __getattribute__ on set_nameThen __call__ is called on xander.set_name with the argument "Xander"
The class calls __getattribute__ on set_name
Then __call__ is called on xander.set_name with the argument "Xander"
We want to change the behaviour of a function in the parent class but we don’t have access to it (maybe because it’s owned by a different module).
We don’t have any control over __call__ because the function is owned by the parent. However, we do have control over our own __getattribute__ so let’s modify that instead.
So to add new functionality we want to take the original method, add new functionality before or after and wrap that in a new function. Then, we interrupt the normal behaviour of __getattribute__ and inject our new wrapper instead.
Let’s look at a basic example, we want to add print statements before and after a function’s run.
def print_wrapper(func): def new_func(*args,**kwargs): print(f"Running: {func.__name__}") out = func(*args,**kwargs) print(f"Finished: {func.__name__}") return out return new_func
For more exciting examples and to understand decorators more generally, I wrote about them here:
towardsdatascience.com
Now we need to write our new __getattribute__ function:
def __getattribute__(self, attr): attribute = super(Parent, self).__getattribute__(attr) if callable(attribute): return print_wrapper(attribute) else: return attribute
Checking if the attribute is callable is checking that the attribute being selected can be called with arguments and hence it makes sense to apply the wrapper. If the attribute is just a property, not a method, the behaviour will be unchanged.
So all together for our basic example above that’s going to look something like:
class Person: def set_name(self,name): self._name = namedef print_wrapper(func): def new_func(*args,**kwargs): print(f"Running: {func.__name__}") out = func(*args,**kwargs) print(f"Finished: {func.__name__}") return out return new_funcclass Worker(Person): def __getattribute__(self, attr): attribute = Person.__getattribute__(self,attr) if callable(attribute): return print_wrapper(attribute) else: return attribute def set_occupation(self,job): self._job = job
And when we try and use it we get:
>>> xander = Worker()>>> xander.set_name("Xander")Running: set_nameFinished: set_name>>> xander.set_occupation("Butcher")Running: set_occupationFinished: set_occupation>>> print(xander.__dict__){'_name': 'Xander', '_job': 'Butcher'}
A few words of working with these types of functions, messing with the __getattribute__ should be done with care, it gets called for every attribute so adding compute-heavy functionality is going slow down your program quite considerably. Messing around with functions like __getattribute__ can also very easily lead to recursion errors and kernel panics because the class keeps calling itself again and again.
One example of this recursion happens if you use __getattribute__ to call __dict__ because __dict__ itself calls __getattribute__ and so the loop continues...
Having command over the double underscore methods of Python objects can allow you do save a lot of time and effort. The alternative way to achieve the same thing would have involved re-implementing each function along with decorators. Maybe that wouldn’t be too bad for this example above but imagine trying to do it if your parent class was something like a Pandas data frame or a NumPy array... Then it becomes a significantly more daunting task. | [
{
"code": null,
"e": 396,
"s": 172,
"text": "As a child of a class, it’s hard to take back control from your parent. You might think that once your parent has given you some functionality, that’s it and there’s nothing you can do to change it but that’s not that case!"
},
{
"code": null,
"e": 677,
"s": 396,
"text": "We’re going to consider an example where we want to use the functionality given to us by a parent but we want to do something before or after a parent method is called. This is going to be particularly useful if you're inheriting from a class defined in a module that isn’t yours."
},
{
"code": null,
"e": 773,
"s": 677,
"text": "To understand how to achieve this, we need an understanding of how Python calls a class method."
},
{
"code": null,
"e": 803,
"s": 773,
"text": "Consider the following class:"
},
{
"code": null,
"e": 969,
"s": 803,
"text": "class Person: def set_name(self,name): self.name = nameclass Worker(Person): def set_occupation(self,job): self.occupation = jobxander = Worker()"
},
{
"code": null,
"e": 1063,
"s": 969,
"text": "So xander is an instance of Worker. When we run xander.set_name(\"Xander\"), two things happen."
},
{
"code": null,
"e": 1177,
"s": 1063,
"text": "The class calls __getattribute__ on set_nameThen __call__ is called on xander.set_name with the argument \"Xander\""
},
{
"code": null,
"e": 1222,
"s": 1177,
"text": "The class calls __getattribute__ on set_name"
},
{
"code": null,
"e": 1292,
"s": 1222,
"text": "Then __call__ is called on xander.set_name with the argument \"Xander\""
},
{
"code": null,
"e": 1439,
"s": 1292,
"text": "We want to change the behaviour of a function in the parent class but we don’t have access to it (maybe because it’s owned by a different module)."
},
{
"code": null,
"e": 1612,
"s": 1439,
"text": "We don’t have any control over __call__ because the function is owned by the parent. However, we do have control over our own __getattribute__ so let’s modify that instead."
},
{
"code": null,
"e": 1844,
"s": 1612,
"text": "So to add new functionality we want to take the original method, add new functionality before or after and wrap that in a new function. Then, we interrupt the normal behaviour of __getattribute__ and inject our new wrapper instead."
},
{
"code": null,
"e": 1942,
"s": 1844,
"text": "Let’s look at a basic example, we want to add print statements before and after a function’s run."
},
{
"code": null,
"e": 2156,
"s": 1942,
"text": "def print_wrapper(func): def new_func(*args,**kwargs): print(f\"Running: {func.__name__}\") out = func(*args,**kwargs) print(f\"Finished: {func.__name__}\") return out return new_func"
},
{
"code": null,
"e": 2253,
"s": 2156,
"text": "For more exciting examples and to understand decorators more generally, I wrote about them here:"
},
{
"code": null,
"e": 2276,
"s": 2253,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2332,
"s": 2276,
"text": "Now we need to write our new __getattribute__ function:"
},
{
"code": null,
"e": 2523,
"s": 2332,
"text": "def __getattribute__(self, attr): attribute = super(Parent, self).__getattribute__(attr) if callable(attribute): return print_wrapper(attribute) else: return attribute"
},
{
"code": null,
"e": 2767,
"s": 2523,
"text": "Checking if the attribute is callable is checking that the attribute being selected can be called with arguments and hence it makes sense to apply the wrapper. If the attribute is just a property, not a method, the behaviour will be unchanged."
},
{
"code": null,
"e": 2848,
"s": 2767,
"text": "So all together for our basic example above that’s going to look something like:"
},
{
"code": null,
"e": 3419,
"s": 2848,
"text": "class Person: def set_name(self,name): self._name = namedef print_wrapper(func): def new_func(*args,**kwargs): print(f\"Running: {func.__name__}\") out = func(*args,**kwargs) print(f\"Finished: {func.__name__}\") return out return new_funcclass Worker(Person): def __getattribute__(self, attr): attribute = Person.__getattribute__(self,attr) if callable(attribute): return print_wrapper(attribute) else: return attribute def set_occupation(self,job): self._job = job"
},
{
"code": null,
"e": 3454,
"s": 3419,
"text": "And when we try and use it we get:"
},
{
"code": null,
"e": 3687,
"s": 3454,
"text": ">>> xander = Worker()>>> xander.set_name(\"Xander\")Running: set_nameFinished: set_name>>> xander.set_occupation(\"Butcher\")Running: set_occupationFinished: set_occupation>>> print(xander.__dict__){'_name': 'Xander', '_job': 'Butcher'}"
},
{
"code": null,
"e": 4098,
"s": 3687,
"text": "A few words of working with these types of functions, messing with the __getattribute__ should be done with care, it gets called for every attribute so adding compute-heavy functionality is going slow down your program quite considerably. Messing around with functions like __getattribute__ can also very easily lead to recursion errors and kernel panics because the class keeps calling itself again and again."
},
{
"code": null,
"e": 4257,
"s": 4098,
"text": "One example of this recursion happens if you use __getattribute__ to call __dict__ because __dict__ itself calls __getattribute__ and so the loop continues..."
}
]
|
How to redirect website after certain amount of time without JavaScript? | To redirect from an HTML page, use the META Tag. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The value of the content is the number of seconds; you want the page to redirect after.
Through this, you can automatically redirect your visitors to a new homepage. Set the content attribute to 0, if you want it to load immediately.
The following is an example of redirecting current page to another page after 2 seconds.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Redirection</title>
<meta http-equiv = "refresh" content = "2; url = https://www.tutorialspoint.com" />
</head>
<body>
<p>This page will redirect in 2 seconds.</p>
</body>
</html> | [
{
"code": null,
"e": 1305,
"s": 1062,
"text": "To redirect from an HTML page, use the META Tag. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The value of the content is the number of seconds; you want the page to redirect after."
},
{
"code": null,
"e": 1451,
"s": 1305,
"text": "Through this, you can automatically redirect your visitors to a new homepage. Set the content attribute to 0, if you want it to load immediately."
},
{
"code": null,
"e": 1540,
"s": 1451,
"text": "The following is an example of redirecting current page to another page after 2 seconds."
},
{
"code": null,
"e": 1550,
"s": 1540,
"text": "Live Demo"
},
{
"code": null,
"e": 1797,
"s": 1550,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Redirection</title>\n <meta http-equiv = \"refresh\" content = \"2; url = https://www.tutorialspoint.com\" />\n </head>\n <body>\n <p>This page will redirect in 2 seconds.</p>\n </body>\n</html>"
}
]
|
wxPython - BoxSizer | This sizer allows the controls to be arranged in row-wise or column-wise manner. BoxSizer’s layout is determined by its orientation argument (either wxVERTICAL or wxHORIZONTAL).
Box = wx.BoxSizer(wxHORIZONTAL)
Box = wx.BoxSizer(wxVERTICAL)
Add() method (inherited from wxSizer) appends it to the next row/column of the sizer.
Box.Add(control, proportion, flag, border)
The proportion parameter controls how the control changes it size in response to dimensions of the container. Combination of various flag parameters decides the appearance of control in the sizer. Following are some of the flags −
wx.EXPAND
Item will expand to fill the space provided to it (wx.GROW is the same)
wx.SHAPED
Similar to EXPAND but maintains the item's aspect ratio
wx.FIXED_MINSIZE
Does not let the item become smaller than its initial minimum size
wx.RESERVE_SPACE_EVEN_IF_ HIDDEN
Does not allow the sizer to reclaim an item's space when it is hidden
The border parameter is an integer, the space in pixels to be left between controls. For example,
b = wx.StaticText(self, -1, “Enter a number”)
Box.Add(b,1,wx.ALL|wx.EXPAND,10)
Following are some more methods of wx.BoxSizer class −
SetOrientation()
Sets orientation wxHORIZONTAL or wxVERTICAL
AddSpacer()
Adds nonstretchable space
AddStretchSpacer()
Adds stretchable space so that resizing the window will affect control size proportionately
Clear()
Removes children from sizer
Detach()
Removes a control from sizer without destroying
Insert()
Inserts a child control at a specified position
Remove()
Removes a child from sizer and destroys it
In the following code, a vertical box sizer is applied to a panel object which is placed inside wxFrame window.
p = wx.Panel(self)
vbox = wx.wx.BoxSizer(wx.VERTICAL)
The first row in the box displays a label (wx.StaticText object) in the center with a border of 20 pixels around it.
l1 = wx.StaticText(p,label = "Enter a number",style = wx.ALIGN_CENTRE )
vbox.Add(l1,0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 20)
In the second row, a wx.Button object is displayed. Because of wx.EXPAND flag it occupies the entire width of the window.
b1 = wx.Button(p, label = "Btn1")
vbox.Add(b1,0, wx.EXPAND)
The next row also contains a button. It is not added with EXPAND flag. Instead, because of ALIGN_CENTER_HORIZONTAL, button with default size appears in the center horizontally.
b2 = wx.Button(p, label = "Btn2")
vbox.Add(b2,0,wx.ALIGN_CENTER_HORIZONTAL)
In the next row, a TextCtrl object with proportion parameter set to 1 and EXPAND flag set is added. As a result, it is taller in size.
t = wx.TextCtrl(p)
vbox.Add(t,1,wx.EXPAND,10)
The last row holds a horizontal sizer object, which in turn has a label and button separated by a stretchable space.
hbox = wx.BoxSizer(wx.HORIZONTAL)
l2 = wx.StaticText(p,label = "Label2", style = wx.ALIGN_CENTRE)
hbox.Add(l2,0,wx.EXPAND)
b3 = wx.Button(p,label = "Btn3")
hbox.AddStretchSpacer(1)
hbox.Add(b3,0,wx.ALIGN_LEFT,20)
vbox.Add(hbox,1,wx.ALL|wx.EXPAND)
Lastly, the vertical box sizer is applied to wx.Panel object.
Following is the complete code −
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title = title, size = (200,300))
self.InitUI()
self.Centre()
self.Show()
def InitUI(self):
p = wx.Panel(self)
vbox = wx.wx.BoxSizer(wx.VERTICAL)
l1 = wx.StaticText(p,label = "Enter a number",style = wx.ALIGN_CENTRE )
vbox.Add(l1,0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 20)
b1 = wx.Button(p, label = "Btn1")
vbox.Add(b1,0,wx.EXPAND)
b2 = wx.Button(p, label = "Btn2")
vbox.Add(b2,0,wx.ALIGN_CENTER_HORIZONTAL)
t = wx.TextCtrl(p)
vbox.Add(t,1,wx.EXPAND,10)
hbox = wx.BoxSizer(wx.HORIZONTAL)
l2 = wx.StaticText(p,label = "Label2", style = wx.ALIGN_CENTRE)
hbox.Add(l2,0,wx.EXPAND)
b3 = wx.Button(p,label = "Btn3")
hbox.AddStretchSpacer(1)
hbox.Add(b3,0,wx.ALIGN_LEFT,20)
vbox.Add(hbox,1,wx.ALL|wx.EXPAND)
p.SetSizer(vbox)
app = wx.App()
Example(None, title = 'BoxSizer demo')
app.MainLoop()
The above code produces the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2060,
"s": 1882,
"text": "This sizer allows the controls to be arranged in row-wise or column-wise manner. BoxSizer’s layout is determined by its orientation argument (either wxVERTICAL or wxHORIZONTAL)."
},
{
"code": null,
"e": 2123,
"s": 2060,
"text": "Box = wx.BoxSizer(wxHORIZONTAL)\nBox = wx.BoxSizer(wxVERTICAL)\n"
},
{
"code": null,
"e": 2209,
"s": 2123,
"text": "Add() method (inherited from wxSizer) appends it to the next row/column of the sizer."
},
{
"code": null,
"e": 2253,
"s": 2209,
"text": "Box.Add(control, proportion, flag, border)\n"
},
{
"code": null,
"e": 2484,
"s": 2253,
"text": "The proportion parameter controls how the control changes it size in response to dimensions of the container. Combination of various flag parameters decides the appearance of control in the sizer. Following are some of the flags −"
},
{
"code": null,
"e": 2494,
"s": 2484,
"text": "wx.EXPAND"
},
{
"code": null,
"e": 2566,
"s": 2494,
"text": "Item will expand to fill the space provided to it (wx.GROW is the same)"
},
{
"code": null,
"e": 2576,
"s": 2566,
"text": "wx.SHAPED"
},
{
"code": null,
"e": 2632,
"s": 2576,
"text": "Similar to EXPAND but maintains the item's aspect ratio"
},
{
"code": null,
"e": 2649,
"s": 2632,
"text": "wx.FIXED_MINSIZE"
},
{
"code": null,
"e": 2716,
"s": 2649,
"text": "Does not let the item become smaller than its initial minimum size"
},
{
"code": null,
"e": 2749,
"s": 2716,
"text": "wx.RESERVE_SPACE_EVEN_IF_ HIDDEN"
},
{
"code": null,
"e": 2819,
"s": 2749,
"text": "Does not allow the sizer to reclaim an item's space when it is hidden"
},
{
"code": null,
"e": 2917,
"s": 2819,
"text": "The border parameter is an integer, the space in pixels to be left between controls. For example,"
},
{
"code": null,
"e": 2998,
"s": 2917,
"text": "b = wx.StaticText(self, -1, “Enter a number”) \nBox.Add(b,1,wx.ALL|wx.EXPAND,10) "
},
{
"code": null,
"e": 3053,
"s": 2998,
"text": "Following are some more methods of wx.BoxSizer class −"
},
{
"code": null,
"e": 3070,
"s": 3053,
"text": "SetOrientation()"
},
{
"code": null,
"e": 3114,
"s": 3070,
"text": "Sets orientation wxHORIZONTAL or wxVERTICAL"
},
{
"code": null,
"e": 3126,
"s": 3114,
"text": "AddSpacer()"
},
{
"code": null,
"e": 3152,
"s": 3126,
"text": "Adds nonstretchable space"
},
{
"code": null,
"e": 3171,
"s": 3152,
"text": "AddStretchSpacer()"
},
{
"code": null,
"e": 3263,
"s": 3171,
"text": "Adds stretchable space so that resizing the window will affect control size proportionately"
},
{
"code": null,
"e": 3271,
"s": 3263,
"text": "Clear()"
},
{
"code": null,
"e": 3299,
"s": 3271,
"text": "Removes children from sizer"
},
{
"code": null,
"e": 3308,
"s": 3299,
"text": "Detach()"
},
{
"code": null,
"e": 3356,
"s": 3308,
"text": "Removes a control from sizer without destroying"
},
{
"code": null,
"e": 3365,
"s": 3356,
"text": "Insert()"
},
{
"code": null,
"e": 3413,
"s": 3365,
"text": "Inserts a child control at a specified position"
},
{
"code": null,
"e": 3422,
"s": 3413,
"text": "Remove()"
},
{
"code": null,
"e": 3465,
"s": 3422,
"text": "Removes a child from sizer and destroys it"
},
{
"code": null,
"e": 3577,
"s": 3465,
"text": "In the following code, a vertical box sizer is applied to a panel object which is placed inside wxFrame window."
},
{
"code": null,
"e": 3633,
"s": 3577,
"text": "p = wx.Panel(self) \nvbox = wx.wx.BoxSizer(wx.VERTICAL)\n"
},
{
"code": null,
"e": 3750,
"s": 3633,
"text": "The first row in the box displays a label (wx.StaticText object) in the center with a border of 20 pixels around it."
},
{
"code": null,
"e": 3889,
"s": 3750,
"text": "l1 = wx.StaticText(p,label = \"Enter a number\",style = wx.ALIGN_CENTRE ) \nvbox.Add(l1,0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 20)\n"
},
{
"code": null,
"e": 4011,
"s": 3889,
"text": "In the second row, a wx.Button object is displayed. Because of wx.EXPAND flag it occupies the entire width of the window."
},
{
"code": null,
"e": 4073,
"s": 4011,
"text": "b1 = wx.Button(p, label = \"Btn1\") \nvbox.Add(b1,0, wx.EXPAND)\n"
},
{
"code": null,
"e": 4250,
"s": 4073,
"text": "The next row also contains a button. It is not added with EXPAND flag. Instead, because of ALIGN_CENTER_HORIZONTAL, button with default size appears in the center horizontally."
},
{
"code": null,
"e": 4328,
"s": 4250,
"text": "b2 = wx.Button(p, label = \"Btn2\") \nvbox.Add(b2,0,wx.ALIGN_CENTER_HORIZONTAL)\n"
},
{
"code": null,
"e": 4463,
"s": 4328,
"text": "In the next row, a TextCtrl object with proportion parameter set to 1 and EXPAND flag set is added. As a result, it is taller in size."
},
{
"code": null,
"e": 4511,
"s": 4463,
"text": "t = wx.TextCtrl(p) \nvbox.Add(t,1,wx.EXPAND,10)\n"
},
{
"code": null,
"e": 4628,
"s": 4511,
"text": "The last row holds a horizontal sizer object, which in turn has a label and button separated by a stretchable space."
},
{
"code": null,
"e": 4882,
"s": 4628,
"text": "hbox = wx.BoxSizer(wx.HORIZONTAL) \nl2 = wx.StaticText(p,label = \"Label2\", style = wx.ALIGN_CENTRE) \nhbox.Add(l2,0,wx.EXPAND) \n\nb3 = wx.Button(p,label = \"Btn3\") \nhbox.AddStretchSpacer(1) \nhbox.Add(b3,0,wx.ALIGN_LEFT,20) \nvbox.Add(hbox,1,wx.ALL|wx.EXPAND)"
},
{
"code": null,
"e": 4944,
"s": 4882,
"text": "Lastly, the vertical box sizer is applied to wx.Panel object."
},
{
"code": null,
"e": 4977,
"s": 4944,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 6094,
"s": 4977,
"text": "import wx \n \nclass Example(wx.Frame): \n \n def __init__(self, parent, title): \n super(Example, self).__init__(parent, title = title, size = (200,300)) \n \n self.InitUI() \n self.Centre() \n self.Show()\n\t\t\n def InitUI(self): \n p = wx.Panel(self) \n vbox = wx.wx.BoxSizer(wx.VERTICAL) \n l1 = wx.StaticText(p,label = \"Enter a number\",style = wx.ALIGN_CENTRE ) \n vbox.Add(l1,0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 20) \n b1 = wx.Button(p, label = \"Btn1\") \n vbox.Add(b1,0,wx.EXPAND) \n \n b2 = wx.Button(p, label = \"Btn2\") \n vbox.Add(b2,0,wx.ALIGN_CENTER_HORIZONTAL) \n t = wx.TextCtrl(p) \n vbox.Add(t,1,wx.EXPAND,10) \n hbox = wx.BoxSizer(wx.HORIZONTAL) \n l2 = wx.StaticText(p,label = \"Label2\", style = wx.ALIGN_CENTRE) \n\t\t\n hbox.Add(l2,0,wx.EXPAND) \n b3 = wx.Button(p,label = \"Btn3\") \n hbox.AddStretchSpacer(1) \n hbox.Add(b3,0,wx.ALIGN_LEFT,20) \n vbox.Add(hbox,1,wx.ALL|wx.EXPAND) \n p.SetSizer(vbox) \n \napp = wx.App() \nExample(None, title = 'BoxSizer demo') \napp.MainLoop()"
},
{
"code": null,
"e": 6141,
"s": 6094,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 6148,
"s": 6141,
"text": " Print"
},
{
"code": null,
"e": 6159,
"s": 6148,
"text": " Add Notes"
}
]
|
numpy.linalg.solve() | The numpy.linalg.solve() function gives the solution of linear equations in the matrix form.
Considering the following linear equations −
x + y + z = 6
2y + 5z = -4
2x + 5y - z = 27
They can be represented in the matrix form as −
If these three matrices are called A, X and B, the equation becomes −
A*X = B
Or
X = A-1B
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2336,
"s": 2243,
"text": "The numpy.linalg.solve() function gives the solution of linear equations in the matrix form."
},
{
"code": null,
"e": 2381,
"s": 2336,
"text": "Considering the following linear equations −"
},
{
"code": null,
"e": 2395,
"s": 2381,
"text": "x + y + z = 6"
},
{
"code": null,
"e": 2408,
"s": 2395,
"text": "2y + 5z = -4"
},
{
"code": null,
"e": 2425,
"s": 2408,
"text": "2x + 5y - z = 27"
},
{
"code": null,
"e": 2473,
"s": 2425,
"text": "They can be represented in the matrix form as −"
},
{
"code": null,
"e": 2543,
"s": 2473,
"text": "If these three matrices are called A, X and B, the equation becomes −"
},
{
"code": null,
"e": 2569,
"s": 2543,
"text": "A*X = B \n\nOr\n\nX = A-1B \n"
},
{
"code": null,
"e": 2602,
"s": 2569,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2619,
"s": 2602,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 2652,
"s": 2619,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2687,
"s": 2652,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 2720,
"s": 2687,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2755,
"s": 2720,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 2790,
"s": 2755,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2802,
"s": 2790,
"text": " Akbar Khan"
},
{
"code": null,
"e": 2835,
"s": 2802,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2850,
"s": 2835,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 2883,
"s": 2850,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2890,
"s": 2883,
"text": " Anmol"
},
{
"code": null,
"e": 2897,
"s": 2890,
"text": " Print"
},
{
"code": null,
"e": 2908,
"s": 2897,
"text": " Add Notes"
}
]
|
Compile our own Android Kernel in 5 Simple Steps - GeeksforGeeks | 23 Feb, 2021
The Android kernel helps the applications to communicate with the hardware components of the device.
For example:
Most of us are familiar with game mode. What it does is instructs the processor and the graphics processing unit to run at their maximum frequencies.Another example is power saver mode. It instructs the processor and the graphics processing unit to run at their minimum frequencies.
Most of us are familiar with game mode. What it does is instructs the processor and the graphics processing unit to run at their maximum frequencies.
Another example is power saver mode. It instructs the processor and the graphics processing unit to run at their minimum frequencies.
Need to compile our own kernel: Compiling our own kernel might prove very useful as:
The user experience can be further optimized as per the need using our own kernel
It can also help in Open Source Development.
Steps to compile our own kernel:
Prerequisites: Below are the prerequisites required to compile our own Android Kernel:Ubuntu or any other Linux based OSFamiliar with basic Linux CommandsFamiliar with GithubDevice source codeNote: This article is for a device with a 64bit Snapdragon SOCInstall Dependencies Open the terminal and paste the following:sudo apt-get install git ccache automake flex lzop bison \ gperf build-essential zip curl zlib1g-dev zlib1g-dev:i386 \ g++-multilib python-networkx libxml2-utils bzip2 libbz2-dev \ libbz2-1.0 libghc-bzlib-dev squashfs-tools pngcrush \ schedtool dpkg-dev liblz4-tool make optipng maven libssl-dev \ pwgen libswitch-perl policycoreutils minicom libxml-sax-base-perl \ libxml-simple-perl bc libc6-dev-i386 lib32ncurses5-dev \ x11proto-core-dev libx11-dev lib32z-dev libgl1-mesa-dev xsltproc unzipDownload Required Files:Clone the device source on local disk:mkdir mykernel git clone {link to your device kernel source}Download a compatible GCC toolchain. In this article, AOSP’s GCC is used.cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchainDownload a compatible CLANG toolchain. In this article, AOSP’s CLANG is used.Move the downloaded file in the mykernel folder and then extract using the following command:tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gzCompiling The Kernel:cd mykernelrm -rf outmkdir outexport ARCH=arm64export SUBARCH=arm64export DTC_EXT=dtc make O=out ARCH=arm64 {device defconfig} PATH="${PWD}/bin:${PWD}/toolchain/bin:${PATH}" \make -j$(nproc --all) O=out \ ARCH=arm64 \ CC=clang \ CLANG_TRIPLE=aarch64-linux-gnu- \ CROSS_COMPILE=aarch64-linux-android- | tee kernel.logHere, replace the {device defconfig} with the name of your config file. You can find it in /arch/arm64/configs folder.Booting The Compiled Kernel:Browse to /out/arch/arm64/boot and find the Image-dtb file (compiled zImage) and copy the file.Download Android Image Kitchen and decompile your stock boot image. Once you decompile it you’ll find the stock zImage in the decompiled folder. Replace it with the one you copied earlier and recompile the boot image.Flash via fastboot using the following command:fastboot flash boot mykernel.imgDealing with the encountered errors: A kernel.log file will be generated in mykernel folder. Find the line which says error and search for the solution. Also please don’t forget to attach the log file when posting in forums for help.
Prerequisites: Below are the prerequisites required to compile our own Android Kernel:Ubuntu or any other Linux based OSFamiliar with basic Linux CommandsFamiliar with GithubDevice source codeNote: This article is for a device with a 64bit Snapdragon SOC
Ubuntu or any other Linux based OS
Familiar with basic Linux Commands
Familiar with Github
Device source code
Note: This article is for a device with a 64bit Snapdragon SOC
Install Dependencies Open the terminal and paste the following:sudo apt-get install git ccache automake flex lzop bison \ gperf build-essential zip curl zlib1g-dev zlib1g-dev:i386 \ g++-multilib python-networkx libxml2-utils bzip2 libbz2-dev \ libbz2-1.0 libghc-bzlib-dev squashfs-tools pngcrush \ schedtool dpkg-dev liblz4-tool make optipng maven libssl-dev \ pwgen libswitch-perl policycoreutils minicom libxml-sax-base-perl \ libxml-simple-perl bc libc6-dev-i386 lib32ncurses5-dev \ x11proto-core-dev libx11-dev lib32z-dev libgl1-mesa-dev xsltproc unzip
sudo apt-get install git ccache automake flex lzop bison \ gperf build-essential zip curl zlib1g-dev zlib1g-dev:i386 \ g++-multilib python-networkx libxml2-utils bzip2 libbz2-dev \ libbz2-1.0 libghc-bzlib-dev squashfs-tools pngcrush \ schedtool dpkg-dev liblz4-tool make optipng maven libssl-dev \ pwgen libswitch-perl policycoreutils minicom libxml-sax-base-perl \ libxml-simple-perl bc libc6-dev-i386 lib32ncurses5-dev \ x11proto-core-dev libx11-dev lib32z-dev libgl1-mesa-dev xsltproc unzip
Download Required Files:Clone the device source on local disk:mkdir mykernel git clone {link to your device kernel source}Download a compatible GCC toolchain. In this article, AOSP’s GCC is used.cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchainDownload a compatible CLANG toolchain. In this article, AOSP’s CLANG is used.Move the downloaded file in the mykernel folder and then extract using the following command:tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gz
Clone the device source on local disk:mkdir mykernel git clone {link to your device kernel source}
mkdir mykernel git clone {link to your device kernel source}
Download a compatible GCC toolchain. In this article, AOSP’s GCC is used.cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchain
cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchain
Download a compatible CLANG toolchain. In this article, AOSP’s CLANG is used.
Move the downloaded file in the mykernel folder and then extract using the following command:tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gz
tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gz
Compiling The Kernel:cd mykernelrm -rf outmkdir outexport ARCH=arm64export SUBARCH=arm64export DTC_EXT=dtc make O=out ARCH=arm64 {device defconfig} PATH="${PWD}/bin:${PWD}/toolchain/bin:${PATH}" \make -j$(nproc --all) O=out \ ARCH=arm64 \ CC=clang \ CLANG_TRIPLE=aarch64-linux-gnu- \ CROSS_COMPILE=aarch64-linux-android- | tee kernel.logHere, replace the {device defconfig} with the name of your config file. You can find it in /arch/arm64/configs folder.
cd mykernelrm -rf outmkdir outexport ARCH=arm64export SUBARCH=arm64export DTC_EXT=dtc make O=out ARCH=arm64 {device defconfig} PATH="${PWD}/bin:${PWD}/toolchain/bin:${PATH}" \make -j$(nproc --all) O=out \ ARCH=arm64 \ CC=clang \ CLANG_TRIPLE=aarch64-linux-gnu- \ CROSS_COMPILE=aarch64-linux-android- | tee kernel.log
Here, replace the {device defconfig} with the name of your config file. You can find it in /arch/arm64/configs folder.
Booting The Compiled Kernel:Browse to /out/arch/arm64/boot and find the Image-dtb file (compiled zImage) and copy the file.Download Android Image Kitchen and decompile your stock boot image. Once you decompile it you’ll find the stock zImage in the decompiled folder. Replace it with the one you copied earlier and recompile the boot image.Flash via fastboot using the following command:fastboot flash boot mykernel.img
Browse to /out/arch/arm64/boot and find the Image-dtb file (compiled zImage) and copy the file.
Download Android Image Kitchen and decompile your stock boot image. Once you decompile it you’ll find the stock zImage in the decompiled folder. Replace it with the one you copied earlier and recompile the boot image.
Flash via fastboot using the following command:fastboot flash boot mykernel.img
fastboot flash boot mykernel.img
Dealing with the encountered errors: A kernel.log file will be generated in mykernel folder. Find the line which says error and search for the solution. Also please don’t forget to attach the log file when posting in forums for help.
This will be the basic kernel, and more features can be added once it boots successfully.
Android-Misc
Technical Scripter 2019
Android
Java
Linux-Unix
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
Retrofit with Kotlin Coroutine in Android
How to Read Data from SQLite Database in Android?
How to Change the Background Color After Clicking the Button in Android?
Android Listview in Java with Example
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": 25140,
"s": 25112,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 25241,
"s": 25140,
"text": "The Android kernel helps the applications to communicate with the hardware components of the device."
},
{
"code": null,
"e": 25254,
"s": 25241,
"text": "For example:"
},
{
"code": null,
"e": 25537,
"s": 25254,
"text": "Most of us are familiar with game mode. What it does is instructs the processor and the graphics processing unit to run at their maximum frequencies.Another example is power saver mode. It instructs the processor and the graphics processing unit to run at their minimum frequencies."
},
{
"code": null,
"e": 25687,
"s": 25537,
"text": "Most of us are familiar with game mode. What it does is instructs the processor and the graphics processing unit to run at their maximum frequencies."
},
{
"code": null,
"e": 25821,
"s": 25687,
"text": "Another example is power saver mode. It instructs the processor and the graphics processing unit to run at their minimum frequencies."
},
{
"code": null,
"e": 25906,
"s": 25821,
"text": "Need to compile our own kernel: Compiling our own kernel might prove very useful as:"
},
{
"code": null,
"e": 25988,
"s": 25906,
"text": "The user experience can be further optimized as per the need using our own kernel"
},
{
"code": null,
"e": 26033,
"s": 25988,
"text": "It can also help in Open Source Development."
},
{
"code": null,
"e": 26066,
"s": 26033,
"text": "Steps to compile our own kernel:"
},
{
"code": null,
"e": 28768,
"s": 26066,
"text": "Prerequisites: Below are the prerequisites required to compile our own Android Kernel:Ubuntu or any other Linux based OSFamiliar with basic Linux CommandsFamiliar with GithubDevice source codeNote: This article is for a device with a 64bit Snapdragon SOCInstall Dependencies Open the terminal and paste the following:sudo apt-get install git ccache automake flex lzop bison \\ gperf build-essential zip curl zlib1g-dev zlib1g-dev:i386 \\ g++-multilib python-networkx libxml2-utils bzip2 libbz2-dev \\ libbz2-1.0 libghc-bzlib-dev squashfs-tools pngcrush \\ schedtool dpkg-dev liblz4-tool make optipng maven libssl-dev \\ pwgen libswitch-perl policycoreutils minicom libxml-sax-base-perl \\ libxml-simple-perl bc libc6-dev-i386 lib32ncurses5-dev \\ x11proto-core-dev libx11-dev lib32z-dev libgl1-mesa-dev xsltproc unzipDownload Required Files:Clone the device source on local disk:mkdir mykernel git clone {link to your device kernel source}Download a compatible GCC toolchain. In this article, AOSP’s GCC is used.cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchainDownload a compatible CLANG toolchain. In this article, AOSP’s CLANG is used.Move the downloaded file in the mykernel folder and then extract using the following command:tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gzCompiling The Kernel:cd mykernelrm -rf outmkdir outexport ARCH=arm64export SUBARCH=arm64export DTC_EXT=dtc make O=out ARCH=arm64 {device defconfig} PATH=\"${PWD}/bin:${PWD}/toolchain/bin:${PATH}\" \\make -j$(nproc --all) O=out \\ ARCH=arm64 \\ CC=clang \\ CLANG_TRIPLE=aarch64-linux-gnu- \\ CROSS_COMPILE=aarch64-linux-android- | tee kernel.logHere, replace the {device defconfig} with the name of your config file. You can find it in /arch/arm64/configs folder.Booting The Compiled Kernel:Browse to /out/arch/arm64/boot and find the Image-dtb file (compiled zImage) and copy the file.Download Android Image Kitchen and decompile your stock boot image. Once you decompile it you’ll find the stock zImage in the decompiled folder. Replace it with the one you copied earlier and recompile the boot image.Flash via fastboot using the following command:fastboot flash boot mykernel.imgDealing with the encountered errors: A kernel.log file will be generated in mykernel folder. Find the line which says error and search for the solution. Also please don’t forget to attach the log file when posting in forums for help."
},
{
"code": null,
"e": 29023,
"s": 28768,
"text": "Prerequisites: Below are the prerequisites required to compile our own Android Kernel:Ubuntu or any other Linux based OSFamiliar with basic Linux CommandsFamiliar with GithubDevice source codeNote: This article is for a device with a 64bit Snapdragon SOC"
},
{
"code": null,
"e": 29058,
"s": 29023,
"text": "Ubuntu or any other Linux based OS"
},
{
"code": null,
"e": 29093,
"s": 29058,
"text": "Familiar with basic Linux Commands"
},
{
"code": null,
"e": 29114,
"s": 29093,
"text": "Familiar with Github"
},
{
"code": null,
"e": 29133,
"s": 29114,
"text": "Device source code"
},
{
"code": null,
"e": 29196,
"s": 29133,
"text": "Note: This article is for a device with a 64bit Snapdragon SOC"
},
{
"code": null,
"e": 29846,
"s": 29196,
"text": "Install Dependencies Open the terminal and paste the following:sudo apt-get install git ccache automake flex lzop bison \\ gperf build-essential zip curl zlib1g-dev zlib1g-dev:i386 \\ g++-multilib python-networkx libxml2-utils bzip2 libbz2-dev \\ libbz2-1.0 libghc-bzlib-dev squashfs-tools pngcrush \\ schedtool dpkg-dev liblz4-tool make optipng maven libssl-dev \\ pwgen libswitch-perl policycoreutils minicom libxml-sax-base-perl \\ libxml-simple-perl bc libc6-dev-i386 lib32ncurses5-dev \\ x11proto-core-dev libx11-dev lib32z-dev libgl1-mesa-dev xsltproc unzip"
},
{
"code": "sudo apt-get install git ccache automake flex lzop bison \\ gperf build-essential zip curl zlib1g-dev zlib1g-dev:i386 \\ g++-multilib python-networkx libxml2-utils bzip2 libbz2-dev \\ libbz2-1.0 libghc-bzlib-dev squashfs-tools pngcrush \\ schedtool dpkg-dev liblz4-tool make optipng maven libssl-dev \\ pwgen libswitch-perl policycoreutils minicom libxml-sax-base-perl \\ libxml-simple-perl bc libc6-dev-i386 lib32ncurses5-dev \\ x11proto-core-dev libx11-dev lib32z-dev libgl1-mesa-dev xsltproc unzip",
"e": 30433,
"s": 29846,
"text": null
},
{
"code": null,
"e": 31018,
"s": 30433,
"text": "Download Required Files:Clone the device source on local disk:mkdir mykernel git clone {link to your device kernel source}Download a compatible GCC toolchain. In this article, AOSP’s GCC is used.cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchainDownload a compatible CLANG toolchain. In this article, AOSP’s CLANG is used.Move the downloaded file in the mykernel folder and then extract using the following command:tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gz"
},
{
"code": null,
"e": 31118,
"s": 31018,
"text": "Clone the device source on local disk:mkdir mykernel git clone {link to your device kernel source}"
},
{
"code": "mkdir mykernel git clone {link to your device kernel source}",
"e": 31180,
"s": 31118,
"text": null
},
{
"code": null,
"e": 31415,
"s": 31180,
"text": "Download a compatible GCC toolchain. In this article, AOSP’s GCC is used.cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchain"
},
{
"code": "cd mykernel git clone https://android.googlesource.com/platform/ prebuilts/gcc/linux-x86/aarch64/ aarch64-linux-android-4.9 toolchain",
"e": 31577,
"s": 31415,
"text": null
},
{
"code": null,
"e": 31655,
"s": 31577,
"text": "Download a compatible CLANG toolchain. In this article, AOSP’s CLANG is used."
},
{
"code": null,
"e": 31806,
"s": 31655,
"text": "Move the downloaded file in the mykernel folder and then extract using the following command:tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gz"
},
{
"code": "tar vxzf linux-x86-android-9.0.0_r48-clang-4691093.tar.gz",
"e": 31864,
"s": 31806,
"text": null
},
{
"code": null,
"e": 32427,
"s": 31864,
"text": "Compiling The Kernel:cd mykernelrm -rf outmkdir outexport ARCH=arm64export SUBARCH=arm64export DTC_EXT=dtc make O=out ARCH=arm64 {device defconfig} PATH=\"${PWD}/bin:${PWD}/toolchain/bin:${PATH}\" \\make -j$(nproc --all) O=out \\ ARCH=arm64 \\ CC=clang \\ CLANG_TRIPLE=aarch64-linux-gnu- \\ CROSS_COMPILE=aarch64-linux-android- | tee kernel.logHere, replace the {device defconfig} with the name of your config file. You can find it in /arch/arm64/configs folder."
},
{
"code": "cd mykernelrm -rf outmkdir outexport ARCH=arm64export SUBARCH=arm64export DTC_EXT=dtc make O=out ARCH=arm64 {device defconfig} PATH=\"${PWD}/bin:${PWD}/toolchain/bin:${PATH}\" \\make -j$(nproc --all) O=out \\ ARCH=arm64 \\ CC=clang \\ CLANG_TRIPLE=aarch64-linux-gnu- \\ CROSS_COMPILE=aarch64-linux-android- | tee kernel.log",
"e": 32851,
"s": 32427,
"text": null
},
{
"code": null,
"e": 32970,
"s": 32851,
"text": "Here, replace the {device defconfig} with the name of your config file. You can find it in /arch/arm64/configs folder."
},
{
"code": null,
"e": 33390,
"s": 32970,
"text": "Booting The Compiled Kernel:Browse to /out/arch/arm64/boot and find the Image-dtb file (compiled zImage) and copy the file.Download Android Image Kitchen and decompile your stock boot image. Once you decompile it you’ll find the stock zImage in the decompiled folder. Replace it with the one you copied earlier and recompile the boot image.Flash via fastboot using the following command:fastboot flash boot mykernel.img"
},
{
"code": null,
"e": 33486,
"s": 33390,
"text": "Browse to /out/arch/arm64/boot and find the Image-dtb file (compiled zImage) and copy the file."
},
{
"code": null,
"e": 33704,
"s": 33486,
"text": "Download Android Image Kitchen and decompile your stock boot image. Once you decompile it you’ll find the stock zImage in the decompiled folder. Replace it with the one you copied earlier and recompile the boot image."
},
{
"code": null,
"e": 33784,
"s": 33704,
"text": "Flash via fastboot using the following command:fastboot flash boot mykernel.img"
},
{
"code": "fastboot flash boot mykernel.img",
"e": 33817,
"s": 33784,
"text": null
},
{
"code": null,
"e": 34051,
"s": 33817,
"text": "Dealing with the encountered errors: A kernel.log file will be generated in mykernel folder. Find the line which says error and search for the solution. Also please don’t forget to attach the log file when posting in forums for help."
},
{
"code": null,
"e": 34141,
"s": 34051,
"text": "This will be the basic kernel, and more features can be added once it boots successfully."
},
{
"code": null,
"e": 34154,
"s": 34141,
"text": "Android-Misc"
},
{
"code": null,
"e": 34178,
"s": 34154,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 34186,
"s": 34178,
"text": "Android"
},
{
"code": null,
"e": 34191,
"s": 34186,
"text": "Java"
},
{
"code": null,
"e": 34202,
"s": 34191,
"text": "Linux-Unix"
},
{
"code": null,
"e": 34221,
"s": 34202,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34226,
"s": 34221,
"text": "Java"
},
{
"code": null,
"e": 34234,
"s": 34226,
"text": "Android"
},
{
"code": null,
"e": 34332,
"s": 34234,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34371,
"s": 34332,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 34413,
"s": 34371,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 34463,
"s": 34413,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 34536,
"s": 34463,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 34574,
"s": 34536,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 34589,
"s": 34574,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34633,
"s": 34589,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34655,
"s": 34633,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34691,
"s": 34655,
"text": "Arrays.sort() in Java with examples"
}
]
|
Python - Create a Time Series Plot using Line Plot with Seaborn | To create a Time Series Plot, use the lineplot(). At first, import the required libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
Create a DataFrame with one of the columns as date i.e. “Date_of_Purchase” −
dataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 45, 70, 70, 87, 66]
})
Pot Time Series using lineplot() −
sb.lineplot(x="Date_of_Purchase", y="Units Sold", data=dataFrame)
Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
# creating DataFrame
dataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 45, 70, 70, 87, 66]
})
# time series plot
sb.lineplot(x="Date_of_Purchase", y="Units Sold", data=dataFrame)
plt.show()
This will produce the following output − | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To create a Time Series Plot, use the lineplot(). At first, import the required libraries −"
},
{
"code": null,
"e": 1227,
"s": 1154,
"text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1304,
"s": 1227,
"text": "Create a DataFrame with one of the columns as date i.e. “Date_of_Purchase” −"
},
{
"code": null,
"e": 1493,
"s": 1304,
"text": "dataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 45, 70, 70, 87, 66]\n})"
},
{
"code": null,
"e": 1528,
"s": 1493,
"text": "Pot Time Series using lineplot() −"
},
{
"code": null,
"e": 1595,
"s": 1528,
"text": "sb.lineplot(x=\"Date_of_Purchase\", y=\"Units Sold\", data=dataFrame)\n"
},
{
"code": null,
"e": 1619,
"s": 1595,
"text": "Following is the code −"
},
{
"code": null,
"e": 2000,
"s": 1619,
"text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# creating DataFrame\ndataFrame = pd.DataFrame({'Date_of_Purchase': ['2018-07-25', '2018-10-25', '2019-01-25', '2019-05-25', '2019-08-25','2020-09-25','2021-03-25'],'Units Sold': [98, 77, 45, 70, 70, 87, 66]\n})\n\n# time series plot\nsb.lineplot(x=\"Date_of_Purchase\", y=\"Units Sold\", data=dataFrame)\nplt.show()"
},
{
"code": null,
"e": 2041,
"s": 2000,
"text": "This will produce the following output −"
}
]
|
Dart - main() Function - GeeksforGeeks | 17 Feb, 2021
The main() function is a predefined method in Dart. It is the most important and mandatory part of any Dart Program. Any Dart script requires the main() method for its execution. This method acts as the entry point for any Dart application. It is responsible for executing all library functions, user-defined statements, and user-defined functions.
Syntax of main() function:
void main()
{
//main() function body
}
The main function can be further structured to variable declaration, function declaration, and executable statements. The main function returns void. Also, optional parameters List<String> may be used as arguments to the function. These arguments may be used in case we need to control our program from outside.
Example 1:
The following example is a basic example of how the main function is the entry point of a Dart program.
Dart
main(){ print("Main is the entry point!");}
Output:
Example 2:
The following example shows how we can pass arguments inside the main() function.
Dart
main(List<String> arguments){ //printing the arguments along with length print(arguments.length); print(arguments);}
We run the app using the following code(if main.dart is the name of the saved file):
dart main.dart Argument1 Argument2
Output:
Picked
Technical Scripter 2020
Dart
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
What is widgets in Flutter?
Android Studio Setup for Flutter Development
Flutter - BorderRadius Widget
Format Dates in Flutter
Flutter - Positioned Widget
Flutter - Dialogs | [
{
"code": null,
"e": 24010,
"s": 23982,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 24360,
"s": 24010,
"text": "The main() function is a predefined method in Dart. It is the most important and mandatory part of any Dart Program. Any Dart script requires the main() method for its execution. This method acts as the entry point for any Dart application. It is responsible for executing all library functions, user-defined statements, and user-defined functions. "
},
{
"code": null,
"e": 24387,
"s": 24360,
"text": "Syntax of main() function:"
},
{
"code": null,
"e": 24431,
"s": 24387,
"text": "void main()\n{\n //main() function body \n}"
},
{
"code": null,
"e": 24744,
"s": 24431,
"text": "The main function can be further structured to variable declaration, function declaration, and executable statements. The main function returns void. Also, optional parameters List<String> may be used as arguments to the function. These arguments may be used in case we need to control our program from outside. "
},
{
"code": null,
"e": 24755,
"s": 24744,
"text": "Example 1:"
},
{
"code": null,
"e": 24859,
"s": 24755,
"text": "The following example is a basic example of how the main function is the entry point of a Dart program."
},
{
"code": null,
"e": 24864,
"s": 24859,
"text": "Dart"
},
{
"code": "main(){ print(\"Main is the entry point!\");}",
"e": 24911,
"s": 24864,
"text": null
},
{
"code": null,
"e": 24919,
"s": 24911,
"text": "Output:"
},
{
"code": null,
"e": 24930,
"s": 24919,
"text": "Example 2:"
},
{
"code": null,
"e": 25012,
"s": 24930,
"text": "The following example shows how we can pass arguments inside the main() function."
},
{
"code": null,
"e": 25017,
"s": 25012,
"text": "Dart"
},
{
"code": "main(List<String> arguments){ //printing the arguments along with length print(arguments.length); print(arguments);}",
"e": 25146,
"s": 25017,
"text": null
},
{
"code": null,
"e": 25231,
"s": 25146,
"text": "We run the app using the following code(if main.dart is the name of the saved file):"
},
{
"code": null,
"e": 25267,
"s": 25231,
"text": " dart main.dart Argument1 Argument2"
},
{
"code": null,
"e": 25275,
"s": 25267,
"text": "Output:"
},
{
"code": null,
"e": 25282,
"s": 25275,
"text": "Picked"
},
{
"code": null,
"e": 25306,
"s": 25282,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 25311,
"s": 25306,
"text": "Dart"
},
{
"code": null,
"e": 25330,
"s": 25311,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25428,
"s": 25330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25467,
"s": 25428,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 25493,
"s": 25467,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 25519,
"s": 25493,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 25542,
"s": 25519,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 25570,
"s": 25542,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 25615,
"s": 25570,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 25645,
"s": 25615,
"text": "Flutter - BorderRadius Widget"
},
{
"code": null,
"e": 25669,
"s": 25645,
"text": "Format Dates in Flutter"
},
{
"code": null,
"e": 25697,
"s": 25669,
"text": "Flutter - Positioned Widget"
}
]
|
XStream - First Application | Before going into the details of the XStream library, let us see an application in action. In this example, we've created Student and Address classes. We will create a student object and then serialize it to an XML String. Then de-serialize the same XML string to obtain the student object back.
Create a java class file named XStreamTester in C:\>XStream_WORKSPACE.
File: XStreamTester.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class XStreamTester {
public static void main(String args[]) {
XStreamTester tester = new XStreamTester();
XStream xstream = new XStream(new StaxDriver());
Student student = tester.getStudentDetails();
//Object to XML Conversion
String xml = xstream.toXML(student);
System.out.println(formatXml(xml));
//XML to Object Conversion
Student student1 = (Student)xstream.fromXML(xml);
System.out.println(student1);
}
private Student getStudentDetails() {
Student student = new Student();
student.setFirstName("Mahesh");
student.setLastName("Parashar");
student.setRollNo(1);
student.setClassName("1st");
Address address = new Address();
address.setArea("H.No. 16/3, Preet Vihar.");
address.setCity("Delhi");
address.setState("Delhi");
address.setCountry("India");
address.setPincode(110012);
student.setAddress(address);
return student;
}
public static String formatXml(String xml) {
try {
Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Source xmlSource = new SAXSource(new InputSource(
new ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
} catch(Exception e) {
return xml;
}
}
}
class Student {
private int rollNo;
private String firstName;
private String lastName;
private String className;
private Address address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Student [ ");
stringBuilder.append("\nfirstName: ");
stringBuilder.append(firstName);
stringBuilder.append("\nlastName: ");
stringBuilder.append(lastName);
stringBuilder.append("\nrollNo: ");
stringBuilder.append(rollNo);
stringBuilder.append("\nclassName: ");
stringBuilder.append(className);
stringBuilder.append("\naddress: ");
stringBuilder.append(address);
stringBuilder.append(" ]");
return stringBuilder.toString();
}
}
class Address {
private String area;
private String city;
private String state;
private String country;
private int pincode;
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\nAddress [ ");
stringBuilder.append("\narea: ");
stringBuilder.append(area);
stringBuilder.append("\ncity: ");
stringBuilder.append(city);
stringBuilder.append("\nstate: ");
stringBuilder.append(state);
stringBuilder.append("\ncountry: ");
stringBuilder.append(country);
stringBuilder.append("\npincode: ");
stringBuilder.append(pincode);
stringBuilder.append(" ]");
return stringBuilder.toString();
}
}
Verify the Result
Compile the classes using javac compiler as follows −
C:\XStream_WORKSPACE>javac XStreamTester.java
Now run the XStreamTester to see the result −
C:\XStream_WORKSPACE>java XStreamTester
Verify the output as follows
<?xml version = "1.0" encoding = "UTF-8"?>
<Student>
<firstName>Mahesh</firstName>
<lastName>Parashar</lastName>
<rollNo>1</rollNo>
<className>1st</className>
<address>
<area>H.No. 16/3, Preet Vihar.</area>
<city>Delhi</city>
<state>Delhi</state>
<country>India</country>
<pincode>110012</pincode>
</address>
</Student>
Student [
firstName: Mahesh
lastName: Parashar
rollNo: 1
className: 1st
address:
Address [
area: H.No. 16/3, Preet Vihar.
city: Delhi
state: Delhi
country: India
pincode: 110012
]
]
Following are the important steps to be considered here.
Create an XStream object by passing it a StaxDriver. StaxDriver uses Stax pull parser (available from java 6) and is a fast xml parser.
XStream xstream = new XStream(new StaxDriver());
Use toXML() method to get the XML string representation of the object.
//Object to XML Conversion
String xml = xstream.toXML(student);
Use fromXML() method to get the object from the XML.
//XML to Object Conversion
Student student1 = (Student)xstream.fromXML(xml);
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2054,
"s": 1758,
"text": "Before going into the details of the XStream library, let us see an application in action. In this example, we've created Student and Address classes. We will create a student object and then serialize it to an XML String. Then de-serialize the same XML string to obtain the student object back."
},
{
"code": null,
"e": 2125,
"s": 2054,
"text": "Create a java class file named XStreamTester in C:\\>XStream_WORKSPACE."
},
{
"code": null,
"e": 2150,
"s": 2125,
"text": "File: XStreamTester.java"
},
{
"code": null,
"e": 7314,
"s": 2150,
"text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.sax.SAXSource;\nimport javax.xml.transform.sax.SAXTransformerFactory;\nimport javax.xml.transform.stream.StreamResult;\nimport org.xml.sax.InputSource;\n\nimport com.thoughtworks.xstream.XStream;\nimport com.thoughtworks.xstream.io.xml.StaxDriver;\n\npublic class XStreamTester {\n\n public static void main(String args[]) {\n XStreamTester tester = new XStreamTester();\n XStream xstream = new XStream(new StaxDriver());\n \n Student student = tester.getStudentDetails();\n \n //Object to XML Conversion\n String xml = xstream.toXML(student);\n System.out.println(formatXml(xml));\n \n //XML to Object Conversion\n Student student1 = (Student)xstream.fromXML(xml);\n System.out.println(student1);\n }\n \n private Student getStudentDetails() {\n \n Student student = new Student();\n student.setFirstName(\"Mahesh\");\n student.setLastName(\"Parashar\");\n student.setRollNo(1);\n student.setClassName(\"1st\");\n\n Address address = new Address();\n address.setArea(\"H.No. 16/3, Preet Vihar.\");\n address.setCity(\"Delhi\");\n address.setState(\"Delhi\");\n address.setCountry(\"India\");\n address.setPincode(110012);\n\n student.setAddress(address);\n return student;\n }\n \n public static String formatXml(String xml) {\n \n try {\n Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();\n \n serializer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n serializer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n \n Source xmlSource = new SAXSource(new InputSource(\n new ByteArrayInputStream(xml.getBytes())));\n StreamResult res = new StreamResult(new ByteArrayOutputStream()); \n \n serializer.transform(xmlSource, res);\n \n return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());\n \n } catch(Exception e) {\n return xml;\n }\n }\n}\n\nclass Student {\n private int rollNo;\n private String firstName;\n private String lastName;\n private String className;\n private Address address;\n\n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n \n public int getRollNo() {\n return rollNo;\n }\n \n public void setRollNo(int rollNo) {\n this.rollNo = rollNo;\n }\n \n public String getClassName() {\n return className;\n }\n \n public void setClassName(String className) {\n this.className = className;\n }\n \n public Address getAddress() {\n return address;\n }\n \n public void setAddress(Address address) {\n this.address = address;\n }\n \n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n \n stringBuilder.append(\"Student [ \");\n stringBuilder.append(\"\\nfirstName: \");\n stringBuilder.append(firstName);\n stringBuilder.append(\"\\nlastName: \");\n stringBuilder.append(lastName);\n stringBuilder.append(\"\\nrollNo: \");\n stringBuilder.append(rollNo);\n stringBuilder.append(\"\\nclassName: \");\n stringBuilder.append(className);\n stringBuilder.append(\"\\naddress: \");\n stringBuilder.append(address);\n stringBuilder.append(\" ]\");\n \n return stringBuilder.toString();\n }\n}\n\nclass Address {\n private String area;\n private String city;\n private String state;\n private String country;\n private int pincode;\n\n public String getArea() {\n return area;\n }\n\n public void setArea(String area) {\n this.area = area;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n\n public int getPincode() {\n return pincode;\n }\n\n public void setPincode(int pincode) {\n this.pincode = pincode;\n }\n\n public String toString() {\n\n StringBuilder stringBuilder = new StringBuilder();\n\n stringBuilder.append(\"\\nAddress [ \");\n stringBuilder.append(\"\\narea: \");\n stringBuilder.append(area);\n stringBuilder.append(\"\\ncity: \");\n stringBuilder.append(city);\n stringBuilder.append(\"\\nstate: \");\n stringBuilder.append(state);\n stringBuilder.append(\"\\ncountry: \");\n stringBuilder.append(country);\n stringBuilder.append(\"\\npincode: \");\t\n stringBuilder.append(pincode);\n stringBuilder.append(\" ]\");\n\n return stringBuilder.toString();\n }\n}"
},
{
"code": null,
"e": 7332,
"s": 7314,
"text": "Verify the Result"
},
{
"code": null,
"e": 7386,
"s": 7332,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 7433,
"s": 7386,
"text": "C:\\XStream_WORKSPACE>javac XStreamTester.java\n"
},
{
"code": null,
"e": 7479,
"s": 7433,
"text": "Now run the XStreamTester to see the result −"
},
{
"code": null,
"e": 7520,
"s": 7479,
"text": "C:\\XStream_WORKSPACE>java XStreamTester\n"
},
{
"code": null,
"e": 7549,
"s": 7520,
"text": "Verify the output as follows"
},
{
"code": null,
"e": 8156,
"s": 7549,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<Student>\n <firstName>Mahesh</firstName>\n <lastName>Parashar</lastName>\n <rollNo>1</rollNo>\n <className>1st</className>\n <address>\n <area>H.No. 16/3, Preet Vihar.</area>\n <city>Delhi</city>\n <state>Delhi</state>\n <country>India</country>\n <pincode>110012</pincode>\n </address>\n</Student>\n\nStudent [ \n firstName: Mahesh\n lastName: Parashar\n rollNo: 1\n className: 1st\n address: \n Address [ \n area: H.No. 16/3, Preet Vihar.\n city: Delhi\n state: Delhi\n country: India\n pincode: 110012\n ] \n]\n"
},
{
"code": null,
"e": 8213,
"s": 8156,
"text": "Following are the important steps to be considered here."
},
{
"code": null,
"e": 8349,
"s": 8213,
"text": "Create an XStream object by passing it a StaxDriver. StaxDriver uses Stax pull parser (available from java 6) and is a fast xml parser."
},
{
"code": null,
"e": 8398,
"s": 8349,
"text": "XStream xstream = new XStream(new StaxDriver());"
},
{
"code": null,
"e": 8469,
"s": 8398,
"text": "Use toXML() method to get the XML string representation of the object."
},
{
"code": null,
"e": 8533,
"s": 8469,
"text": "//Object to XML Conversion\nString xml = xstream.toXML(student);"
},
{
"code": null,
"e": 8586,
"s": 8533,
"text": "Use fromXML() method to get the object from the XML."
},
{
"code": null,
"e": 8665,
"s": 8586,
"text": "//XML to Object Conversion\t\t\nStudent student1 = (Student)xstream.fromXML(xml);"
},
{
"code": null,
"e": 8672,
"s": 8665,
"text": " Print"
},
{
"code": null,
"e": 8683,
"s": 8672,
"text": " Add Notes"
}
]
|
Bootstrap .tooltip("toggle") method | Use the tooltip(“toggle”) method in Bootstrap to togle the tooltip.
The tooltip generates on clicking the button shown below −
<button type="button" class="btn btn-info">
Toggle Tooltip
</button>
Toggle the tooltip on button click like the following code snippet −
$(".btn-info").click(function(){
$("[data-toggle='tooltip']").tooltip('toggle');
});
You can try to run the following code to implement the tooltip(“toggle”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Demo</h3>
<a href="#" data-toggle="tooltip" title="Tooltip is visible!">Tooltip will be visible here</a>
<div>
<button type="button" class="btn btn-primary">Show Tooltip</button>
<button type="button" class="btn btn-default">Hide Tooltip</button>
<button type="button" class="btn btn-info">Toggle Tooltip</button>
</div>
</div>
<script>
$(document).ready(function(){
$(".btn-primary").click(function(){
$("[data-toggle='tooltip']").tooltip('show');
});
$(".btn-default").click(function(){
$("[data-toggle='tooltip']").tooltip('hide');
});
$(".btn-info").click(function(){
$("[data-toggle='tooltip']").tooltip('toggle');
});
});
</script>
</body>
</html> | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Use the tooltip(“toggle”) method in Bootstrap to togle the tooltip."
},
{
"code": null,
"e": 1189,
"s": 1130,
"text": "The tooltip generates on clicking the button shown below −"
},
{
"code": null,
"e": 1260,
"s": 1189,
"text": "<button type=\"button\" class=\"btn btn-info\">\n Toggle Tooltip\n</button>"
},
{
"code": null,
"e": 1329,
"s": 1260,
"text": "Toggle the tooltip on button click like the following code snippet −"
},
{
"code": null,
"e": 1416,
"s": 1329,
"text": "$(\".btn-info\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('toggle');\n});"
},
{
"code": null,
"e": 1498,
"s": 1416,
"text": "You can try to run the following code to implement the tooltip(“toggle”) method −"
},
{
"code": null,
"e": 1508,
"s": 1498,
"text": "Live Demo"
},
{
"code": null,
"e": 2752,
"s": 1508,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h3>Demo</h3>\n <a href=\"#\" data-toggle=\"tooltip\" title=\"Tooltip is visible!\">Tooltip will be visible here</a>\n <div>\n <button type=\"button\" class=\"btn btn-primary\">Show Tooltip</button>\n <button type=\"button\" class=\"btn btn-default\">Hide Tooltip</button>\n <button type=\"button\" class=\"btn btn-info\">Toggle Tooltip</button>\n </div> \n </div>\n\n<script>\n $(document).ready(function(){\n $(\".btn-primary\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('show');\n });\n $(\".btn-default\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('hide');\n });\n $(\".btn-info\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('toggle');\n });\n});\n</script>\n\n</body>\n</html>"
}
]
|
Data Science over the Movies Dataset with Spark, Scala and some SQL. And some Python.(Part 1). | by Borja González | Towards Data Science | One day, a friend of mine who works as a SQL developer told me that she was interested on big data processing engines but she has not any experience on other programming languages apart from SQL. I wanted to demonstrate her that knowing SQL is a good starting point to learn big data because thanks to Spark it is possible to perform plane SQL queries on tables and also its code sintax is similar to SQL. I hope you enjoy this story.
To prove it I have performed some queries and descriptive statistics to extract insights from a fancy dataset, the movie lens dataset, which is available on https://grouplens.org/datasets/movielens/and contains lots of rates of different users over more almost 30000 movies. This report might be useful to learn how to make aggregations and perform basics spark queries. I am not an expert on Spark neither on Scala so the code might not be implemented on the most efficient way but I do not stop learning and I am very open to suggestions and comments.
One of the biggest problem we face when we want to learn big data and to use Spark with Scala on the Hadoop ecosystem is always installing and integrating all the tools from these frameworks. However, Databricks community edition will save us from that problem. It has literally, everything we need to use: Its own file system, and all the APIs installed (and working properly) that we are going to use ( Hive well integrated with Spark and Scala and the rest of Spark libraries such as MLlib or Graphx). In order not to make this article too long I will not cover those techologies but good documentation about can be found on their website: https://databricks.com/spark/about.
The main topic of this article is not Databricks usage but scala-Spark coding over the movies datset (statistics, queries, aggregations...) . Some queries will be shown with their equivalent in SQL. Databricks will also allow us to manage this huge dataset that might fit in the memory of our local machine. Spark will provide us an efficient way to process the data.
The first and necessary step will be to download the two long format datasets that are on the recommended for new research section. After that, we have to import them on the databricks file system and then load them into Hive tables. Now we can perform some basic queries on both datasets/tables, the one with information about the movies and the one with the rates on the movies. Describe and printSchema methods are always a good entry point:
val movies = table("movies")val ratings = sql("select userId, movieId, rating from ratingsB")ratings.describe().showmovies.printSchemaratings.printSchema
To improve our spark coding we can perform whatever query we can think of with learning purposes. Firstly, let us check the users that have rated the most and the least number of movies:
import org.apache.spark.sql.functions.countimport org.apache.spark.sql.functions.{desc,asc} ratings.groupBy("userId").agg(count("*").alias("number_cnt")).orderBy(desc("number_cnt")) ratings.groupBy("userId").agg(count("*").alias("number_cnt")).orderBy(asc("number_cnt"))
The equivalent SQL query (It is important to note that as long as we can we should write this queries with spark since it will give us the errors at compile time and not on running time as the pure sql queries, to avoid wasting time in the future specially on large processes):
sql("select userId, count(*) from ratingsB group by userId order by count(*) desc")
There are some users that have rated more than 5000 movies!! That is crazy!
That made me wonder how long they’ve spent watching movies considering an average time for the length of the movies of 100 minutes. This result is worth to be shown!! Some queries will be packed into functions to be used whenever we want/need them and even on different cells of the notebook or parts of the code:
ratings.groupBy("userId").agg(count("*").alias("number_cnt")).withColumn("years_Watching", round($"number_cnt" * 100/ 60 / 24 / 365,3)).orderBy(desc("years_Watching")).show(10)
As we can see, user number 123100 has spent more than 4.5 years watching movies and watched more than 20000 films. What a cinephile!! Regarding the code, it has some useful methods such as a proper gropuBy agregation with a count with the round function applied on the new field created with .withColumn (since we do not need that much decimals Spark displays). Now, we will join both dataframes to have all the information in just 1 df to toy around:
val df_full = ratings.join(movies, $"ratingsb.movieId" === $"movies.movieId").drop($"ratingsb.movieId")
Are you interested on knowing which movies have been rated with 3 or 5 stars by the cinephile? We can know that with this function that receives as input a scala Seq of integers, together with the number of stars we want to query and the number of the user we are asking for or. All the movies rated by that user will be displayed if the seq comes empty (this is checked with the scala .isEmpty method):
import org.apache.spark.sql.functions.{asc, desc}def movie_query (df: org.apache.spark.sql.DataFrame, stars: Seq[Double], user: Int ) : Unit = { if (stars.isEmpty) { println(s"All movies rated by user $user") df.filter(df("userId") ===user).orderBy(desc("rating")).show(20, false) } else stars.foreach(starsNum =>{ println(s"All movies rated by user $user with $starsNum stars:") df.filter(df("userId") === user).filter(df("rating") === starsNum).orderBy(asc("movieId")).show(7, false)})} movie_query(df_full, Seq((3.0, 4.5), 21)
Usually, we all got lots of movie recommendations from friends and family and we make a list out of those movies. Right after that, when I am hesitant about which movie should I watch first I always go to filmaffinity or imdb to check the best rated movies out of my list. It turns out that we can do something similar. To do so, we need to obtain the mean rating for the movies and retrieve them orderedBy their rate from best to worst. It is important to note that a good movie searcher might not recieve the exact name of the movie and that can be solved with the scala contains method:
import org.apache.spark.sql.functions._def movie_grade (df: org.apache.spark.sql.DataFrame, movie: String ) : Unit = df.filter((df("title").contains(movie))).groupBy("title").agg((round(avg($"rating"),3)).as("averageStars")).orderBy(desc("averageStars")).show(false)
We will test our function on two famous sagas:
movie_grade(df_full, "Wild Bunch")movie_grade(df_full, "Lord of the Rings")
Yay! We love Lord of the Rings! The lowest rated movie corresponds to the animated version which I have yet to see.
Aragorn with 2 hobbits on the Lord of the Rings animated movie.
I am sure that there also a lot of fans of Star Wars saga so let us get the score of all the movies with its similar SQL query:
sql("Select title, avg(rating) as averageRate from full_movies where title like '%Star Wars%' group by title order by averageRate desc").show(false)
As we can see, the old movies are the best rated but in my opinion the first 3 episodes are not that bad to get that low score below 3.5 stars. But that is just opinion!! We have also obtained some spin offs and parallel movies that also could be interesting for Star Wars freaks.
The next thing I have wondered is which are the most and the least rated movies. Since this is rather extense dataset, it contains lots of movies that have poor number of visualizations, some of them with less than 5 rates. Of course, if we want to make a consistent study we should neglect those movies. I am just going to pay attention at the movies that have more than 600 rates that represents a 1% of the total movies rates (a totally not mainstream movie). To do that, we will create a new dataframe with the total rates of each movie and their average grade. After that, we will filter the movies with more than 600 rates and display the by their average rate in an ascending and descending way to check the worst and the best movies.
val df_count = df_full.groupBy("title").agg(avg("rating").as("averageRating"), count("title").as("RatesCount")) df_count.withColumn("roundedAverageRating", round(df_count("averageRating"),2)).filter(df_count("RatesCount") > 600).orderBy(asc("averageRating")).drop("averageRating").show(20, false) df_count.withColumn("roundedAverageRating", round(df_count("averageRating"),2)).filter(df_count("RatesCount") > 600).orderBy(desc("averageRating")).drop("averageRating").show(20, false)
The lowest ranked movies with more than 600 rates.
As you can see, Glitter is the worst movie. I have searched for it on imbd and indeed it looks horrible:
And now it comes the good part, paying attention to the head of the list:
Which is again consequent to its rating on imdb:
This dataset is perfect to improve and understand how do recommender systems work. I am working on machine learing models for recommender systems using the spark machine learning library MLlib and they will be shown on next articles. I have just come up with a simple solution for it just performing a big query. It is a simple model that could work as a dummy solution. The solution is about retrieving the categories an user has watched the most and output the movies that are best rated from those categories that the user has not watched yet. That is a more complex query packed into the easy_recommender fuction that will receive the number of the user we want the recommendations for, the number or rates as a minimun threshold we are going to use for a movie (remember that from a statistical point of view is not a good practice to retrieve movies with just a bit of rates) and the number of movies we want to display. These are the steps we are going to follow:
Obtain the categories that user X has seen the most. To achieve this, we need to filter by that user, groubBy the genres, make a count and then order by that count. Once we have that, we will just select the genres column and map the column with map to then perform a collect operation and then convert it into a Scala list using: .map(r => r.getString(0)).collect.toList.After that, we will mark the movies that user X has watched with a new column “ToDelete” containing a simple string such as “DELETE” to be easily found once we perform the join. With this we will have the movies user X has seen well identified.We will make the join of that dataframe with the big dataframe. The movies we want to neglect are marked with “DELETE” (so we will filter out the ones that have that column empty with .filter(“ToDelete is null”)).To conclude, we will loop over the categories we want to filter with the foreach scala method now tht we have selected the movies that user X has not watched yed. Now we just have to groupBy title, get the average grade, filter once again to have more than Y rates by movie (remember, for statistical reasons) and order them in a descending way by their average rating.
Obtain the categories that user X has seen the most. To achieve this, we need to filter by that user, groubBy the genres, make a count and then order by that count. Once we have that, we will just select the genres column and map the column with map to then perform a collect operation and then convert it into a Scala list using: .map(r => r.getString(0)).collect.toList.
After that, we will mark the movies that user X has watched with a new column “ToDelete” containing a simple string such as “DELETE” to be easily found once we perform the join. With this we will have the movies user X has seen well identified.
We will make the join of that dataframe with the big dataframe. The movies we want to neglect are marked with “DELETE” (so we will filter out the ones that have that column empty with .filter(“ToDelete is null”)).
To conclude, we will loop over the categories we want to filter with the foreach scala method now tht we have selected the movies that user X has not watched yed. Now we just have to groupBy title, get the average grade, filter once again to have more than Y rates by movie (remember, for statistical reasons) and order them in a descending way by their average rating.
It has been a bit complex process and I am sure there are better ways to do it. Here you can see the code:
def easy_recommender(nUser: Int, nRates: Int, nMovies: Int) : Unit = { val mostSeenGenresList = df_full.filter(df_full("userId") === nUser).groupBy("genres").agg(count("*").alias("cuenta")).orderBy(desc("cuenta")).limit(3).select("genres").map(r => r.getString(0)).collect.toList println(s"List of genres user $nUser has seen the most : $mostSeenGenresList") val movies_watched_by_userX = df_full.filter($"userId" === nUser).withColumn("ToDelete", lit("DELETE")).select($"ToDelete", $"title".as("title2")) var df_filt = df_full.join(movies_watched_by_userX, $"title" === $"title2", "left_outer") df_filt = df_filt.filter("ToDelete is null").select($"title", $"rating", $"genres") mostSeenGenresList.foreach(e => { println(s"Top $nMovies movies user number $nUser has not seen from category $e with more than $nRates rates: ") df_filt.filter($"genres" === e).groupBy("title").agg(avg("rating").as("avgByRating"), count("*").alias("nRates")).filter($"nRates" > nRates).orderBy(desc("avgByRating")).show(nMovies, false) })} easy_recommender(134596, 1000, 5)
The results we obtain from our “recommender system” are printed out with scala string interpolation:
You can see that firstly we print out the categories user X has seen the most. We can control the number of categories to be recommended with the .limit(3) method. As you can see we can control most of the parameters we want to include in our model with the inputs of the function.
To conclude, this is not a good Data Science work without its proper visualization/plot. To accomplish this, Python is always a good choice and together with it I am going to show you another wonderful feature of databricks that allows us to run Python and Scala code on the same notebook.
The first step will be saving our df_full with just the column that is important for our visualization into a temporary Hive table (which will only persists during the current session):
val ratesDF = df_full.select("rating").groupBy("rating").agg(count("rating").as("NumberOfRates")).orderBy(asc("rating")) ratesDF.createOrReplaceTempView("ratedDF")spark.sql("select * from ratedDF").show
And now it is the moment when the magic comes. Just by typing %python at the top of a cell we ca execute python code with all the Spark (pyspark) advantages ad features. We load the table into a pyspark dataframe and convert both columns into Python lists using these Python oneliners:
%pythondf = table("ratedDF")rating_list = df.select("rating").collect()number_rates = df.select("NumberOfRates").collect()rate_category = [float(row.rating) for row in rating_list]n_rates = [int(row.NumberOfRates) for row in number_rates]
And to conclude, we will make our visualization. This is a total freestyle process and some plots will be more prettier than others. Remember that a categorical variable should be represented with a barplot:
%pythonimport matplotlib.pyplot as pltimport numpy as npfig, ax = plt.subplots()ax.bar(rate_category, n_rates, align='center', width=0.4, facecolor='b', edgecolor='b', linewidth=3, alpha=.3)plt.title('Number of Rates vs Stars')plt.xlabel('Stars (*)')plt.xlim(0,5.5)plt.ylim(0,8000000)ax.set_xticks(rate_category)display(fig)
Not much to comment about it except that there are no movies rated with 0 stars and that this does not look as a normal distribution as one could expect.
And that’s all folks. I hope you have enjoyed this article as much as I have done it learning about scala, spark and Databricks and thinking about insights on the movies dataset. Now I am implementing and improving the perfomance of recommender systems on this dataset using the machine learning library from spark Spark MLlib. These models might be shown along with more complex queries and descriptive statistics over this dataset on future articles. I have played a bit with the genres column and obtained deeper statistics but I did not want this article to super dense.
Since this is my very first article, once again, any feedback and comments are well appreciated.
Originally published at https://medium.com on July 23, 2019. | [
{
"code": null,
"e": 607,
"s": 172,
"text": "One day, a friend of mine who works as a SQL developer told me that she was interested on big data processing engines but she has not any experience on other programming languages apart from SQL. I wanted to demonstrate her that knowing SQL is a good starting point to learn big data because thanks to Spark it is possible to perform plane SQL queries on tables and also its code sintax is similar to SQL. I hope you enjoy this story."
},
{
"code": null,
"e": 1161,
"s": 607,
"text": "To prove it I have performed some queries and descriptive statistics to extract insights from a fancy dataset, the movie lens dataset, which is available on https://grouplens.org/datasets/movielens/and contains lots of rates of different users over more almost 30000 movies. This report might be useful to learn how to make aggregations and perform basics spark queries. I am not an expert on Spark neither on Scala so the code might not be implemented on the most efficient way but I do not stop learning and I am very open to suggestions and comments."
},
{
"code": null,
"e": 1840,
"s": 1161,
"text": "One of the biggest problem we face when we want to learn big data and to use Spark with Scala on the Hadoop ecosystem is always installing and integrating all the tools from these frameworks. However, Databricks community edition will save us from that problem. It has literally, everything we need to use: Its own file system, and all the APIs installed (and working properly) that we are going to use ( Hive well integrated with Spark and Scala and the rest of Spark libraries such as MLlib or Graphx). In order not to make this article too long I will not cover those techologies but good documentation about can be found on their website: https://databricks.com/spark/about."
},
{
"code": null,
"e": 2208,
"s": 1840,
"text": "The main topic of this article is not Databricks usage but scala-Spark coding over the movies datset (statistics, queries, aggregations...) . Some queries will be shown with their equivalent in SQL. Databricks will also allow us to manage this huge dataset that might fit in the memory of our local machine. Spark will provide us an efficient way to process the data."
},
{
"code": null,
"e": 2653,
"s": 2208,
"text": "The first and necessary step will be to download the two long format datasets that are on the recommended for new research section. After that, we have to import them on the databricks file system and then load them into Hive tables. Now we can perform some basic queries on both datasets/tables, the one with information about the movies and the one with the rates on the movies. Describe and printSchema methods are always a good entry point:"
},
{
"code": null,
"e": 2807,
"s": 2653,
"text": "val movies = table(\"movies\")val ratings = sql(\"select userId, movieId, rating from ratingsB\")ratings.describe().showmovies.printSchemaratings.printSchema"
},
{
"code": null,
"e": 2994,
"s": 2807,
"text": "To improve our spark coding we can perform whatever query we can think of with learning purposes. Firstly, let us check the users that have rated the most and the least number of movies:"
},
{
"code": null,
"e": 3265,
"s": 2994,
"text": "import org.apache.spark.sql.functions.countimport org.apache.spark.sql.functions.{desc,asc} ratings.groupBy(\"userId\").agg(count(\"*\").alias(\"number_cnt\")).orderBy(desc(\"number_cnt\")) ratings.groupBy(\"userId\").agg(count(\"*\").alias(\"number_cnt\")).orderBy(asc(\"number_cnt\"))"
},
{
"code": null,
"e": 3543,
"s": 3265,
"text": "The equivalent SQL query (It is important to note that as long as we can we should write this queries with spark since it will give us the errors at compile time and not on running time as the pure sql queries, to avoid wasting time in the future specially on large processes):"
},
{
"code": null,
"e": 3627,
"s": 3543,
"text": "sql(\"select userId, count(*) from ratingsB group by userId order by count(*) desc\")"
},
{
"code": null,
"e": 3703,
"s": 3627,
"text": "There are some users that have rated more than 5000 movies!! That is crazy!"
},
{
"code": null,
"e": 4017,
"s": 3703,
"text": "That made me wonder how long they’ve spent watching movies considering an average time for the length of the movies of 100 minutes. This result is worth to be shown!! Some queries will be packed into functions to be used whenever we want/need them and even on different cells of the notebook or parts of the code:"
},
{
"code": null,
"e": 4194,
"s": 4017,
"text": "ratings.groupBy(\"userId\").agg(count(\"*\").alias(\"number_cnt\")).withColumn(\"years_Watching\", round($\"number_cnt\" * 100/ 60 / 24 / 365,3)).orderBy(desc(\"years_Watching\")).show(10)"
},
{
"code": null,
"e": 4646,
"s": 4194,
"text": "As we can see, user number 123100 has spent more than 4.5 years watching movies and watched more than 20000 films. What a cinephile!! Regarding the code, it has some useful methods such as a proper gropuBy agregation with a count with the round function applied on the new field created with .withColumn (since we do not need that much decimals Spark displays). Now, we will join both dataframes to have all the information in just 1 df to toy around:"
},
{
"code": null,
"e": 4750,
"s": 4646,
"text": "val df_full = ratings.join(movies, $\"ratingsb.movieId\" === $\"movies.movieId\").drop($\"ratingsb.movieId\")"
},
{
"code": null,
"e": 5154,
"s": 4750,
"text": "Are you interested on knowing which movies have been rated with 3 or 5 stars by the cinephile? We can know that with this function that receives as input a scala Seq of integers, together with the number of stars we want to query and the number of the user we are asking for or. All the movies rated by that user will be displayed if the seq comes empty (this is checked with the scala .isEmpty method):"
},
{
"code": null,
"e": 5686,
"s": 5154,
"text": "import org.apache.spark.sql.functions.{asc, desc}def movie_query (df: org.apache.spark.sql.DataFrame, stars: Seq[Double], user: Int ) : Unit = { if (stars.isEmpty) { println(s\"All movies rated by user $user\") df.filter(df(\"userId\") ===user).orderBy(desc(\"rating\")).show(20, false) } else stars.foreach(starsNum =>{ println(s\"All movies rated by user $user with $starsNum stars:\") df.filter(df(\"userId\") === user).filter(df(\"rating\") === starsNum).orderBy(asc(\"movieId\")).show(7, false)})} movie_query(df_full, Seq((3.0, 4.5), 21)"
},
{
"code": null,
"e": 6276,
"s": 5686,
"text": "Usually, we all got lots of movie recommendations from friends and family and we make a list out of those movies. Right after that, when I am hesitant about which movie should I watch first I always go to filmaffinity or imdb to check the best rated movies out of my list. It turns out that we can do something similar. To do so, we need to obtain the mean rating for the movies and retrieve them orderedBy their rate from best to worst. It is important to note that a good movie searcher might not recieve the exact name of the movie and that can be solved with the scala contains method:"
},
{
"code": null,
"e": 6543,
"s": 6276,
"text": "import org.apache.spark.sql.functions._def movie_grade (df: org.apache.spark.sql.DataFrame, movie: String ) : Unit = df.filter((df(\"title\").contains(movie))).groupBy(\"title\").agg((round(avg($\"rating\"),3)).as(\"averageStars\")).orderBy(desc(\"averageStars\")).show(false)"
},
{
"code": null,
"e": 6590,
"s": 6543,
"text": "We will test our function on two famous sagas:"
},
{
"code": null,
"e": 6666,
"s": 6590,
"text": "movie_grade(df_full, \"Wild Bunch\")movie_grade(df_full, \"Lord of the Rings\")"
},
{
"code": null,
"e": 6782,
"s": 6666,
"text": "Yay! We love Lord of the Rings! The lowest rated movie corresponds to the animated version which I have yet to see."
},
{
"code": null,
"e": 6846,
"s": 6782,
"text": "Aragorn with 2 hobbits on the Lord of the Rings animated movie."
},
{
"code": null,
"e": 6974,
"s": 6846,
"text": "I am sure that there also a lot of fans of Star Wars saga so let us get the score of all the movies with its similar SQL query:"
},
{
"code": null,
"e": 7123,
"s": 6974,
"text": "sql(\"Select title, avg(rating) as averageRate from full_movies where title like '%Star Wars%' group by title order by averageRate desc\").show(false)"
},
{
"code": null,
"e": 7404,
"s": 7123,
"text": "As we can see, the old movies are the best rated but in my opinion the first 3 episodes are not that bad to get that low score below 3.5 stars. But that is just opinion!! We have also obtained some spin offs and parallel movies that also could be interesting for Star Wars freaks."
},
{
"code": null,
"e": 8146,
"s": 7404,
"text": "The next thing I have wondered is which are the most and the least rated movies. Since this is rather extense dataset, it contains lots of movies that have poor number of visualizations, some of them with less than 5 rates. Of course, if we want to make a consistent study we should neglect those movies. I am just going to pay attention at the movies that have more than 600 rates that represents a 1% of the total movies rates (a totally not mainstream movie). To do that, we will create a new dataframe with the total rates of each movie and their average grade. After that, we will filter the movies with more than 600 rates and display the by their average rate in an ascending and descending way to check the worst and the best movies."
},
{
"code": null,
"e": 8629,
"s": 8146,
"text": "val df_count = df_full.groupBy(\"title\").agg(avg(\"rating\").as(\"averageRating\"), count(\"title\").as(\"RatesCount\")) df_count.withColumn(\"roundedAverageRating\", round(df_count(\"averageRating\"),2)).filter(df_count(\"RatesCount\") > 600).orderBy(asc(\"averageRating\")).drop(\"averageRating\").show(20, false) df_count.withColumn(\"roundedAverageRating\", round(df_count(\"averageRating\"),2)).filter(df_count(\"RatesCount\") > 600).orderBy(desc(\"averageRating\")).drop(\"averageRating\").show(20, false)"
},
{
"code": null,
"e": 8680,
"s": 8629,
"text": "The lowest ranked movies with more than 600 rates."
},
{
"code": null,
"e": 8785,
"s": 8680,
"text": "As you can see, Glitter is the worst movie. I have searched for it on imbd and indeed it looks horrible:"
},
{
"code": null,
"e": 8859,
"s": 8785,
"text": "And now it comes the good part, paying attention to the head of the list:"
},
{
"code": null,
"e": 8908,
"s": 8859,
"text": "Which is again consequent to its rating on imdb:"
},
{
"code": null,
"e": 9879,
"s": 8908,
"text": "This dataset is perfect to improve and understand how do recommender systems work. I am working on machine learing models for recommender systems using the spark machine learning library MLlib and they will be shown on next articles. I have just come up with a simple solution for it just performing a big query. It is a simple model that could work as a dummy solution. The solution is about retrieving the categories an user has watched the most and output the movies that are best rated from those categories that the user has not watched yet. That is a more complex query packed into the easy_recommender fuction that will receive the number of the user we want the recommendations for, the number or rates as a minimun threshold we are going to use for a movie (remember that from a statistical point of view is not a good practice to retrieve movies with just a bit of rates) and the number of movies we want to display. These are the steps we are going to follow:"
},
{
"code": null,
"e": 11078,
"s": 9879,
"text": "Obtain the categories that user X has seen the most. To achieve this, we need to filter by that user, groubBy the genres, make a count and then order by that count. Once we have that, we will just select the genres column and map the column with map to then perform a collect operation and then convert it into a Scala list using: .map(r => r.getString(0)).collect.toList.After that, we will mark the movies that user X has watched with a new column “ToDelete” containing a simple string such as “DELETE” to be easily found once we perform the join. With this we will have the movies user X has seen well identified.We will make the join of that dataframe with the big dataframe. The movies we want to neglect are marked with “DELETE” (so we will filter out the ones that have that column empty with .filter(“ToDelete is null”)).To conclude, we will loop over the categories we want to filter with the foreach scala method now tht we have selected the movies that user X has not watched yed. Now we just have to groupBy title, get the average grade, filter once again to have more than Y rates by movie (remember, for statistical reasons) and order them in a descending way by their average rating."
},
{
"code": null,
"e": 11451,
"s": 11078,
"text": "Obtain the categories that user X has seen the most. To achieve this, we need to filter by that user, groubBy the genres, make a count and then order by that count. Once we have that, we will just select the genres column and map the column with map to then perform a collect operation and then convert it into a Scala list using: .map(r => r.getString(0)).collect.toList."
},
{
"code": null,
"e": 11696,
"s": 11451,
"text": "After that, we will mark the movies that user X has watched with a new column “ToDelete” containing a simple string such as “DELETE” to be easily found once we perform the join. With this we will have the movies user X has seen well identified."
},
{
"code": null,
"e": 11910,
"s": 11696,
"text": "We will make the join of that dataframe with the big dataframe. The movies we want to neglect are marked with “DELETE” (so we will filter out the ones that have that column empty with .filter(“ToDelete is null”))."
},
{
"code": null,
"e": 12280,
"s": 11910,
"text": "To conclude, we will loop over the categories we want to filter with the foreach scala method now tht we have selected the movies that user X has not watched yed. Now we just have to groupBy title, get the average grade, filter once again to have more than Y rates by movie (remember, for statistical reasons) and order them in a descending way by their average rating."
},
{
"code": null,
"e": 12387,
"s": 12280,
"text": "It has been a bit complex process and I am sure there are better ways to do it. Here you can see the code:"
},
{
"code": null,
"e": 13444,
"s": 12387,
"text": "def easy_recommender(nUser: Int, nRates: Int, nMovies: Int) : Unit = { val mostSeenGenresList = df_full.filter(df_full(\"userId\") === nUser).groupBy(\"genres\").agg(count(\"*\").alias(\"cuenta\")).orderBy(desc(\"cuenta\")).limit(3).select(\"genres\").map(r => r.getString(0)).collect.toList println(s\"List of genres user $nUser has seen the most : $mostSeenGenresList\") val movies_watched_by_userX = df_full.filter($\"userId\" === nUser).withColumn(\"ToDelete\", lit(\"DELETE\")).select($\"ToDelete\", $\"title\".as(\"title2\")) var df_filt = df_full.join(movies_watched_by_userX, $\"title\" === $\"title2\", \"left_outer\") df_filt = df_filt.filter(\"ToDelete is null\").select($\"title\", $\"rating\", $\"genres\") mostSeenGenresList.foreach(e => { println(s\"Top $nMovies movies user number $nUser has not seen from category $e with more than $nRates rates: \") df_filt.filter($\"genres\" === e).groupBy(\"title\").agg(avg(\"rating\").as(\"avgByRating\"), count(\"*\").alias(\"nRates\")).filter($\"nRates\" > nRates).orderBy(desc(\"avgByRating\")).show(nMovies, false) })} easy_recommender(134596, 1000, 5)"
},
{
"code": null,
"e": 13545,
"s": 13444,
"text": "The results we obtain from our “recommender system” are printed out with scala string interpolation:"
},
{
"code": null,
"e": 13827,
"s": 13545,
"text": "You can see that firstly we print out the categories user X has seen the most. We can control the number of categories to be recommended with the .limit(3) method. As you can see we can control most of the parameters we want to include in our model with the inputs of the function."
},
{
"code": null,
"e": 14117,
"s": 13827,
"text": "To conclude, this is not a good Data Science work without its proper visualization/plot. To accomplish this, Python is always a good choice and together with it I am going to show you another wonderful feature of databricks that allows us to run Python and Scala code on the same notebook."
},
{
"code": null,
"e": 14303,
"s": 14117,
"text": "The first step will be saving our df_full with just the column that is important for our visualization into a temporary Hive table (which will only persists during the current session):"
},
{
"code": null,
"e": 14506,
"s": 14303,
"text": "val ratesDF = df_full.select(\"rating\").groupBy(\"rating\").agg(count(\"rating\").as(\"NumberOfRates\")).orderBy(asc(\"rating\")) ratesDF.createOrReplaceTempView(\"ratedDF\")spark.sql(\"select * from ratedDF\").show"
},
{
"code": null,
"e": 14792,
"s": 14506,
"text": "And now it is the moment when the magic comes. Just by typing %python at the top of a cell we ca execute python code with all the Spark (pyspark) advantages ad features. We load the table into a pyspark dataframe and convert both columns into Python lists using these Python oneliners:"
},
{
"code": null,
"e": 15031,
"s": 14792,
"text": "%pythondf = table(\"ratedDF\")rating_list = df.select(\"rating\").collect()number_rates = df.select(\"NumberOfRates\").collect()rate_category = [float(row.rating) for row in rating_list]n_rates = [int(row.NumberOfRates) for row in number_rates]"
},
{
"code": null,
"e": 15239,
"s": 15031,
"text": "And to conclude, we will make our visualization. This is a total freestyle process and some plots will be more prettier than others. Remember that a categorical variable should be represented with a barplot:"
},
{
"code": null,
"e": 15565,
"s": 15239,
"text": "%pythonimport matplotlib.pyplot as pltimport numpy as npfig, ax = plt.subplots()ax.bar(rate_category, n_rates, align='center', width=0.4, facecolor='b', edgecolor='b', linewidth=3, alpha=.3)plt.title('Number of Rates vs Stars')plt.xlabel('Stars (*)')plt.xlim(0,5.5)plt.ylim(0,8000000)ax.set_xticks(rate_category)display(fig) "
},
{
"code": null,
"e": 15719,
"s": 15565,
"text": "Not much to comment about it except that there are no movies rated with 0 stars and that this does not look as a normal distribution as one could expect."
},
{
"code": null,
"e": 16294,
"s": 15719,
"text": "And that’s all folks. I hope you have enjoyed this article as much as I have done it learning about scala, spark and Databricks and thinking about insights on the movies dataset. Now I am implementing and improving the perfomance of recommender systems on this dataset using the machine learning library from spark Spark MLlib. These models might be shown along with more complex queries and descriptive statistics over this dataset on future articles. I have played a bit with the genres column and obtained deeper statistics but I did not want this article to super dense."
},
{
"code": null,
"e": 16391,
"s": 16294,
"text": "Since this is my very first article, once again, any feedback and comments are well appreciated."
}
]
|
Imbalanced-Learn module in Python - GeeksforGeeks | 11 Dec, 2020
Imbalanced-Learn is a Python module that helps in balancing the datasets which are highly skewed or biased towards some classes. Thus, it helps in resampling the classes which are otherwise oversampled or undesampled. If there is a greater imbalance ratio, the output is biased to the class which has a higher number of examples. The following dependencies need to be installed to use imbalanced-learn:
scipy(>=0.19.1)
numpy(>=1.13.3)
scikit-learn(>=0.23)
joblib(>=0.11)
keras 2 (optional)
tensorflow (optional)
To install imbalanced-learn just type in :
pip install imbalanced-learn
The resampling of data is done in 2 parts:
Estimator: It implements a fit method which is derived from scikit-learn. The data and targets are both in the form of a 2D array
estimator = obj.fit(data, targets)
Resampler: The fit_resample method resample the data and targets into a dictionary with a key-value pair of data_resampled and targets_resampled.
data_resampled, targets_resampled = obj.fit_resample(data, targets)
The Imbalanced Learn module has different algorithms for oversampling and undersampling:
We will use the built-in dataset called the make_classification dataset which return
x: a matrix of n_samples*n_features and
y: an array of integer labels.
Click dataset to get the dataset used.
Python3
# import required modulesfrom sklearn.datasets import make_classification # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)print('x:\n', X)print('y:\n', y)
Output:
Below are some programs in which depict how to apply oversampling and undersampling to the dataset:
Random Over Sampler: It is a naive method where classes that have low examples are generated and randomly resampled.
Syntax:
from imblearn.over_sampling import RandomOverSampler
Parameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, ratio=None
Implementation:oversample = RandomOverSampler(sampling_strategy=’minority’)X_oversample,Y_oversample=oversample.fit_resample(X,Y)
Return Type:a matrix with the shape of n_samples*n_features
Example:
Python3
# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.over_sampling import RandomOverSampler # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0) oversample = RandomOverSampler(sampling_strategy='minority')x_over, y_over = oversample.fit_resample(x, y) # print the features and the labelsprint('x_over:\n', x_over)print('y_over:\n', y_over)
Output:
SMOTE, ADASYN: Synthetic Minority Oversampling Technique (SMOTE) and the Adaptive Synthetic (ADASYN) are 2 methods used in oversampling. These also generate low examples but ADASYN takes into account the density of distribution to distribute the data points evenly.
Syntax:
from imblearn.over_sampling import SMOTE, ADASYN
Parameters(optional):*, sampling_strategy=’auto’, random_state=None, n_neighbors=5, n_jobs=None
Implementation:smote = SMOTE(ratio=’minority’)X_smote,Y_smote=smote.fit_resample(X,Y)
Return Type:a matrix with the shape of n_samples*n_features
Example:
Python3
# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.over_sampling import SMOTE # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)smote = SMOTE()x_smote, y_smote = smote.fit_resample(x, y) # print the features and the labelsprint('x_smote:\n', x_smote)print('y_smote:\n', y_smote)
Output:
Edited Nearest Neighbours: This algorithm removes any sample which has labels different from those of its adjoining classes.
Syntax:
from imblearn.under_sampling import EditedNearestNeighbours
Parameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, n_neighbors=3, kind_sel=’all’, n_jobs=1, ratio=None
Implementation:en = EditedNearestNeighbours()X_en,Y_en=en.fit_resample(X, y)
Return Type:a matrix with the shape of n_samples*n_features
Example:
Python3
# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.under_sampling import EditedNearestNeighbours # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)en = EditedNearestNeighbours()x_en, y_en = en.fit_resample(x, y) # print the features and the labelsprint('x_en:\n', x_en)print('y_en:\n', y_en)
Output:
Random Under Sampler: It involves sampling any random class with or without any replacement.
Syntax:
from imblearn.under_sampling import RandomUnderSamplerParameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, replacement=False, ratio=None
Implementation:undersample = RandomUnderSampler()X_under, y_under = undersample.fit_resample(X, y)
Return Type: a matrix with the shape of n_samples*n_features
Example:
Python3
# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.under_sampling import RandomUnderSampler # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)undersample = RandomUnderSampler()x_under, y_under = undersample.fit_resample(x, y) # print the features and the labelsprint('x_under:\n', x_under)print('y_under:\n', y_under)
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 24304,
"s": 23901,
"text": "Imbalanced-Learn is a Python module that helps in balancing the datasets which are highly skewed or biased towards some classes. Thus, it helps in resampling the classes which are otherwise oversampled or undesampled. If there is a greater imbalance ratio, the output is biased to the class which has a higher number of examples. The following dependencies need to be installed to use imbalanced-learn:"
},
{
"code": null,
"e": 24320,
"s": 24304,
"text": "scipy(>=0.19.1)"
},
{
"code": null,
"e": 24336,
"s": 24320,
"text": "numpy(>=1.13.3)"
},
{
"code": null,
"e": 24357,
"s": 24336,
"text": "scikit-learn(>=0.23)"
},
{
"code": null,
"e": 24372,
"s": 24357,
"text": "joblib(>=0.11)"
},
{
"code": null,
"e": 24391,
"s": 24372,
"text": "keras 2 (optional)"
},
{
"code": null,
"e": 24413,
"s": 24391,
"text": "tensorflow (optional)"
},
{
"code": null,
"e": 24456,
"s": 24413,
"text": "To install imbalanced-learn just type in :"
},
{
"code": null,
"e": 24485,
"s": 24456,
"text": "pip install imbalanced-learn"
},
{
"code": null,
"e": 24529,
"s": 24485,
"text": "The resampling of data is done in 2 parts: "
},
{
"code": null,
"e": 24659,
"s": 24529,
"text": "Estimator: It implements a fit method which is derived from scikit-learn. The data and targets are both in the form of a 2D array"
},
{
"code": null,
"e": 24694,
"s": 24659,
"text": "estimator = obj.fit(data, targets)"
},
{
"code": null,
"e": 24840,
"s": 24694,
"text": "Resampler: The fit_resample method resample the data and targets into a dictionary with a key-value pair of data_resampled and targets_resampled."
},
{
"code": null,
"e": 24908,
"s": 24840,
"text": "data_resampled, targets_resampled = obj.fit_resample(data, targets)"
},
{
"code": null,
"e": 24997,
"s": 24908,
"text": "The Imbalanced Learn module has different algorithms for oversampling and undersampling:"
},
{
"code": null,
"e": 25083,
"s": 24997,
"text": "We will use the built-in dataset called the make_classification dataset which return "
},
{
"code": null,
"e": 25124,
"s": 25083,
"text": "x: a matrix of n_samples*n_features and "
},
{
"code": null,
"e": 25155,
"s": 25124,
"text": "y: an array of integer labels."
},
{
"code": null,
"e": 25194,
"s": 25155,
"text": "Click dataset to get the dataset used."
},
{
"code": null,
"e": 25202,
"s": 25194,
"text": "Python3"
},
{
"code": "# import required modulesfrom sklearn.datasets import make_classification # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)print('x:\\n', X)print('y:\\n', y)",
"e": 25449,
"s": 25202,
"text": null
},
{
"code": null,
"e": 25457,
"s": 25449,
"text": "Output:"
},
{
"code": null,
"e": 25557,
"s": 25457,
"text": "Below are some programs in which depict how to apply oversampling and undersampling to the dataset:"
},
{
"code": null,
"e": 25674,
"s": 25557,
"text": "Random Over Sampler: It is a naive method where classes that have low examples are generated and randomly resampled."
},
{
"code": null,
"e": 25682,
"s": 25674,
"text": "Syntax:"
},
{
"code": null,
"e": 25735,
"s": 25682,
"text": "from imblearn.over_sampling import RandomOverSampler"
},
{
"code": null,
"e": 25835,
"s": 25735,
"text": "Parameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, ratio=None"
},
{
"code": null,
"e": 25965,
"s": 25835,
"text": "Implementation:oversample = RandomOverSampler(sampling_strategy=’minority’)X_oversample,Y_oversample=oversample.fit_resample(X,Y)"
},
{
"code": null,
"e": 26025,
"s": 25965,
"text": "Return Type:a matrix with the shape of n_samples*n_features"
},
{
"code": null,
"e": 26034,
"s": 26025,
"text": "Example:"
},
{
"code": null,
"e": 26042,
"s": 26034,
"text": "Python3"
},
{
"code": "# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.over_sampling import RandomOverSampler # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0) oversample = RandomOverSampler(sampling_strategy='minority')x_over, y_over = oversample.fit_resample(x, y) # print the features and the labelsprint('x_over:\\n', x_over)print('y_over:\\n', y_over)",
"e": 26506,
"s": 26042,
"text": null
},
{
"code": null,
"e": 26514,
"s": 26506,
"text": "Output:"
},
{
"code": null,
"e": 26782,
"s": 26514,
"text": " SMOTE, ADASYN: Synthetic Minority Oversampling Technique (SMOTE) and the Adaptive Synthetic (ADASYN) are 2 methods used in oversampling. These also generate low examples but ADASYN takes into account the density of distribution to distribute the data points evenly."
},
{
"code": null,
"e": 26790,
"s": 26782,
"text": "Syntax:"
},
{
"code": null,
"e": 26839,
"s": 26790,
"text": "from imblearn.over_sampling import SMOTE, ADASYN"
},
{
"code": null,
"e": 26935,
"s": 26839,
"text": "Parameters(optional):*, sampling_strategy=’auto’, random_state=None, n_neighbors=5, n_jobs=None"
},
{
"code": null,
"e": 27021,
"s": 26935,
"text": "Implementation:smote = SMOTE(ratio=’minority’)X_smote,Y_smote=smote.fit_resample(X,Y)"
},
{
"code": null,
"e": 27081,
"s": 27021,
"text": "Return Type:a matrix with the shape of n_samples*n_features"
},
{
"code": null,
"e": 27090,
"s": 27081,
"text": "Example:"
},
{
"code": null,
"e": 27098,
"s": 27090,
"text": "Python3"
},
{
"code": "# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.over_sampling import SMOTE # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)smote = SMOTE()x_smote, y_smote = smote.fit_resample(x, y) # print the features and the labelsprint('x_smote:\\n', x_smote)print('y_smote:\\n', y_smote)",
"e": 27450,
"s": 27098,
"text": null
},
{
"code": null,
"e": 27458,
"s": 27450,
"text": "Output:"
},
{
"code": null,
"e": 27583,
"s": 27458,
"text": "Edited Nearest Neighbours: This algorithm removes any sample which has labels different from those of its adjoining classes."
},
{
"code": null,
"e": 27591,
"s": 27583,
"text": "Syntax:"
},
{
"code": null,
"e": 27651,
"s": 27591,
"text": "from imblearn.under_sampling import EditedNearestNeighbours"
},
{
"code": null,
"e": 27792,
"s": 27651,
"text": "Parameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, n_neighbors=3, kind_sel=’all’, n_jobs=1, ratio=None"
},
{
"code": null,
"e": 27869,
"s": 27792,
"text": "Implementation:en = EditedNearestNeighbours()X_en,Y_en=en.fit_resample(X, y)"
},
{
"code": null,
"e": 27929,
"s": 27869,
"text": "Return Type:a matrix with the shape of n_samples*n_features"
},
{
"code": null,
"e": 27938,
"s": 27929,
"text": "Example:"
},
{
"code": null,
"e": 27946,
"s": 27938,
"text": "Python3"
},
{
"code": "# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.under_sampling import EditedNearestNeighbours # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)en = EditedNearestNeighbours()x_en, y_en = en.fit_resample(x, y) # print the features and the labelsprint('x_en:\\n', x_en)print('y_en:\\n', y_en)",
"e": 28311,
"s": 27946,
"text": null
},
{
"code": null,
"e": 28319,
"s": 28311,
"text": "Output:"
},
{
"code": null,
"e": 28412,
"s": 28319,
"text": "Random Under Sampler: It involves sampling any random class with or without any replacement."
},
{
"code": null,
"e": 28420,
"s": 28412,
"text": "Syntax:"
},
{
"code": null,
"e": 28593,
"s": 28420,
"text": "from imblearn.under_sampling import RandomUnderSamplerParameters(optional): sampling_strategy=’auto’, return_indices=False, random_state=None, replacement=False, ratio=None"
},
{
"code": null,
"e": 28692,
"s": 28593,
"text": "Implementation:undersample = RandomUnderSampler()X_under, y_under = undersample.fit_resample(X, y)"
},
{
"code": null,
"e": 28753,
"s": 28692,
"text": "Return Type: a matrix with the shape of n_samples*n_features"
},
{
"code": null,
"e": 28762,
"s": 28753,
"text": "Example:"
},
{
"code": null,
"e": 28770,
"s": 28762,
"text": "Python3"
},
{
"code": "# import required modulesfrom sklearn.datasets import make_classificationfrom imblearn.under_sampling import RandomUnderSampler # define datasetx, y = make_classification(n_samples=10000, weights=[0.99], flip_y=0)undersample = RandomUnderSampler()x_under, y_under = undersample.fit_resample(x, y) # print the features and the labelsprint('x_under:\\n', x_under)print('y_under:\\n', y_under)",
"e": 29215,
"s": 28770,
"text": null
},
{
"code": null,
"e": 29223,
"s": 29215,
"text": "Output:"
},
{
"code": null,
"e": 29238,
"s": 29223,
"text": "python-modules"
},
{
"code": null,
"e": 29245,
"s": 29238,
"text": "Python"
},
{
"code": null,
"e": 29343,
"s": 29245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29352,
"s": 29343,
"text": "Comments"
},
{
"code": null,
"e": 29365,
"s": 29352,
"text": "Old Comments"
},
{
"code": null,
"e": 29386,
"s": 29365,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 29418,
"s": 29386,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29441,
"s": 29418,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 29463,
"s": 29441,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29490,
"s": 29463,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29506,
"s": 29490,
"text": "Deque in Python"
},
{
"code": null,
"e": 29548,
"s": 29506,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29604,
"s": 29548,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29649,
"s": 29604,
"text": "Python - Ways to remove duplicates from list"
}
]
|
Java program to calculate the power of a number | Read the base and exponent values from the user. Multiply the base number by itself and multiply the resultant with base (again) repeat this n times where n is the exponent value.
2 ^ 5 = 2 X 2 X 2 X 2 X 2 (5 times)
import java.util.Scanner;
public class PowerOfNumber {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base number ::");
int base = sc.nextInt();
int temp = base;
System.out.println("Enter the exponent number ::");
int exp = sc.nextInt();
for (int i=1; i<exp; i++){
temp = temp*temp;
}
System.out.println("Result of "+base+" power "+exp+" is "+temp);
}
}
Enter the base number ::
12
Enter the exponent number ::
2
Result of 12 power 2 is 144 | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "Read the base and exponent values from the user. Multiply the base number by itself and multiply the resultant with base (again) repeat this n times where n is the exponent value."
},
{
"code": null,
"e": 1278,
"s": 1242,
"text": "2 ^ 5 = 2 X 2 X 2 X 2 X 2 (5 times)"
},
{
"code": null,
"e": 1762,
"s": 1278,
"text": "import java.util.Scanner;\npublic class PowerOfNumber {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the base number ::\");\n int base = sc.nextInt();\n int temp = base;\n System.out.println(\"Enter the exponent number ::\");\n int exp = sc.nextInt();\n\n for (int i=1; i<exp; i++){\n temp = temp*temp;\n }\n System.out.println(\"Result of \"+base+\" power \"+exp+\" is \"+temp);\n }\n}"
},
{
"code": null,
"e": 1849,
"s": 1762,
"text": "Enter the base number ::\n12\nEnter the exponent number ::\n2\nResult of 12 power 2 is 144"
}
]
|
Can we assign a reference to a variable in Python? | Concept of variable in Python is different from C/C++. In C/C++, variable is a named location in memory. Even if value of one is assigned to another, it creates a copy in another location.
int x=5;
int y=x;
For example in C++, the & operator returns address of the declared variable.
cout<x<<&x<<y<<&y;
This will print different address of x and y even though both contain same value. You can create an alias to it by storing the address in a reference variable
int x=5;
int &y=x;
y=10;
cout<<x<<y;
This shows both variables having 10. Here, y is a reference to x. Hence they can be interchangeably used.
However, in Python, variable is just a name given to an object in the memory. Even if we assign its value to another variable, both are in fact referring to same object in memory. This can be verified by id() function.
>>> x=5
>>> y=x
>>> id(x), id(y)
(1486402752, 1486402752)
It therefore is clear that in Python, we can not create reference to a variable. | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "Concept of variable in Python is different from C/C++. In C/C++, variable is a named location in memory. Even if value of one is assigned to another, it creates a copy in another location."
},
{
"code": null,
"e": 1269,
"s": 1251,
"text": "int x=5;\nint y=x;"
},
{
"code": null,
"e": 1346,
"s": 1269,
"text": "For example in C++, the & operator returns address of the declared variable."
},
{
"code": null,
"e": 1365,
"s": 1346,
"text": "cout<x<<&x<<y<<&y;"
},
{
"code": null,
"e": 1524,
"s": 1365,
"text": "This will print different address of x and y even though both contain same value. You can create an alias to it by storing the address in a reference variable"
},
{
"code": null,
"e": 1561,
"s": 1524,
"text": "int x=5;\nint &y=x;\ny=10;\ncout<<x<<y;"
},
{
"code": null,
"e": 1667,
"s": 1561,
"text": "This shows both variables having 10. Here, y is a reference to x. Hence they can be interchangeably used."
},
{
"code": null,
"e": 1886,
"s": 1667,
"text": "However, in Python, variable is just a name given to an object in the memory. Even if we assign its value to another variable, both are in fact referring to same object in memory. This can be verified by id() function."
},
{
"code": null,
"e": 1944,
"s": 1886,
"text": ">>> x=5\n>>> y=x\n>>> id(x), id(y)\n(1486402752, 1486402752)"
},
{
"code": null,
"e": 2025,
"s": 1944,
"text": "It therefore is clear that in Python, we can not create reference to a variable."
}
]
|
CoffeeScript Tutorial | CoffeeScript is a light weight language which transcompiles into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language.
This tutorial has been prepared for beginners to help them understand the basic functionality of CoffeeScript to build dynamic webpages and web applications.
For this tutorial, it is assumed that the readers have a prior knowledge of HTML coding and JavaScript. It would help if the reader has some prior exposure to object-oriented programming concepts and a general idea on creating online applications.
For most of the examples given in this tutorial, you will find Try it option, so just make use of this option to transcompile your CoffeeScript programs to JavaScript programs on the spot and enjoy your learning.
Try the following example using the Try it option available at the top right corner of the below sample code box −
console.log "Hello Welcome to Tutorials point"
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2513,
"s": 2309,
"text": "CoffeeScript is a light weight language which transcompiles into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language."
},
{
"code": null,
"e": 2671,
"s": 2513,
"text": "This tutorial has been prepared for beginners to help them understand the basic functionality of CoffeeScript to build dynamic webpages and web applications."
},
{
"code": null,
"e": 2919,
"s": 2671,
"text": "For this tutorial, it is assumed that the readers have a prior knowledge of HTML coding and JavaScript. It would help if the reader has some prior exposure to object-oriented programming concepts and a general idea on creating online applications."
},
{
"code": null,
"e": 3132,
"s": 2919,
"text": "For most of the examples given in this tutorial, you will find Try it option, so just make use of this option to transcompile your CoffeeScript programs to JavaScript programs on the spot and enjoy your learning."
},
{
"code": null,
"e": 3247,
"s": 3132,
"text": "Try the following example using the Try it option available at the top right corner of the below sample code box −"
},
{
"code": null,
"e": 3296,
"s": 3247,
"text": "console.log \"Hello Welcome to Tutorials point\"\n\n"
},
{
"code": null,
"e": 3303,
"s": 3296,
"text": " Print"
},
{
"code": null,
"e": 3314,
"s": 3303,
"text": " Add Notes"
}
]
|
What’s the difference between useContext and Redux ? | 21 May, 2021
useContext: useContext is a hook that provides a way to pass data through the component tree without manually passing props down through each nested component.
Syntax:
const Context = useContext(initialValue);
Project Structure: It will look like this.
Example: In this example, App.js is sending data to component ComC with the help of useContext.
App.js
Javascript
import React, { createContext } from 'react';import "./index.css";import ComB from './ComB'; const Data = createContext(); export default function App() { return ( <div className="App"> <Data.Provider value={"Welcome to GFG"}> <ComB /> </Data.Provider> </div> );} export { Data };
ComB.js
Javascript
import React, { useState } from "react";import ComC from "./ComC"; const ComB = () => { const [show, setShow] = useState(false); return ( <> {show ? <ComC /> : null} <button onClick={() => setShow(!show)}> Click ME</button> </> );} export default ComB;
ComC.js
Javascript
import React, { useContext } from 'react';import { Data } from './App'; const ComC = ({ name }) => { const context = useContext(Data); return <h1>{context}</h1>} export default ComC;
Output:
Redux: Redux is a state managing library used in JavaScript apps. It is very popular for React and React-Native. It simply manages the state and data of your application.
Building Parts of redux:
ActionReducerStore
Action
Reducer
Store
Project Structure: It will look like this.
Example: In this example, we have created two buttons one will increment the value and another will decrement the value. With Redux, we are managing the state.
App.js
Javascript
import React from 'react';import './index.css';import { useSelector, useDispatch } from 'react-redux';import { incNum, decNum } from './actions/index'; function App() { const mystate = useSelector((state) => state.change); const dispatch = useDispatch(); return ( <> <h2>Increment/Decrement the number using Redux.</h2> <div className="app"> <h1>{mystate}</h1> <button onClick={() => dispatch(incNum())}>+</button> <button onClick={() => dispatch(decNum())}>-</button> </div> </> );} export default App;
index.js (In src/actions folder)
Javascript
export const incNum = () => { return{ type:"INCREMENT"}} export const decNum = () => { return{ type:"DECREMENT"}}
func.js
Javascript
const initialState = 0; const change = (state = initialState, action) => { switch (action.type) { case "INCREMENT": return state + 1; case "DECREMENT": return state - 1; default: return state; }} export default change;
index.js (In src/reducers folder)
Javascript
import change from './func'import {combineReducers}from 'redux'; const rootReducer = combineReducers({change}); export default rootReducer;
store.js
Javascript
import {createStore} from 'redux';import rootReducer from './reducers/index'; const store = createStore(rootReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); export default store;
index.js (In src folder)
Javascript
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App.jsx'import store from './store';import { Provider } from 'react-redux'; ReactDOM.render( <Provider store={store}> <App /> </Provider> , document.getElementById("root"));
Output:
Some difference between useContext and Redux:
useContext
Redux
Picked
React-Questions
ReactJS-Advanced
Redux
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
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?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 212,
"s": 52,
"text": "useContext: useContext is a hook that provides a way to pass data through the component tree without manually passing props down through each nested component."
},
{
"code": null,
"e": 220,
"s": 212,
"text": "Syntax:"
},
{
"code": null,
"e": 262,
"s": 220,
"text": "const Context = useContext(initialValue);"
},
{
"code": null,
"e": 305,
"s": 262,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 401,
"s": 305,
"text": "Example: In this example, App.js is sending data to component ComC with the help of useContext."
},
{
"code": null,
"e": 408,
"s": 401,
"text": "App.js"
},
{
"code": null,
"e": 419,
"s": 408,
"text": "Javascript"
},
{
"code": "import React, { createContext } from 'react';import \"./index.css\";import ComB from './ComB'; const Data = createContext(); export default function App() { return ( <div className=\"App\"> <Data.Provider value={\"Welcome to GFG\"}> <ComB /> </Data.Provider> </div> );} export { Data };",
"e": 728,
"s": 419,
"text": null
},
{
"code": null,
"e": 736,
"s": 728,
"text": "ComB.js"
},
{
"code": null,
"e": 747,
"s": 736,
"text": "Javascript"
},
{
"code": "import React, { useState } from \"react\";import ComC from \"./ComC\"; const ComB = () => { const [show, setShow] = useState(false); return ( <> {show ? <ComC /> : null} <button onClick={() => setShow(!show)}> Click ME</button> </> );} export default ComB;",
"e": 1028,
"s": 747,
"text": null
},
{
"code": null,
"e": 1036,
"s": 1028,
"text": "ComC.js"
},
{
"code": null,
"e": 1047,
"s": 1036,
"text": "Javascript"
},
{
"code": "import React, { useContext } from 'react';import { Data } from './App'; const ComC = ({ name }) => { const context = useContext(Data); return <h1>{context}</h1>} export default ComC;",
"e": 1234,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1242,
"s": 1234,
"text": "Output:"
},
{
"code": null,
"e": 1413,
"s": 1242,
"text": "Redux: Redux is a state managing library used in JavaScript apps. It is very popular for React and React-Native. It simply manages the state and data of your application."
},
{
"code": null,
"e": 1438,
"s": 1413,
"text": "Building Parts of redux:"
},
{
"code": null,
"e": 1457,
"s": 1438,
"text": "ActionReducerStore"
},
{
"code": null,
"e": 1464,
"s": 1457,
"text": "Action"
},
{
"code": null,
"e": 1472,
"s": 1464,
"text": "Reducer"
},
{
"code": null,
"e": 1478,
"s": 1472,
"text": "Store"
},
{
"code": null,
"e": 1521,
"s": 1478,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 1681,
"s": 1521,
"text": "Example: In this example, we have created two buttons one will increment the value and another will decrement the value. With Redux, we are managing the state."
},
{
"code": null,
"e": 1688,
"s": 1681,
"text": "App.js"
},
{
"code": null,
"e": 1699,
"s": 1688,
"text": "Javascript"
},
{
"code": "import React from 'react';import './index.css';import { useSelector, useDispatch } from 'react-redux';import { incNum, decNum } from './actions/index'; function App() { const mystate = useSelector((state) => state.change); const dispatch = useDispatch(); return ( <> <h2>Increment/Decrement the number using Redux.</h2> <div className=\"app\"> <h1>{mystate}</h1> <button onClick={() => dispatch(incNum())}>+</button> <button onClick={() => dispatch(decNum())}>-</button> </div> </> );} export default App;",
"e": 2257,
"s": 1699,
"text": null
},
{
"code": null,
"e": 2290,
"s": 2257,
"text": "index.js (In src/actions folder)"
},
{
"code": null,
"e": 2301,
"s": 2290,
"text": "Javascript"
},
{
"code": "export const incNum = () => { return{ type:\"INCREMENT\"}} export const decNum = () => { return{ type:\"DECREMENT\"}}",
"e": 2420,
"s": 2301,
"text": null
},
{
"code": null,
"e": 2428,
"s": 2420,
"text": "func.js"
},
{
"code": null,
"e": 2439,
"s": 2428,
"text": "Javascript"
},
{
"code": "const initialState = 0; const change = (state = initialState, action) => { switch (action.type) { case \"INCREMENT\": return state + 1; case \"DECREMENT\": return state - 1; default: return state; }} export default change;",
"e": 2671,
"s": 2439,
"text": null
},
{
"code": null,
"e": 2705,
"s": 2671,
"text": "index.js (In src/reducers folder)"
},
{
"code": null,
"e": 2716,
"s": 2705,
"text": "Javascript"
},
{
"code": "import change from './func'import {combineReducers}from 'redux'; const rootReducer = combineReducers({change}); export default rootReducer;",
"e": 2858,
"s": 2716,
"text": null
},
{
"code": null,
"e": 2867,
"s": 2858,
"text": "store.js"
},
{
"code": null,
"e": 2878,
"s": 2867,
"text": "Javascript"
},
{
"code": "import {createStore} from 'redux';import rootReducer from './reducers/index'; const store = createStore(rootReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); export default store;",
"e": 3097,
"s": 2878,
"text": null
},
{
"code": null,
"e": 3122,
"s": 3097,
"text": "index.js (In src folder)"
},
{
"code": null,
"e": 3133,
"s": 3122,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App.jsx'import store from './store';import { Provider } from 'react-redux'; ReactDOM.render( <Provider store={store}> <App /> </Provider> , document.getElementById(\"root\"));",
"e": 3413,
"s": 3133,
"text": null
},
{
"code": null,
"e": 3421,
"s": 3413,
"text": "Output:"
},
{
"code": null,
"e": 3467,
"s": 3421,
"text": "Some difference between useContext and Redux:"
},
{
"code": null,
"e": 3479,
"s": 3467,
"text": "useContext "
},
{
"code": null,
"e": 3485,
"s": 3479,
"text": "Redux"
},
{
"code": null,
"e": 3492,
"s": 3485,
"text": "Picked"
},
{
"code": null,
"e": 3508,
"s": 3492,
"text": "React-Questions"
},
{
"code": null,
"e": 3525,
"s": 3508,
"text": "ReactJS-Advanced"
},
{
"code": null,
"e": 3531,
"s": 3525,
"text": "Redux"
},
{
"code": null,
"e": 3539,
"s": 3531,
"text": "ReactJS"
},
{
"code": null,
"e": 3556,
"s": 3539,
"text": "Web Technologies"
},
{
"code": null,
"e": 3654,
"s": 3556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3692,
"s": 3654,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 3719,
"s": 3692,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 3758,
"s": 3719,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 3810,
"s": 3758,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 3849,
"s": 3810,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 3882,
"s": 3849,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3944,
"s": 3882,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4005,
"s": 3944,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4055,
"s": 4005,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
isdigit() function in C/C++ with Examples | 19 Jan, 2021
The isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if it’s a digit else it returns 0. For example, it returns a non-zero value for ‘0’ to ‘9’ and zero for others.
The isdigit() is declared inside ctype.h header file.
It is used to check whether the entered character is a numeric character[0 – 9] or not.
It takes a single argument in the form of an integer and returns the value of type int.
Even though isdigit() takes an integer as an argument, the character is passed to the function. Internally, the character is converted to its ASCII value for the check.
Header File:
#include <ctype.h>
Syntax:
std::isdigit(int arg)
Parameter: The template std::isdigit() accepts a single parameter of integer type.
Return type: This function returns an integer value on the basis of the argument passed to it, if the argument is a numeric character then it returns a non-zero value(true value), otherwise it returns zero(false value).
Below is the program to illustrate the same:
C
// C program to demonstrate isdigit()#include <ctype.h>#include <stdio.h> // Driver Codeint main(){ // Taking input char ch = '6'; // Check if the given input // is numeric or not if (isdigit(ch)) printf("\nEntered character is" " numeric character"); else printf("\nEntered character is not" " a numeric character"); return 0;}
// C++ program to demonstrate isdigit()#include <ctype.h>#include <iostream>using namespace std;
// Driver Codeint main(){// Taking inputchar ch = ‘6’;
// Check if the given input// is numeric or notif (isdigit(ch))cout << "\nEntered character is"<< " numeric character";elsecout << "\nEntered character is not"" a numeric character";return 0;}
Entered character is numeric character
C Basics
CPP-Functions
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Jan, 2021"
},
{
"code": null,
"e": 297,
"s": 53,
"text": "The isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if it’s a digit else it returns 0. For example, it returns a non-zero value for ‘0’ to ‘9’ and zero for others."
},
{
"code": null,
"e": 351,
"s": 297,
"text": "The isdigit() is declared inside ctype.h header file."
},
{
"code": null,
"e": 439,
"s": 351,
"text": "It is used to check whether the entered character is a numeric character[0 – 9] or not."
},
{
"code": null,
"e": 527,
"s": 439,
"text": "It takes a single argument in the form of an integer and returns the value of type int."
},
{
"code": null,
"e": 696,
"s": 527,
"text": "Even though isdigit() takes an integer as an argument, the character is passed to the function. Internally, the character is converted to its ASCII value for the check."
},
{
"code": null,
"e": 709,
"s": 696,
"text": "Header File:"
},
{
"code": null,
"e": 728,
"s": 709,
"text": "#include <ctype.h>"
},
{
"code": null,
"e": 736,
"s": 728,
"text": "Syntax:"
},
{
"code": null,
"e": 758,
"s": 736,
"text": "std::isdigit(int arg)"
},
{
"code": null,
"e": 841,
"s": 758,
"text": "Parameter: The template std::isdigit() accepts a single parameter of integer type."
},
{
"code": null,
"e": 1061,
"s": 841,
"text": "Return type: This function returns an integer value on the basis of the argument passed to it, if the argument is a numeric character then it returns a non-zero value(true value), otherwise it returns zero(false value)."
},
{
"code": null,
"e": 1106,
"s": 1061,
"text": "Below is the program to illustrate the same:"
},
{
"code": null,
"e": 1108,
"s": 1106,
"text": "C"
},
{
"code": "// C program to demonstrate isdigit()#include <ctype.h>#include <stdio.h> // Driver Codeint main(){ // Taking input char ch = '6'; // Check if the given input // is numeric or not if (isdigit(ch)) printf(\"\\nEntered character is\" \" numeric character\"); else printf(\"\\nEntered character is not\" \" a numeric character\"); return 0;}",
"e": 1503,
"s": 1108,
"text": null
},
{
"code": null,
"e": 1600,
"s": 1503,
"text": "// C++ program to demonstrate isdigit()#include <ctype.h>#include <iostream>using namespace std;"
},
{
"code": null,
"e": 1655,
"s": 1600,
"text": "// Driver Codeint main(){// Taking inputchar ch = ‘6’;"
},
{
"code": null,
"e": 1848,
"s": 1655,
"text": "// Check if the given input// is numeric or notif (isdigit(ch))cout << \"\\nEntered character is\"<< \" numeric character\";elsecout << \"\\nEntered character is not\"\" a numeric character\";return 0;}"
},
{
"code": null,
"e": 1888,
"s": 1848,
"text": "Entered character is numeric character\n"
},
{
"code": null,
"e": 1897,
"s": 1888,
"text": "C Basics"
},
{
"code": null,
"e": 1911,
"s": 1897,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1915,
"s": 1911,
"text": "C++"
},
{
"code": null,
"e": 1928,
"s": 1915,
"text": "C++ Programs"
},
{
"code": null,
"e": 1932,
"s": 1928,
"text": "CPP"
}
]
|
Simplified International Data Encryption Algorithm (IDEA) | 22 Oct, 2021
In cryptography, block ciphers are very important in the designing of many cryptographic algorithms and are widely used to encrypt the bulk of data in chunks. By chunks, it means that the cipher takes a fixed size of the plaintext in the encryption process and generates a fixed size ciphertext using a fixed-length key. An algorithm’s strength is determined by its key length.
The Simplified International Data Encryption Algorithm (IDEA) is a symmetric key block cipher that:
uses a fixed-length plaintext of 16 bits and
encrypts them in 4 chunks of 4 bits each
to produce 16 bits ciphertext.
The length of the key used is 32 bits.
The key is also divided into 8 blocks of 4 bits each.
This algorithm involves a series of 4 identical complete rounds and 1 half-round. Each complete round involves a series of 14 steps that includes operations like:
Bitwise XOR
Addition modulo
Multiplication modulo +1
After 4 complete rounds, the final “half-round” consists of only the first 4 out of the 14 steps previously used in the full rounds. To perform these rounds, each binary notation must be converted to its equivalent decimal notation, perform the operation and the result obtained should be converted back to the binary representation for the final result of that particular step.
Key Schedule: 6 subkeys of 4 bits out of the 8 subkeys are used in each complete round, while 4 are used in the half-round. So, 4.5 rounds require 28 subkeys. The given key, ‘K’, directly gives the first 8 subkeys. By rotating the main key left by 6 bits between each group of 8, further groups of 8 subkeys are created, implying less than one rotation per round for the key (3 rotations).
* denotes a shift of bits
Notations used in the 14 steps:
The 16-bit plaintext can be represented as X1 || X2 || X3 || X4, each of size 4 bits. The 32-bit key is broken into 8 subkeys denoted as K1 || K2 || K3 || K4 || K5 || K6 || K7 || K8, again of size 4 bits each. Each round of 14 steps uses the three algebraic operation-Addition modulo (2^4), Multiplication modulo (2^4)+1 and Bitwise XOR. The steps involved are as follows:
X1 * K1X2 + K2X3 + K3X4 * K4Step 1 ^ Step 3Step 2 ^ Step 4Step 5 * K5Step 6 + Step 7Step 8 * K6Step 7 + Step 9Step 1 ^ Step 9Step 3 ^ Step 9Step 2 ^ Step 10Step 4 ^ Step 10
X1 * K1
X2 + K2
X3 + K3
X4 * K4
Step 1 ^ Step 3
Step 2 ^ Step 4
Step 5 * K5
Step 6 + Step 7
Step 8 * K6
Step 7 + Step 9
Step 1 ^ Step 9
Step 3 ^ Step 9
Step 2 ^ Step 10
Step 4 ^ Step 10
The input to the next round is Step 11 || Step 13 || Step 12 || Step 14, which becomes X1 || X2 || X3 || X4. This swap between 12 and 13 takes place after each complete round, except the last complete round (4th round), where the input to the final half round is Step 11 || Step 12 || Step 13 || Step 14.
After last complete round, the half-round is as follows:
X1 * K1X2 + K2X3 + K3X4 * K4
X1 * K1
X2 + K2
X3 + K3
X4 * K4
The final output is obtained by concatenating the blocks.
Example:
Key: 1101 1100 0110 1111 0011 1111 0101 1001
Plaintext: 1001 1100 1010 1100
Ciphertext: 1011 1011 0100 1011
Explanation: The explanation is only for 1st complete round (the remaining can be implemented similarly) and the last half-round.
Round 1: From the plaintext: X1 – 1001, X2 – 1100, X3 – 1010, X4 – 1100 From the table above: K1 – 1101, K2 – 1100, K3 – 0110, K4 – 1111, K5 – 0011, K6 – 1111
From the plaintext: X1 – 1001, X2 – 1100, X3 – 1010, X4 – 1100
From the table above: K1 – 1101, K2 – 1100, K3 – 0110, K4 – 1111, K5 – 0011, K6 – 1111
(1001(9) * 1101(13))(mod 17) = 1111(15)
(1100(12) + 1100(12))(mod 16) = 1000(8)
(1010(10) + 0110(6))(mod 16) = 0000(0)
(1100(12) * 1111(15))(mod 17) = 1010(10)
(1111(15) ^ 0000(0)) = 1111(15)
(1000(8) ^ 1010(10)) = 0010(2)
(1111(15) * 0011(3))(mod 17) = 1011(11)
(0010(2) + 1011(11))(mod 16) = 1101(13)
(1101(13) * 1111(15))(mod 17) = 1000(8)
(1011(11) + 1000(8))(mod 16) = 0011(3)
(1000(8) ^ 1111(15)) = 0111(7)
(1000(8) ^ 0000(0)) = 1000(8)
(0011(3) ^ 1000(8)) = 1011(11)
(0011(3) ^ 1010(10)) = 1001(9)
Round 1 Output: 0111 1011 1000 1001 (Step 12 and Step 13 results are interchanged)
Round 2: From Round 1 output: X1 – 0111, X2 – 1011, X3 – 1000, X4 – 1001 From the table above: K1 – 0101, K2 – 1001, K3 – 0001, K4 – 1011, K5 – 1100, K6 – 1111 Round 2 Output: 0110 0110 1110 1100 (Step 12 and Step 13 results are interchanged)
From Round 1 output: X1 – 0111, X2 – 1011, X3 – 1000, X4 – 1001
From the table above: K1 – 0101, K2 – 1001, K3 – 0001, K4 – 1011, K5 – 1100, K6 – 1111
Round 2 Output: 0110 0110 1110 1100 (Step 12 and Step 13 results are interchanged)
Round 3: From Round 2 Output: X1 – 0110, X2 – 0110, X3 – 1110, X4 – 1100 From the table above: K1 – 1101, K2 – 0110, K3 – 0111, K4 – 0111, K5 – 1111, K6 – 0011 Round 3 Output: 0100 1110 1011 0010 (Step 12 and Step 13 results are interchanged)
From Round 2 Output: X1 – 0110, X2 – 0110, X3 – 1110, X4 – 1100
From the table above: K1 – 1101, K2 – 0110, K3 – 0111, K4 – 0111, K5 – 1111, K6 – 0011
Round 3 Output: 0100 1110 1011 0010 (Step 12 and Step 13 results are interchanged)
Round 4: From Round 3 Output: X1 – 0100, X2 – 1110, X3 – 1011, X4 – 0010 From the table above: K1 – 1111, K2 – 0101, K3 – 1001, K4 – 1101, K5 – 1100, K6 – 0110 Round 4 Output: 0011 1110 1110 0100 (Step 12 and Step 13 results are interchanged)
From Round 3 Output: X1 – 0100, X2 – 1110, X3 – 1011, X4 – 0010
From the table above: K1 – 1111, K2 – 0101, K3 – 1001, K4 – 1101, K5 – 1100, K6 – 0110
Round 4 Output: 0011 1110 1110 0100 (Step 12 and Step 13 results are interchanged)
Round 4.5: From Round 4 Output: X1 – 0011, X2 – 1110, X3 – 1110, X4 – 0100 From the table above: K1 – 1111, K2 – 1101, K3 – 0110, K4 – 0111 Round 4.5 Output: 1011 1011 0100 1011 (Step 2 and Step 3 results are not interchanged)
From Round 4 Output: X1 – 0011, X2 – 1110, X3 – 1110, X4 – 0100
From the table above: K1 – 1111, K2 – 1101, K3 – 0110, K4 – 0111
Round 4.5 Output: 1011 1011 0100 1011 (Step 2 and Step 3 results are not interchanged)
(0011(3) * 1111(15))(mod 17) = 1011(11)
(1110(14) + 1101(13))(mod 16) = 1011(11)
(1110(14) + 0110(6))(mod 16) = 0100(4)
(0100(4) * 0111(7))(mod 17) = 1011(11)
Final Ciphertext is 1011 1011 0100 1011
NOTE: For every round except the final transformation, a swap occurs, and the input is given to the next round
virenp2000
cryptography
Algorithms
Articles
Technical Scripter
cryptography
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Time Complexity and Space Complexity
SQL Interview Questions | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 431,
"s": 52,
"text": "In cryptography, block ciphers are very important in the designing of many cryptographic algorithms and are widely used to encrypt the bulk of data in chunks. By chunks, it means that the cipher takes a fixed size of the plaintext in the encryption process and generates a fixed size ciphertext using a fixed-length key. An algorithm’s strength is determined by its key length. "
},
{
"code": null,
"e": 533,
"s": 431,
"text": "The Simplified International Data Encryption Algorithm (IDEA) is a symmetric key block cipher that: "
},
{
"code": null,
"e": 578,
"s": 533,
"text": "uses a fixed-length plaintext of 16 bits and"
},
{
"code": null,
"e": 619,
"s": 578,
"text": "encrypts them in 4 chunks of 4 bits each"
},
{
"code": null,
"e": 650,
"s": 619,
"text": "to produce 16 bits ciphertext."
},
{
"code": null,
"e": 689,
"s": 650,
"text": "The length of the key used is 32 bits."
},
{
"code": null,
"e": 743,
"s": 689,
"text": "The key is also divided into 8 blocks of 4 bits each."
},
{
"code": null,
"e": 908,
"s": 743,
"text": "This algorithm involves a series of 4 identical complete rounds and 1 half-round. Each complete round involves a series of 14 steps that includes operations like: "
},
{
"code": null,
"e": 920,
"s": 908,
"text": "Bitwise XOR"
},
{
"code": null,
"e": 937,
"s": 920,
"text": "Addition modulo "
},
{
"code": null,
"e": 962,
"s": 937,
"text": "Multiplication modulo +1"
},
{
"code": null,
"e": 1342,
"s": 962,
"text": "After 4 complete rounds, the final “half-round” consists of only the first 4 out of the 14 steps previously used in the full rounds. To perform these rounds, each binary notation must be converted to its equivalent decimal notation, perform the operation and the result obtained should be converted back to the binary representation for the final result of that particular step. "
},
{
"code": null,
"e": 1733,
"s": 1342,
"text": "Key Schedule: 6 subkeys of 4 bits out of the 8 subkeys are used in each complete round, while 4 are used in the half-round. So, 4.5 rounds require 28 subkeys. The given key, ‘K’, directly gives the first 8 subkeys. By rotating the main key left by 6 bits between each group of 8, further groups of 8 subkeys are created, implying less than one rotation per round for the key (3 rotations). "
},
{
"code": null,
"e": 1764,
"s": 1737,
"text": "* denotes a shift of bits "
},
{
"code": null,
"e": 1797,
"s": 1764,
"text": "Notations used in the 14 steps: "
},
{
"code": null,
"e": 2174,
"s": 1799,
"text": "The 16-bit plaintext can be represented as X1 || X2 || X3 || X4, each of size 4 bits. The 32-bit key is broken into 8 subkeys denoted as K1 || K2 || K3 || K4 || K5 || K6 || K7 || K8, again of size 4 bits each. Each round of 14 steps uses the three algebraic operation-Addition modulo (2^4), Multiplication modulo (2^4)+1 and Bitwise XOR. The steps involved are as follows: "
},
{
"code": null,
"e": 2347,
"s": 2174,
"text": "X1 * K1X2 + K2X3 + K3X4 * K4Step 1 ^ Step 3Step 2 ^ Step 4Step 5 * K5Step 6 + Step 7Step 8 * K6Step 7 + Step 9Step 1 ^ Step 9Step 3 ^ Step 9Step 2 ^ Step 10Step 4 ^ Step 10"
},
{
"code": null,
"e": 2355,
"s": 2347,
"text": "X1 * K1"
},
{
"code": null,
"e": 2363,
"s": 2355,
"text": "X2 + K2"
},
{
"code": null,
"e": 2371,
"s": 2363,
"text": "X3 + K3"
},
{
"code": null,
"e": 2379,
"s": 2371,
"text": "X4 * K4"
},
{
"code": null,
"e": 2395,
"s": 2379,
"text": "Step 1 ^ Step 3"
},
{
"code": null,
"e": 2411,
"s": 2395,
"text": "Step 2 ^ Step 4"
},
{
"code": null,
"e": 2423,
"s": 2411,
"text": "Step 5 * K5"
},
{
"code": null,
"e": 2439,
"s": 2423,
"text": "Step 6 + Step 7"
},
{
"code": null,
"e": 2451,
"s": 2439,
"text": "Step 8 * K6"
},
{
"code": null,
"e": 2467,
"s": 2451,
"text": "Step 7 + Step 9"
},
{
"code": null,
"e": 2483,
"s": 2467,
"text": "Step 1 ^ Step 9"
},
{
"code": null,
"e": 2499,
"s": 2483,
"text": "Step 3 ^ Step 9"
},
{
"code": null,
"e": 2516,
"s": 2499,
"text": "Step 2 ^ Step 10"
},
{
"code": null,
"e": 2533,
"s": 2516,
"text": "Step 4 ^ Step 10"
},
{
"code": null,
"e": 2839,
"s": 2533,
"text": "The input to the next round is Step 11 || Step 13 || Step 12 || Step 14, which becomes X1 || X2 || X3 || X4. This swap between 12 and 13 takes place after each complete round, except the last complete round (4th round), where the input to the final half round is Step 11 || Step 12 || Step 13 || Step 14. "
},
{
"code": null,
"e": 2898,
"s": 2839,
"text": "After last complete round, the half-round is as follows: "
},
{
"code": null,
"e": 2927,
"s": 2898,
"text": "X1 * K1X2 + K2X3 + K3X4 * K4"
},
{
"code": null,
"e": 2935,
"s": 2927,
"text": "X1 * K1"
},
{
"code": null,
"e": 2943,
"s": 2935,
"text": "X2 + K2"
},
{
"code": null,
"e": 2951,
"s": 2943,
"text": "X3 + K3"
},
{
"code": null,
"e": 2959,
"s": 2951,
"text": "X4 * K4"
},
{
"code": null,
"e": 3018,
"s": 2959,
"text": "The final output is obtained by concatenating the blocks. "
},
{
"code": null,
"e": 3029,
"s": 3018,
"text": "Example: "
},
{
"code": null,
"e": 3138,
"s": 3029,
"text": "Key: 1101 1100 0110 1111 0011 1111 0101 1001 \nPlaintext: 1001 1100 1010 1100\nCiphertext: 1011 1011 0100 1011"
},
{
"code": null,
"e": 3270,
"s": 3138,
"text": "Explanation: The explanation is only for 1st complete round (the remaining can be implemented similarly) and the last half-round. "
},
{
"code": null,
"e": 3433,
"s": 3270,
"text": "Round 1: From the plaintext: X1 – 1001, X2 – 1100, X3 – 1010, X4 – 1100 From the table above: K1 – 1101, K2 – 1100, K3 – 0110, K4 – 1111, K5 – 0011, K6 – 1111 "
},
{
"code": null,
"e": 3498,
"s": 3433,
"text": "From the plaintext: X1 – 1001, X2 – 1100, X3 – 1010, X4 – 1100 "
},
{
"code": null,
"e": 3587,
"s": 3498,
"text": "From the table above: K1 – 1101, K2 – 1100, K3 – 0110, K4 – 1111, K5 – 0011, K6 – 1111 "
},
{
"code": null,
"e": 4094,
"s": 3589,
"text": "(1001(9) * 1101(13))(mod 17) = 1111(15)\n(1100(12) + 1100(12))(mod 16) = 1000(8)\n(1010(10) + 0110(6))(mod 16) = 0000(0)\n(1100(12) * 1111(15))(mod 17) = 1010(10)\n(1111(15) ^ 0000(0)) = 1111(15)\n(1000(8) ^ 1010(10)) = 0010(2)\n(1111(15) * 0011(3))(mod 17) = 1011(11)\n(0010(2) + 1011(11))(mod 16) = 1101(13)\n(1101(13) * 1111(15))(mod 17) = 1000(8)\n(1011(11) + 1000(8))(mod 16) = 0011(3)\n(1000(8) ^ 1111(15)) = 0111(7)\n(1000(8) ^ 0000(0)) = 1000(8)\n(0011(3) ^ 1000(8)) = 1011(11)\n(0011(3) ^ 1010(10)) = 1001(9)"
},
{
"code": null,
"e": 4179,
"s": 4096,
"text": "Round 1 Output: 0111 1011 1000 1001 (Step 12 and Step 13 results are interchanged)"
},
{
"code": null,
"e": 4424,
"s": 4179,
"text": "Round 2: From Round 1 output: X1 – 0111, X2 – 1011, X3 – 1000, X4 – 1001 From the table above: K1 – 0101, K2 – 1001, K3 – 0001, K4 – 1011, K5 – 1100, K6 – 1111 Round 2 Output: 0110 0110 1110 1100 (Step 12 and Step 13 results are interchanged)"
},
{
"code": null,
"e": 4490,
"s": 4424,
"text": "From Round 1 output: X1 – 0111, X2 – 1011, X3 – 1000, X4 – 1001 "
},
{
"code": null,
"e": 4579,
"s": 4490,
"text": "From the table above: K1 – 0101, K2 – 1001, K3 – 0001, K4 – 1011, K5 – 1100, K6 – 1111 "
},
{
"code": null,
"e": 4662,
"s": 4579,
"text": "Round 2 Output: 0110 0110 1110 1100 (Step 12 and Step 13 results are interchanged)"
},
{
"code": null,
"e": 4907,
"s": 4662,
"text": "Round 3: From Round 2 Output: X1 – 0110, X2 – 0110, X3 – 1110, X4 – 1100 From the table above: K1 – 1101, K2 – 0110, K3 – 0111, K4 – 0111, K5 – 1111, K6 – 0011 Round 3 Output: 0100 1110 1011 0010 (Step 12 and Step 13 results are interchanged)"
},
{
"code": null,
"e": 4973,
"s": 4907,
"text": "From Round 2 Output: X1 – 0110, X2 – 0110, X3 – 1110, X4 – 1100 "
},
{
"code": null,
"e": 5062,
"s": 4973,
"text": "From the table above: K1 – 1101, K2 – 0110, K3 – 0111, K4 – 0111, K5 – 1111, K6 – 0011 "
},
{
"code": null,
"e": 5145,
"s": 5062,
"text": "Round 3 Output: 0100 1110 1011 0010 (Step 12 and Step 13 results are interchanged)"
},
{
"code": null,
"e": 5390,
"s": 5145,
"text": "Round 4: From Round 3 Output: X1 – 0100, X2 – 1110, X3 – 1011, X4 – 0010 From the table above: K1 – 1111, K2 – 0101, K3 – 1001, K4 – 1101, K5 – 1100, K6 – 0110 Round 4 Output: 0011 1110 1110 0100 (Step 12 and Step 13 results are interchanged)"
},
{
"code": null,
"e": 5456,
"s": 5390,
"text": "From Round 3 Output: X1 – 0100, X2 – 1110, X3 – 1011, X4 – 0010 "
},
{
"code": null,
"e": 5545,
"s": 5456,
"text": "From the table above: K1 – 1111, K2 – 0101, K3 – 1001, K4 – 1101, K5 – 1100, K6 – 0110 "
},
{
"code": null,
"e": 5628,
"s": 5545,
"text": "Round 4 Output: 0011 1110 1110 0100 (Step 12 and Step 13 results are interchanged)"
},
{
"code": null,
"e": 5859,
"s": 5628,
"text": "Round 4.5: From Round 4 Output: X1 – 0011, X2 – 1110, X3 – 1110, X4 – 0100 From the table above: K1 – 1111, K2 – 1101, K3 – 0110, K4 – 0111 Round 4.5 Output: 1011 1011 0100 1011 (Step 2 and Step 3 results are not interchanged) "
},
{
"code": null,
"e": 5925,
"s": 5859,
"text": "From Round 4 Output: X1 – 0011, X2 – 1110, X3 – 1110, X4 – 0100 "
},
{
"code": null,
"e": 5992,
"s": 5925,
"text": "From the table above: K1 – 1111, K2 – 1101, K3 – 0110, K4 – 0111 "
},
{
"code": null,
"e": 6080,
"s": 5992,
"text": "Round 4.5 Output: 1011 1011 0100 1011 (Step 2 and Step 3 results are not interchanged)"
},
{
"code": null,
"e": 6244,
"s": 6084,
"text": "(0011(3) * 1111(15))(mod 17) = 1011(11)\n(1110(14) + 1101(13))(mod 16) = 1011(11)\n(1110(14) + 0110(6))(mod 16) = 0100(4)\n(0100(4) * 0111(7))(mod 17) = 1011(11) "
},
{
"code": null,
"e": 6286,
"s": 6246,
"text": "Final Ciphertext is 1011 1011 0100 1011"
},
{
"code": null,
"e": 6398,
"s": 6286,
"text": "NOTE: For every round except the final transformation, a swap occurs, and the input is given to the next round "
},
{
"code": null,
"e": 6411,
"s": 6400,
"text": "virenp2000"
},
{
"code": null,
"e": 6424,
"s": 6411,
"text": "cryptography"
},
{
"code": null,
"e": 6435,
"s": 6424,
"text": "Algorithms"
},
{
"code": null,
"e": 6444,
"s": 6435,
"text": "Articles"
},
{
"code": null,
"e": 6463,
"s": 6444,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6476,
"s": 6463,
"text": "cryptography"
},
{
"code": null,
"e": 6487,
"s": 6476,
"text": "Algorithms"
},
{
"code": null,
"e": 6585,
"s": 6487,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6623,
"s": 6585,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6691,
"s": 6623,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 6718,
"s": 6691,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 6761,
"s": 6718,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 6828,
"s": 6761,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 6878,
"s": 6828,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 6925,
"s": 6878,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 6961,
"s": 6925,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 6998,
"s": 6961,
"text": "Time Complexity and Space Complexity"
}
]
|
Find the Largest Top 10 Files and Directories On a Linux | Sometimes, it becomes important to find which files or directories are ingesting up, all of your disk area on a Linux. Similarly, we should be able to discover a particular directory location on file system such as /tmp/ or /var/ or /domestic/. This article will help you to use Unix and Linux commands for finding the most important or biggest files or directories on the file systems.
Although, there is no shortcut command which is available to discover the largest documents/directories on a Linux/UNIX/BSD file system but there is a possibility which we will be showcasing you about.
By aggregating the following three commands (the use of pipes) can help you easily discover a list of largest documents on a Linux machine.
du command : It estimates file space usage
sort command : Sort lines of text files or given input data
head command : Output the first part of files i.e. to display first 10 largest file
find command : It Searches file on Linux machine
Use the following command to find the largest Top 10 files and directories on a Linux system –
$ sudo du -a /var | sort -n -r | head -n 10
The sample output should be like this –
1128132 /var
779176 /var/cache
629292 /var/cache/apt
541020 /var/cache/apt/archives
327212 /var/lib
172180 /var/lib/apt
172024 /var/lib/apt/lists
130084 /var/cache/apt-xapian-index
130080 /var/cache/apt-xapian-index/index.1
87556 /var/lib/dpkg
To see human readable output, use the following command –
$ du -hsx * | sort -rh | head -10
The sample output should be like this –
4.4G Desktop
3.8G Downloads
149M en-GB
146M Apache_OpenOffice_4.1.1_Linux_x86-64_install-deb_en-GB.tar.gz
95M scala-2.11.4.deb
20M gawk-4.1.1
4.5M linux-dash
3.9M yii-1.1.13.e9e4a0.tar.gz.1
3.9M yii-1.1.13.e9e4a0.tar.gz
The above command can be better understood with the following explanations –
du command -h option : Display sizes in human readable format (e.g., 1K, 234M, 2G).
du command -s option : It shows only a total for each argument (summary).
du command -x option : Skip directories on different file systems.
sort command -r option : Reverse the result of comparisons.
sort command -h option : It compares human readable numbers. This is GNU sort specific option only.
head command -10 OR -n 10 option : It shows the first 10 lines.
The above command will work for GNU/sort which is installed on a Linux, Other Unix like operating systems uses the following command –
$find /path/to/dir/ -printf '%s %p\n'| sort -nr | head -10
$find . -printf '%s %p\n'| sort -nr | head -10
The sample output should be like this –
185016320 ./Desktop/gdb-7.9.tar
153300495 ./Downloads/apache-storm-1.0.0.tar.gz
152847886 ./Apache_OpenOffice_4.1.1_Linux_x86-64_install-deb_en-GB.tar.gz
98756608 ./scala-2.11.4.deb
96477184 ./.cache/chromium/Default/Cache/data_3
88088576 ./.cache/google-chrome/Default/Cache/data_3
66586000 ./Downloads/Apache24.zip
61919701 ./Downloads/apache-storm-1.0.0/external/flux/flux-examples-1.0.0.jar
55678503 ./Downloads/apache-storm-1.0.0/examples/storm-starter/storm-starter-topologies-1.0.0.jar
To skip directories and only display files, use the following command
$ find /path/to/search/ -type f -printf '%s %p\n'| sort -nr | head -10
or
$ find /path/to/search/ -type f -iname "*.mp4" -printf '%s %p\n'| sort -nr | head -10
Use the following bash shell commands as shown below
$ alias ducks='du -cks * | sort -rn | head'
Use the following command to get top 10 files/dirs eating your disk space-
$ ducks
The sample output should be like this –
5994400 total
4559508 Desktop
673712 Downloads
151596 en-GB
149268 Apache_OpenOffice_4.1.1_Linux_x86-64_install-deb_en-GB.tar.gz
96444 scala-2.11.4.deb
20024 gawk-4.1.1
4544 linux-dash
3952 yii-1.1.13.e9e4a0.tar.gz.1
Congratulations! Now, you know “How to find The Largest Top 10 Files and Directories On a Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading! | [
{
"code": null,
"e": 1574,
"s": 1187,
"text": "Sometimes, it becomes important to find which files or directories are ingesting up, all of your disk area on a Linux. Similarly, we should be able to discover a particular directory location on file system such as /tmp/ or /var/ or /domestic/. This article will help you to use Unix and Linux commands for finding the most important or biggest files or directories on the file systems."
},
{
"code": null,
"e": 1776,
"s": 1574,
"text": "Although, there is no shortcut command which is available to discover the largest documents/directories on a Linux/UNIX/BSD file system but there is a possibility which we will be showcasing you about."
},
{
"code": null,
"e": 1916,
"s": 1776,
"text": "By aggregating the following three commands (the use of pipes) can help you easily discover a list of largest documents on a Linux machine."
},
{
"code": null,
"e": 1959,
"s": 1916,
"text": "du command : It estimates file space usage"
},
{
"code": null,
"e": 2019,
"s": 1959,
"text": "sort command : Sort lines of text files or given input data"
},
{
"code": null,
"e": 2103,
"s": 2019,
"text": "head command : Output the first part of files i.e. to display first 10 largest file"
},
{
"code": null,
"e": 2152,
"s": 2103,
"text": "find command : It Searches file on Linux machine"
},
{
"code": null,
"e": 2247,
"s": 2152,
"text": "Use the following command to find the largest Top 10 files and directories on a Linux system –"
},
{
"code": null,
"e": 2291,
"s": 2247,
"text": "$ sudo du -a /var | sort -n -r | head -n 10"
},
{
"code": null,
"e": 2331,
"s": 2291,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 2635,
"s": 2331,
"text": "1128132 /var\n779176 /var/cache\n629292 /var/cache/apt\n541020 /var/cache/apt/archives\n327212 /var/lib\n172180 /var/lib/apt\n172024 /var/lib/apt/lists\n130084 /var/cache/apt-xapian-index\n130080 /var/cache/apt-xapian-index/index.1\n87556 /var/lib/dpkg"
},
{
"code": null,
"e": 2693,
"s": 2635,
"text": "To see human readable output, use the following command –"
},
{
"code": null,
"e": 2727,
"s": 2693,
"text": "$ du -hsx * | sort -rh | head -10"
},
{
"code": null,
"e": 2767,
"s": 2727,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 3005,
"s": 2767,
"text": "4.4G Desktop\n3.8G Downloads\n149M en-GB\n146M Apache_OpenOffice_4.1.1_Linux_x86-64_install-deb_en-GB.tar.gz\n95M scala-2.11.4.deb\n20M gawk-4.1.1\n4.5M linux-dash\n3.9M yii-1.1.13.e9e4a0.tar.gz.1\n3.9M yii-1.1.13.e9e4a0.tar.gz"
},
{
"code": null,
"e": 3082,
"s": 3005,
"text": "The above command can be better understood with the following explanations –"
},
{
"code": null,
"e": 3166,
"s": 3082,
"text": "du command -h option : Display sizes in human readable format (e.g., 1K, 234M, 2G)."
},
{
"code": null,
"e": 3240,
"s": 3166,
"text": "du command -s option : It shows only a total for each argument (summary)."
},
{
"code": null,
"e": 3307,
"s": 3240,
"text": "du command -x option : Skip directories on different file systems."
},
{
"code": null,
"e": 3367,
"s": 3307,
"text": "sort command -r option : Reverse the result of comparisons."
},
{
"code": null,
"e": 3467,
"s": 3367,
"text": "sort command -h option : It compares human readable numbers. This is GNU sort specific option only."
},
{
"code": null,
"e": 3531,
"s": 3467,
"text": "head command -10 OR -n 10 option : It shows the first 10 lines."
},
{
"code": null,
"e": 3666,
"s": 3531,
"text": "The above command will work for GNU/sort which is installed on a Linux, Other Unix like operating systems uses the following command –"
},
{
"code": null,
"e": 3772,
"s": 3666,
"text": "$find /path/to/dir/ -printf '%s %p\\n'| sort -nr | head -10\n$find . -printf '%s %p\\n'| sort -nr | head -10"
},
{
"code": null,
"e": 3812,
"s": 3772,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 4305,
"s": 3812,
"text": "185016320 ./Desktop/gdb-7.9.tar\n153300495 ./Downloads/apache-storm-1.0.0.tar.gz\n152847886 ./Apache_OpenOffice_4.1.1_Linux_x86-64_install-deb_en-GB.tar.gz\n98756608 ./scala-2.11.4.deb\n96477184 ./.cache/chromium/Default/Cache/data_3\n88088576 ./.cache/google-chrome/Default/Cache/data_3\n66586000 ./Downloads/Apache24.zip\n61919701 ./Downloads/apache-storm-1.0.0/external/flux/flux-examples-1.0.0.jar\n55678503 ./Downloads/apache-storm-1.0.0/examples/storm-starter/storm-starter-topologies-1.0.0.jar"
},
{
"code": null,
"e": 4375,
"s": 4305,
"text": "To skip directories and only display files, use the following command"
},
{
"code": null,
"e": 4446,
"s": 4375,
"text": "$ find /path/to/search/ -type f -printf '%s %p\\n'| sort -nr | head -10"
},
{
"code": null,
"e": 4449,
"s": 4446,
"text": "or"
},
{
"code": null,
"e": 4535,
"s": 4449,
"text": "$ find /path/to/search/ -type f -iname \"*.mp4\" -printf '%s %p\\n'| sort -nr | head -10"
},
{
"code": null,
"e": 4588,
"s": 4535,
"text": "Use the following bash shell commands as shown below"
},
{
"code": null,
"e": 4632,
"s": 4588,
"text": "$ alias ducks='du -cks * | sort -rn | head'"
},
{
"code": null,
"e": 4707,
"s": 4632,
"text": "Use the following command to get top 10 files/dirs eating your disk space-"
},
{
"code": null,
"e": 4715,
"s": 4707,
"text": "$ ducks"
},
{
"code": null,
"e": 4755,
"s": 4715,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 5003,
"s": 4755,
"text": "5994400 total\n4559508 Desktop\n673712 Downloads\n151596 en-GB\n149268 Apache_OpenOffice_4.1.1_Linux_x86-64_install-deb_en-GB.tar.gz\n96444 scala-2.11.4.deb\n20024 gawk-4.1.1\n4544 linux-dash\n3952 yii-1.1.13.e9e4a0.tar.gz.1"
},
{
"code": null,
"e": 5186,
"s": 5003,
"text": "Congratulations! Now, you know “How to find The Largest Top 10 Files and Directories On a Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!"
}
]
|
Groovy - padRight() | Pad the String with the spaces appended to the right. This method has 2 different variants.
String padRight(Number numberOfCharacters) − Pad the String with the spaces appended to the right.
String padRight(Number numberOfCharacters) − Pad the String with the spaces appended to the right.
Syntax
String padRight(Number numberOfCharacters)
Parameters
numberOfCharacters − The number of characters to pad the string with.
Return Value − The new value of the string with the padded characters.
String padRight(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the right.
String padRight(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the right.
Syntax
String padRight(Number numberOfCharacters, String padding)
Parameters
numberOfCharacters − The number of characters to pad the string with.
numberOfCharacters − The number of characters to pad the string with.
Padding − The character to apply for the padding.
Padding − The character to apply for the padding.
Return Value − The new value of the string with the padded characters
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
String a = "Hello World";
println(a.padRight(14));
println(a.padRight(16));
println(a.padRight(16,'*'));
println(a.padRight(14,'*'));
}
}
When we run the above program, we will get the following result − | [
{
"code": null,
"e": 2464,
"s": 2372,
"text": "Pad the String with the spaces appended to the right. This method has 2 different variants."
},
{
"code": null,
"e": 2563,
"s": 2464,
"text": "String padRight(Number numberOfCharacters) − Pad the String with the spaces appended to the right."
},
{
"code": null,
"e": 2662,
"s": 2563,
"text": "String padRight(Number numberOfCharacters) − Pad the String with the spaces appended to the right."
},
{
"code": null,
"e": 2669,
"s": 2662,
"text": "Syntax"
},
{
"code": null,
"e": 2713,
"s": 2669,
"text": "String padRight(Number numberOfCharacters)\n"
},
{
"code": null,
"e": 2724,
"s": 2713,
"text": "Parameters"
},
{
"code": null,
"e": 2794,
"s": 2724,
"text": "numberOfCharacters − The number of characters to pad the string with."
},
{
"code": null,
"e": 2865,
"s": 2794,
"text": "Return Value − The new value of the string with the padded characters."
},
{
"code": null,
"e": 2992,
"s": 2865,
"text": "String padRight(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the right."
},
{
"code": null,
"e": 3119,
"s": 2992,
"text": "String padRight(Number numberOfCharacters, String padding) − Pad the String with the padding characters appended to the right."
},
{
"code": null,
"e": 3126,
"s": 3119,
"text": "Syntax"
},
{
"code": null,
"e": 3186,
"s": 3126,
"text": "String padRight(Number numberOfCharacters, String padding)\n"
},
{
"code": null,
"e": 3197,
"s": 3186,
"text": "Parameters"
},
{
"code": null,
"e": 3267,
"s": 3197,
"text": "numberOfCharacters − The number of characters to pad the string with."
},
{
"code": null,
"e": 3337,
"s": 3267,
"text": "numberOfCharacters − The number of characters to pad the string with."
},
{
"code": null,
"e": 3387,
"s": 3337,
"text": "Padding − The character to apply for the padding."
},
{
"code": null,
"e": 3437,
"s": 3387,
"text": "Padding − The character to apply for the padding."
},
{
"code": null,
"e": 3507,
"s": 3437,
"text": "Return Value − The new value of the string with the padded characters"
},
{
"code": null,
"e": 3561,
"s": 3507,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 3796,
"s": 3561,
"text": "class Example { \n static void main(String[] args) { \n String a = \"Hello World\"; \n\t\t\n println(a.padRight(14)); \n println(a.padRight(16)); \n println(a.padRight(16,'*')); \n println(a.padRight(14,'*')); \n } \n}"
}
]
|
Count characters in a string whose ASCII values are prime | 08 Mar, 2022
Given a string S. The task is to count and print the number of characters in the string whose ASCII values are prime.
Examples:
Input: S = “geeksforgeeks” Output : 3 ‘g’, ‘e’ and ‘k’ are the only characters whose ASCII values are prime i.e. 103, 101 and 107 respectively.
Input: S = “abcdefghijklmnopqrstuvwxyz” Output: 6
Approach: The idea is to generate all primes upto max ASCII value of character of string S using Sieve of Eratosthenes. Now, Iterate the string and get the ASCII value of each character. If the ASCII value is prime then increment the count. Finally, print the count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std;#define max_val 257 // Function to find prime characters in the stringint PrimeCharacters(string s){ // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } int count = 0; // Traverse all the characters for (int i = 0; i < s.length(); ++i) { if (prime[int(s[i])]) count++; } return count;} // Driver programint main(){ string S = "geeksforgeeks"; // print required answer cout << PrimeCharacters(S); return 0;}
// Java implementation of above approachclass Solution{static final int max_val=257; // Function to find prime characters in the Stringstatic int PrimeCharacters(String s){ // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[]= new boolean[max_val+1]; //initialize the value for(int i=0;i<=max_val;i++) prime[i]=true; // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } int count = 0; // Traverse all the characters for (int i = 0; i < s.length(); ++i) { if (prime[(int)(s.charAt(i))]) count++; } return count;} // Driver programpublic static void main(String args[]){ String S = "geeksforgeeks"; // print required answer System.out.print( PrimeCharacters(S)); }}//contributed by Arnab Kundu
# Python3 implementation of above approach from math import sqrt max_val = 257 # Function to find prime characters in the stringdef PrimeCharacters(s) : # USE SIEVE TO FIND ALL PRIME NUMBERS LESS # THAN OR EQUAL TO max_val # Create a Boolean array "prime[0..n]". A # value in prime[i] will finally be false # if i is Not a prime, else true. prime = [True] * (max_val + 1) # 0 and 1 are not primes prime[0] = False prime[1] = False for p in range(2, int(sqrt(max_val)) + 1) : # If prime[p] is not changed, then # it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(2*p ,max_val + 1, p) : prime[i] = False count = 0 # Traverse all the characters for i in range(len(s)) : if (prime[ord(s[i])]) : count += 1 return count # Driver programif __name__ == "__main__" : S = "geeksforgeeks"; # print required answer print(PrimeCharacters(S)) # This code is contributed by Ryuga
// C# implementation of above approachusing System;class GFG{ static readonly int max_val = 257; // Function to find prime characters in the Stringstatic int PrimeCharacters(String s){ // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. bool []prime = new bool[max_val + 1]; //initialize the value for(int i = 0; i <= max_val; i++) prime[i] = true; // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } int count = 0; // Traverse all the characters for (int i = 0; i < s.Length; ++i) { if (prime[(int)(s[i])]) count++; } return count; } // Driver Codepublic static void Main(){ String S = "geeksforgeeks"; // print required answer Console.Write( PrimeCharacters(S)); }} // This code is contributed by PrinciRaj1992
<script> // JavaScript implementation of above approach const max_val = 257; // Function to find prime characters in the String function PrimeCharacters(s) { // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. var prime = new Array(max_val + 1); //initialize the value for (var i = 0; i <= max_val; i++) prime[i] = true; // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (var p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] === true) { // Update all multiples of p for (var i = p * 2; i <= max_val; i += p) prime[i] = false; } } var count = 0; // Traverse all the characters for (var i = 0; i < s.length; ++i) { if (prime[s[i].charCodeAt(0)]) count++; } return count; } // Driver Code var S = "geeksforgeeks"; // print required answer document.write(PrimeCharacters(S)); // This code is contributed by rdtank. </script>
8
Time Complexity: O(max_val*log(log(max_val)))Auxiliary Space: O(max_val)
ankthon
andrew1234
princiraj1992
rdtank
arorakashish0911
singhh3010
ASCII
Prime Number
Strings
Strings
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Data Structure: Types, Classifications and Applications
Top 50 String Coding Problems for Interviews
String class in Java | Set 1
Return maximum occurring character in an input string
Naive algorithm for Pattern Searching
Print all the duplicates in the input string
Iterate over characters of a string in C++
Longest Common Prefix using Sorting
Vigenère Cipher
Tokenizing a string in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "Given a string S. The task is to count and print the number of characters in the string whose ASCII values are prime."
},
{
"code": null,
"e": 157,
"s": 146,
"text": "Examples: "
},
{
"code": null,
"e": 301,
"s": 157,
"text": "Input: S = “geeksforgeeks” Output : 3 ‘g’, ‘e’ and ‘k’ are the only characters whose ASCII values are prime i.e. 103, 101 and 107 respectively."
},
{
"code": null,
"e": 352,
"s": 301,
"text": "Input: S = “abcdefghijklmnopqrstuvwxyz” Output: 6 "
},
{
"code": null,
"e": 619,
"s": 352,
"text": "Approach: The idea is to generate all primes upto max ASCII value of character of string S using Sieve of Eratosthenes. Now, Iterate the string and get the ASCII value of each character. If the ASCII value is prime then increment the count. Finally, print the count."
},
{
"code": null,
"e": 671,
"s": 619,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 675,
"s": 671,
"text": "C++"
},
{
"code": null,
"e": 680,
"s": 675,
"text": "Java"
},
{
"code": null,
"e": 688,
"s": 680,
"text": "Python3"
},
{
"code": null,
"e": 691,
"s": 688,
"text": "C#"
},
{
"code": null,
"e": 702,
"s": 691,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std;#define max_val 257 // Function to find prime characters in the stringint PrimeCharacters(string s){ // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } int count = 0; // Traverse all the characters for (int i = 0; i < s.length(); ++i) { if (prime[int(s[i])]) count++; } return count;} // Driver programint main(){ string S = \"geeksforgeeks\"; // print required answer cout << PrimeCharacters(S); return 0;}",
"e": 1797,
"s": 702,
"text": null
},
{
"code": "// Java implementation of above approachclass Solution{static final int max_val=257; // Function to find prime characters in the Stringstatic int PrimeCharacters(String s){ // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[]= new boolean[max_val+1]; //initialize the value for(int i=0;i<=max_val;i++) prime[i]=true; // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } int count = 0; // Traverse all the characters for (int i = 0; i < s.length(); ++i) { if (prime[(int)(s.charAt(i))]) count++; } return count;} // Driver programpublic static void main(String args[]){ String S = \"geeksforgeeks\"; // print required answer System.out.print( PrimeCharacters(S)); }}//contributed by Arnab Kundu",
"e": 3027,
"s": 1797,
"text": null
},
{
"code": "# Python3 implementation of above approach from math import sqrt max_val = 257 # Function to find prime characters in the stringdef PrimeCharacters(s) : # USE SIEVE TO FIND ALL PRIME NUMBERS LESS # THAN OR EQUAL TO max_val # Create a Boolean array \"prime[0..n]\". A # value in prime[i] will finally be false # if i is Not a prime, else true. prime = [True] * (max_val + 1) # 0 and 1 are not primes prime[0] = False prime[1] = False for p in range(2, int(sqrt(max_val)) + 1) : # If prime[p] is not changed, then # it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(2*p ,max_val + 1, p) : prime[i] = False count = 0 # Traverse all the characters for i in range(len(s)) : if (prime[ord(s[i])]) : count += 1 return count # Driver programif __name__ == \"__main__\" : S = \"geeksforgeeks\"; # print required answer print(PrimeCharacters(S)) # This code is contributed by Ryuga",
"e": 4072,
"s": 3027,
"text": null
},
{
"code": "// C# implementation of above approachusing System;class GFG{ static readonly int max_val = 257; // Function to find prime characters in the Stringstatic int PrimeCharacters(String s){ // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. bool []prime = new bool[max_val + 1]; //initialize the value for(int i = 0; i <= max_val; i++) prime[i] = true; // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } int count = 0; // Traverse all the characters for (int i = 0; i < s.Length; ++i) { if (prime[(int)(s[i])]) count++; } return count; } // Driver Codepublic static void Main(){ String S = \"geeksforgeeks\"; // print required answer Console.Write( PrimeCharacters(S)); }} // This code is contributed by PrinciRaj1992",
"e": 5361,
"s": 4072,
"text": null
},
{
"code": "<script> // JavaScript implementation of above approach const max_val = 257; // Function to find prime characters in the String function PrimeCharacters(s) { // USE SIEVE TO FIND ALL PRIME NUMBERS LESS // THAN OR EQUAL TO max_val // Create a Boolean array \"prime[0..n]\". A // value in prime[i] will finally be false // if i is Not a prime, else true. var prime = new Array(max_val + 1); //initialize the value for (var i = 0; i <= max_val; i++) prime[i] = true; // 0 and 1 are not primes prime[0] = false; prime[1] = false; for (var p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] === true) { // Update all multiples of p for (var i = p * 2; i <= max_val; i += p) prime[i] = false; } } var count = 0; // Traverse all the characters for (var i = 0; i < s.length; ++i) { if (prime[s[i].charCodeAt(0)]) count++; } return count; } // Driver Code var S = \"geeksforgeeks\"; // print required answer document.write(PrimeCharacters(S)); // This code is contributed by rdtank. </script>",
"e": 6648,
"s": 5361,
"text": null
},
{
"code": null,
"e": 6650,
"s": 6648,
"text": "8"
},
{
"code": null,
"e": 6725,
"s": 6652,
"text": "Time Complexity: O(max_val*log(log(max_val)))Auxiliary Space: O(max_val)"
},
{
"code": null,
"e": 6733,
"s": 6725,
"text": "ankthon"
},
{
"code": null,
"e": 6744,
"s": 6733,
"text": "andrew1234"
},
{
"code": null,
"e": 6758,
"s": 6744,
"text": "princiraj1992"
},
{
"code": null,
"e": 6765,
"s": 6758,
"text": "rdtank"
},
{
"code": null,
"e": 6782,
"s": 6765,
"text": "arorakashish0911"
},
{
"code": null,
"e": 6793,
"s": 6782,
"text": "singhh3010"
},
{
"code": null,
"e": 6799,
"s": 6793,
"text": "ASCII"
},
{
"code": null,
"e": 6812,
"s": 6799,
"text": "Prime Number"
},
{
"code": null,
"e": 6820,
"s": 6812,
"text": "Strings"
},
{
"code": null,
"e": 6828,
"s": 6820,
"text": "Strings"
},
{
"code": null,
"e": 6841,
"s": 6828,
"text": "Prime Number"
},
{
"code": null,
"e": 6939,
"s": 6841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7003,
"s": 6939,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 7048,
"s": 7003,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 7077,
"s": 7048,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 7131,
"s": 7077,
"text": "Return maximum occurring character in an input string"
},
{
"code": null,
"e": 7169,
"s": 7131,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 7214,
"s": 7169,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 7257,
"s": 7214,
"text": "Iterate over characters of a string in C++"
},
{
"code": null,
"e": 7293,
"s": 7257,
"text": "Longest Common Prefix using Sorting"
},
{
"code": null,
"e": 7310,
"s": 7293,
"text": "Vigenère Cipher"
}
]
|
PostgreSQL – Export PostgreSQL Table to CSV file | 28 Feb, 2021
In this article will discuss we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine.
Use the below syntax to copy a PostgreSQL table from the server itself:
Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER;
Note: If you have permission to perform a read/write operation on the server-side then use this command.
Example:
First, let’s create a table with columns id, first_name, last_name, and email to the database:
CREATE TABLE students(
id SERIAL PRIMARY KEY,
first_name VARCHAR,
last_name VARCHAR,
email VARCHAR UNIQUE
);
Let’s insert some data into our students table:
INSERT INTO students(first_name, last_name, email)
VALUES('Virender', 'Sehwag', '[email protected]'),
('Hardik', 'Pandiya', '[email protected]'),
('Shreyas', 'Iyer', '[email protected]'),
('Rishabh', 'Pant', '[email protected]');
Now check the data in the table:
SELECT * FROM students;
Output:
Now export the above table as a CSV file.
COPY students TO '/tmp/student1.csv' CSV HEADER;
Note: Make sure that the path that you specify should have read/write permission.
If everything works fine then it should look like this:
The CSV file would look like below:
We can also specify columns that we want to export or write a query for the data.
COPY (SELECT first_name FROM students) TO '/tmp/student.csv' CSV HEADER;
Output:
The CSV file would look like below:
CSV File
Use the below syntax for client-side export of CSV file:
Syntax: \copy Table_Name to 'Path/filename.csv' CSV HEADER
If you do not have permission to perform a read/write operation on the server-side and want to copy the table to the client-side machine then use this command.
Let’s use the students table here also.
Execute the below command to export the table to a CSV file.
\copy students to '/tmp/students.csv' CSV HEADER
Output:
The CSV file would look like below:
You can give a query to select data here also.
Picked
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - EXISTS Operator
PostgreSQL - SELECT DISTINCT clause | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2021"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "In this article will discuss we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine."
},
{
"code": null,
"e": 281,
"s": 209,
"text": "Use the below syntax to copy a PostgreSQL table from the server itself:"
},
{
"code": null,
"e": 340,
"s": 281,
"text": "Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER;"
},
{
"code": null,
"e": 445,
"s": 340,
"text": "Note: If you have permission to perform a read/write operation on the server-side then use this command."
},
{
"code": null,
"e": 454,
"s": 445,
"text": "Example:"
},
{
"code": null,
"e": 549,
"s": 454,
"text": "First, let’s create a table with columns id, first_name, last_name, and email to the database:"
},
{
"code": null,
"e": 670,
"s": 549,
"text": "CREATE TABLE students(\n id SERIAL PRIMARY KEY,\n first_name VARCHAR,\n last_name VARCHAR,\n email VARCHAR UNIQUE\n);"
},
{
"code": null,
"e": 718,
"s": 670,
"text": "Let’s insert some data into our students table:"
},
{
"code": null,
"e": 977,
"s": 718,
"text": "INSERT INTO students(first_name, last_name, email)\nVALUES('Virender', 'Sehwag', '[email protected]'),\n ('Hardik', 'Pandiya', '[email protected]'),\n ('Shreyas', 'Iyer', '[email protected]'),\n ('Rishabh', 'Pant', '[email protected]');"
},
{
"code": null,
"e": 1010,
"s": 977,
"text": "Now check the data in the table:"
},
{
"code": null,
"e": 1034,
"s": 1010,
"text": "SELECT * FROM students;"
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Output:"
},
{
"code": null,
"e": 1084,
"s": 1042,
"text": "Now export the above table as a CSV file."
},
{
"code": null,
"e": 1133,
"s": 1084,
"text": "COPY students TO '/tmp/student1.csv' CSV HEADER;"
},
{
"code": null,
"e": 1215,
"s": 1133,
"text": "Note: Make sure that the path that you specify should have read/write permission."
},
{
"code": null,
"e": 1271,
"s": 1215,
"text": "If everything works fine then it should look like this:"
},
{
"code": null,
"e": 1307,
"s": 1271,
"text": "The CSV file would look like below:"
},
{
"code": null,
"e": 1389,
"s": 1307,
"text": "We can also specify columns that we want to export or write a query for the data."
},
{
"code": null,
"e": 1462,
"s": 1389,
"text": "COPY (SELECT first_name FROM students) TO '/tmp/student.csv' CSV HEADER;"
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "Output:"
},
{
"code": null,
"e": 1506,
"s": 1470,
"text": "The CSV file would look like below:"
},
{
"code": null,
"e": 1515,
"s": 1506,
"text": "CSV File"
},
{
"code": null,
"e": 1572,
"s": 1515,
"text": "Use the below syntax for client-side export of CSV file:"
},
{
"code": null,
"e": 1631,
"s": 1572,
"text": "Syntax: \\copy Table_Name to 'Path/filename.csv' CSV HEADER"
},
{
"code": null,
"e": 1791,
"s": 1631,
"text": "If you do not have permission to perform a read/write operation on the server-side and want to copy the table to the client-side machine then use this command."
},
{
"code": null,
"e": 1831,
"s": 1791,
"text": "Let’s use the students table here also."
},
{
"code": null,
"e": 1892,
"s": 1831,
"text": "Execute the below command to export the table to a CSV file."
},
{
"code": null,
"e": 1941,
"s": 1892,
"text": "\\copy students to '/tmp/students.csv' CSV HEADER"
},
{
"code": null,
"e": 1949,
"s": 1941,
"text": "Output:"
},
{
"code": null,
"e": 1985,
"s": 1949,
"text": "The CSV file would look like below:"
},
{
"code": null,
"e": 2032,
"s": 1985,
"text": "You can give a query to select data here also."
},
{
"code": null,
"e": 2039,
"s": 2032,
"text": "Picked"
},
{
"code": null,
"e": 2065,
"s": 2039,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 2076,
"s": 2065,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2174,
"s": 2076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2212,
"s": 2174,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 2242,
"s": 2212,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 2266,
"s": 2242,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 2286,
"s": 2266,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 2314,
"s": 2286,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 2347,
"s": 2314,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 2374,
"s": 2347,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 2394,
"s": 2374,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 2423,
"s": 2394,
"text": "PostgreSQL - EXISTS Operator"
}
]
|
Most similar string | 17 Jul, 2021
Given a string str and an array of strings arr[] of size N, the task is to print a string from arr[], which has maximum count of matching characters with str.
Examples:
Input: str = “vikas”, N = 3, arr[] = [“preeti”, “khusbu”, “katherina”] Output: “katherina” Explanation: Number of similar characters between Str and each string in D[ ] are, “preeti” = 1 “khusbu” = 2 “katherina” = 3 Hence, “katherina” has maximum matching characters.
Input: str = “gfg”, N = 3, arr[] = [“goal”, “fog”, “abc”] Output: “fog” Explanation:Number of similar characters between Str and each string in D[ ] are, “goal” = 1 “fog” = 2 “abc” = 0 Hence, “fog” has maximum matching characters.
Approach: The idea is to consider each string of array arr[], and compare each of its character with the given string str. Keep track of the maximum number of matching characters and corresponding string. Also, make sure to remove the duplicates from each string. Below are the steps:
Create a variable maxVal and a variable val, to keep track of maximum number of matching characters and corresponding string respectively.Traverse the array arr[] and remove duplicates from each string. Also, remove duplicates from Str.For each string of arr[], compare it with the given string str, and count the number of matching characters.Keep updating maxVal with the maximum number of matching characters and val with corresponding string.Finally, print the value of val after the above operations.
Create a variable maxVal and a variable val, to keep track of maximum number of matching characters and corresponding string respectively.
Traverse the array arr[] and remove duplicates from each string. Also, remove duplicates from Str.
For each string of arr[], compare it with the given string str, and count the number of matching characters.
Keep updating maxVal with the maximum number of matching characters and val with corresponding string.
Finally, print the value of val after the above operations.
Below is the implementation of the above approach:
Java
Python3
C#
// Java program for the above approachimport java.util.*;import java.io.*; public class GFG { // Function that print string which // has maximum similar characters private static void maxMatchingChar(ArrayList<String> list, int n, char ch[]) { String val = ""; int maxVal = Integer.MIN_VALUE; for (String s : list) { // Count matching characters int matchingchar = matchingChar( s.toLowerCase(), ch); // Update maxVal if needed if (matchingchar > maxVal) { maxVal = matchingchar; val = s; } } System.out.print(val + " "); } // Function that returns the count // of number of matching characters private static int matchingChar( String s, char[] ch) { int freq = 0, c = ch.length; // Traverse the character array for (int i = 0; i < c; i++) { // If character matches // then increment the count if (s.contains( String.valueOf(ch[i]))) { freq++; } } return freq; } // Function to remove duplicate // characters private static char[] removeDuplicate(String str) { // To keep unique character only HashSet<Character> set = new HashSet<Character>(); int c = str.length(); // Inserting character in hashset for (int i = 0; i < c; i++) { set.add(str.charAt(i)); } char arr[] = new char[set.size()]; int index = 0; // Update string with unique characters for (char s : set) { arr[index] = s; index++; } // Return the char array return arr; } // Driver Code public static void main( String[] args) throws Exception { int n = 3; String str = "Vikas"; String D[] = { "preeti", "khusbu", "katherina" }; // Removing duplicate and // convert to lowercase char ch[] = removeDuplicate(str.toLowerCase()); ArrayList<String> list = new ArrayList<String>(); // Insert each string in the list for (int i = 0; i < n; i++) { list.add(D[i]); } // Function Call maxMatchingChar(list, n, ch); }}
# Python3 program for the above approachimport sys # Function that print string which# has maximum similar charactersdef maxMatchingChar(list, n, ch): val = "" maxVal = -sys.maxsize - 1 for s in list: # Count matching characters matchingchar = matchingChar(s.lower(), ch) # Update maxVal if needed if (matchingchar > maxVal): maxVal = matchingchar val = s print(val, end = " ") # Function that returns the count# of number of matching charactersdef matchingChar(s, ch): freq = 0 c = len(ch) # Traverse the character array for i in range(c): # If character matches # then increment the count if ch[i] in s: freq += 1 return freq # Driver Coden = 3str = "Vikas"D = [ "preeti", "khusbu", "katherina" ] # Remove duplicate characters and# convert to lowercasech = list(set(str.lower()))List = [] # Insert each string in the listfor i in range(n): List.append(D[i]) # Function callmaxMatchingChar(List, n, ch) # This code is contributed by avanitrachhadiya2155
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that print string which// has maximum similar charactersprivate static void maxMatchingChar(List<String> list, int n, char []ch){ String val = ""; int maxVal = int.MinValue; foreach(String s in list) { // Count matching characters int matchingchar = matchingChar( s.ToLower(), ch); // Update maxVal if needed if (matchingchar > maxVal) { maxVal = matchingchar; val = s; } } Console.Write(val + " ");} // Function that returns the count// of number of matching charactersprivate static int matchingChar(String s, char[] ch){ int freq = 0, c = ch.Length; // Traverse the character array for(int i = 0; i < c; i++) { // If character matches // then increment the count if (s.Contains(String.Join("", ch[i]))) { freq++; } } return freq;} // Function to remove duplicate// charactersprivate static char[] removeDuplicate(String str){ // To keep unique character only HashSet<char> set = new HashSet<char>(); int c = str.Length; // Inserting character in hashset for(int i = 0; i < c; i++) { set.Add(str[i]); } char []arr = new char[set.Count]; int index = 0; // Update string with unique characters foreach(char s in set) { arr[index] = s; index++; } // Return the char array return arr;} // Driver Codepublic static void Main(String[] args){ int n = 3; String str = "Vikas"; String []D = { "preeti", "khusbu", "katherina" }; // Removing duplicate and // convert to lowercase char []ch = removeDuplicate(str.ToLower()); List<String> list = new List<String>(); // Insert each string in the list for(int i = 0; i < n; i++) { list.Add(D[i]); } // Function call maxMatchingChar(list, n, ch);}} // This code is contributed by Rohit_ranjan
katherina
Time Complexity: O(N*M) where M is the maximum length of a string.Auxiliary space: O(M)
Rohit_ranjan
avanitrachhadiya2155
saurabh1990aror
frequency-counting
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jul, 2021"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "Given a string str and an array of strings arr[] of size N, the task is to print a string from arr[], which has maximum count of matching characters with str."
},
{
"code": null,
"e": 197,
"s": 187,
"text": "Examples:"
},
{
"code": null,
"e": 466,
"s": 197,
"text": "Input: str = “vikas”, N = 3, arr[] = [“preeti”, “khusbu”, “katherina”] Output: “katherina” Explanation: Number of similar characters between Str and each string in D[ ] are, “preeti” = 1 “khusbu” = 2 “katherina” = 3 Hence, “katherina” has maximum matching characters."
},
{
"code": null,
"e": 698,
"s": 466,
"text": "Input: str = “gfg”, N = 3, arr[] = [“goal”, “fog”, “abc”] Output: “fog” Explanation:Number of similar characters between Str and each string in D[ ] are, “goal” = 1 “fog” = 2 “abc” = 0 Hence, “fog” has maximum matching characters."
},
{
"code": null,
"e": 983,
"s": 698,
"text": "Approach: The idea is to consider each string of array arr[], and compare each of its character with the given string str. Keep track of the maximum number of matching characters and corresponding string. Also, make sure to remove the duplicates from each string. Below are the steps:"
},
{
"code": null,
"e": 1489,
"s": 983,
"text": "Create a variable maxVal and a variable val, to keep track of maximum number of matching characters and corresponding string respectively.Traverse the array arr[] and remove duplicates from each string. Also, remove duplicates from Str.For each string of arr[], compare it with the given string str, and count the number of matching characters.Keep updating maxVal with the maximum number of matching characters and val with corresponding string.Finally, print the value of val after the above operations."
},
{
"code": null,
"e": 1628,
"s": 1489,
"text": "Create a variable maxVal and a variable val, to keep track of maximum number of matching characters and corresponding string respectively."
},
{
"code": null,
"e": 1727,
"s": 1628,
"text": "Traverse the array arr[] and remove duplicates from each string. Also, remove duplicates from Str."
},
{
"code": null,
"e": 1836,
"s": 1727,
"text": "For each string of arr[], compare it with the given string str, and count the number of matching characters."
},
{
"code": null,
"e": 1939,
"s": 1836,
"text": "Keep updating maxVal with the maximum number of matching characters and val with corresponding string."
},
{
"code": null,
"e": 1999,
"s": 1939,
"text": "Finally, print the value of val after the above operations."
},
{
"code": null,
"e": 2050,
"s": 1999,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2055,
"s": 2050,
"text": "Java"
},
{
"code": null,
"e": 2063,
"s": 2055,
"text": "Python3"
},
{
"code": null,
"e": 2066,
"s": 2063,
"text": "C#"
},
{
"code": "// Java program for the above approachimport java.util.*;import java.io.*; public class GFG { // Function that print string which // has maximum similar characters private static void maxMatchingChar(ArrayList<String> list, int n, char ch[]) { String val = \"\"; int maxVal = Integer.MIN_VALUE; for (String s : list) { // Count matching characters int matchingchar = matchingChar( s.toLowerCase(), ch); // Update maxVal if needed if (matchingchar > maxVal) { maxVal = matchingchar; val = s; } } System.out.print(val + \" \"); } // Function that returns the count // of number of matching characters private static int matchingChar( String s, char[] ch) { int freq = 0, c = ch.length; // Traverse the character array for (int i = 0; i < c; i++) { // If character matches // then increment the count if (s.contains( String.valueOf(ch[i]))) { freq++; } } return freq; } // Function to remove duplicate // characters private static char[] removeDuplicate(String str) { // To keep unique character only HashSet<Character> set = new HashSet<Character>(); int c = str.length(); // Inserting character in hashset for (int i = 0; i < c; i++) { set.add(str.charAt(i)); } char arr[] = new char[set.size()]; int index = 0; // Update string with unique characters for (char s : set) { arr[index] = s; index++; } // Return the char array return arr; } // Driver Code public static void main( String[] args) throws Exception { int n = 3; String str = \"Vikas\"; String D[] = { \"preeti\", \"khusbu\", \"katherina\" }; // Removing duplicate and // convert to lowercase char ch[] = removeDuplicate(str.toLowerCase()); ArrayList<String> list = new ArrayList<String>(); // Insert each string in the list for (int i = 0; i < n; i++) { list.add(D[i]); } // Function Call maxMatchingChar(list, n, ch); }}",
"e": 4456,
"s": 2066,
"text": null
},
{
"code": "# Python3 program for the above approachimport sys # Function that print string which# has maximum similar charactersdef maxMatchingChar(list, n, ch): val = \"\" maxVal = -sys.maxsize - 1 for s in list: # Count matching characters matchingchar = matchingChar(s.lower(), ch) # Update maxVal if needed if (matchingchar > maxVal): maxVal = matchingchar val = s print(val, end = \" \") # Function that returns the count# of number of matching charactersdef matchingChar(s, ch): freq = 0 c = len(ch) # Traverse the character array for i in range(c): # If character matches # then increment the count if ch[i] in s: freq += 1 return freq # Driver Coden = 3str = \"Vikas\"D = [ \"preeti\", \"khusbu\", \"katherina\" ] # Remove duplicate characters and# convert to lowercasech = list(set(str.lower()))List = [] # Insert each string in the listfor i in range(n): List.append(D[i]) # Function callmaxMatchingChar(List, n, ch) # This code is contributed by avanitrachhadiya2155",
"e": 5564,
"s": 4456,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that print string which// has maximum similar charactersprivate static void maxMatchingChar(List<String> list, int n, char []ch){ String val = \"\"; int maxVal = int.MinValue; foreach(String s in list) { // Count matching characters int matchingchar = matchingChar( s.ToLower(), ch); // Update maxVal if needed if (matchingchar > maxVal) { maxVal = matchingchar; val = s; } } Console.Write(val + \" \");} // Function that returns the count// of number of matching charactersprivate static int matchingChar(String s, char[] ch){ int freq = 0, c = ch.Length; // Traverse the character array for(int i = 0; i < c; i++) { // If character matches // then increment the count if (s.Contains(String.Join(\"\", ch[i]))) { freq++; } } return freq;} // Function to remove duplicate// charactersprivate static char[] removeDuplicate(String str){ // To keep unique character only HashSet<char> set = new HashSet<char>(); int c = str.Length; // Inserting character in hashset for(int i = 0; i < c; i++) { set.Add(str[i]); } char []arr = new char[set.Count]; int index = 0; // Update string with unique characters foreach(char s in set) { arr[index] = s; index++; } // Return the char array return arr;} // Driver Codepublic static void Main(String[] args){ int n = 3; String str = \"Vikas\"; String []D = { \"preeti\", \"khusbu\", \"katherina\" }; // Removing duplicate and // convert to lowercase char []ch = removeDuplicate(str.ToLower()); List<String> list = new List<String>(); // Insert each string in the list for(int i = 0; i < n; i++) { list.Add(D[i]); } // Function call maxMatchingChar(list, n, ch);}} // This code is contributed by Rohit_ranjan",
"e": 7656,
"s": 5564,
"text": null
},
{
"code": null,
"e": 7666,
"s": 7656,
"text": "katherina"
},
{
"code": null,
"e": 7754,
"s": 7666,
"text": "Time Complexity: O(N*M) where M is the maximum length of a string.Auxiliary space: O(M)"
},
{
"code": null,
"e": 7767,
"s": 7754,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 7788,
"s": 7767,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 7804,
"s": 7788,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 7823,
"s": 7804,
"text": "frequency-counting"
},
{
"code": null,
"e": 7828,
"s": 7823,
"text": "Hash"
},
{
"code": null,
"e": 7836,
"s": 7828,
"text": "Strings"
},
{
"code": null,
"e": 7841,
"s": 7836,
"text": "Hash"
},
{
"code": null,
"e": 7849,
"s": 7841,
"text": "Strings"
}
]
|
How to convert String to Float in PHP ? | 30 Apr, 2021
Strings in PHP can be converted to float very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert a string into a number in PHP, some of them are discussed below:
Methods:
Using floatval() function.
Using Typecasting.
Using number_format() function.
Method 1: Using floatval() function.
Note: The floatval() function can be used to convert the string into float values .
Syntax:
$floatvar = floatval($stringvar)
Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter.
Example:
PHP
<?php // Number in string format $stringvar = "1000.314"; // converts string into float $floatvar = floatval($stringvar); // prints the value of above variable as a float echo "Converted float = ".$floatvar; ?>
Output:
Converted float = 1000.314
Method 2: Using Typecasting.
Note: Typecasting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We convert String into Float.
Syntax:
$floatvar = (float)$stringvar
Example:
PHP
<?php // Number in string format$stringvar = "1000.314"; // converts string into float$floatvar = (float)$stringvar; // prints the value of above variable as a floatecho "Converted float = ".$floatvar; ?>
Output:
Converted float = 1000.314
Method 3: Using number_format() function.
Note: The number_format() function is an inbuilt function in PHP that is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure.
Syntax:
string number_format( $number, $decimals, $decimalpoint, $sep )
Return Value: It returns a formatted number in case of success, otherwise it gives E_WARNING if it fails.
Example:
PHP
<?php // Number in string format$stringvar = "1000.3145635"; // converts string into float with 6 decimals$floatvar = number_format($stringvar, 6); // prints the value of above variable as a stringecho "Converted float = ".$floatvar; ?>
Output:
Converted float = 1000.314564
PHP-function
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to 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?
PHP | Converting string to Date and DateTime
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": "\n30 Apr, 2021"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "Strings in PHP can be converted to float very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert a string into a number in PHP, some of them are discussed below:"
},
{
"code": null,
"e": 271,
"s": 262,
"text": "Methods:"
},
{
"code": null,
"e": 298,
"s": 271,
"text": "Using floatval() function."
},
{
"code": null,
"e": 317,
"s": 298,
"text": "Using Typecasting."
},
{
"code": null,
"e": 349,
"s": 317,
"text": "Using number_format() function."
},
{
"code": null,
"e": 386,
"s": 349,
"text": "Method 1: Using floatval() function."
},
{
"code": null,
"e": 470,
"s": 386,
"text": "Note: The floatval() function can be used to convert the string into float values ."
},
{
"code": null,
"e": 478,
"s": 470,
"text": "Syntax:"
},
{
"code": null,
"e": 511,
"s": 478,
"text": "$floatvar = floatval($stringvar)"
},
{
"code": null,
"e": 650,
"s": 511,
"text": "Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter."
},
{
"code": null,
"e": 659,
"s": 650,
"text": "Example:"
},
{
"code": null,
"e": 663,
"s": 659,
"text": "PHP"
},
{
"code": "<?php // Number in string format $stringvar = \"1000.314\"; // converts string into float $floatvar = floatval($stringvar); // prints the value of above variable as a float echo \"Converted float = \".$floatvar; ?>",
"e": 888,
"s": 663,
"text": null
},
{
"code": null,
"e": 896,
"s": 888,
"text": "Output:"
},
{
"code": null,
"e": 923,
"s": 896,
"text": "Converted float = 1000.314"
},
{
"code": null,
"e": 952,
"s": 923,
"text": "Method 2: Using Typecasting."
},
{
"code": null,
"e": 1118,
"s": 952,
"text": "Note: Typecasting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We convert String into Float."
},
{
"code": null,
"e": 1126,
"s": 1118,
"text": "Syntax:"
},
{
"code": null,
"e": 1156,
"s": 1126,
"text": "$floatvar = (float)$stringvar"
},
{
"code": null,
"e": 1165,
"s": 1156,
"text": "Example:"
},
{
"code": null,
"e": 1169,
"s": 1165,
"text": "PHP"
},
{
"code": "<?php // Number in string format$stringvar = \"1000.314\"; // converts string into float$floatvar = (float)$stringvar; // prints the value of above variable as a floatecho \"Converted float = \".$floatvar; ?>",
"e": 1379,
"s": 1169,
"text": null
},
{
"code": null,
"e": 1387,
"s": 1379,
"text": "Output:"
},
{
"code": null,
"e": 1414,
"s": 1387,
"text": "Converted float = 1000.314"
},
{
"code": null,
"e": 1456,
"s": 1414,
"text": "Method 3: Using number_format() function."
},
{
"code": null,
"e": 1661,
"s": 1456,
"text": "Note: The number_format() function is an inbuilt function in PHP that is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure."
},
{
"code": null,
"e": 1669,
"s": 1661,
"text": "Syntax:"
},
{
"code": null,
"e": 1733,
"s": 1669,
"text": "string number_format( $number, $decimals, $decimalpoint, $sep )"
},
{
"code": null,
"e": 1839,
"s": 1733,
"text": "Return Value: It returns a formatted number in case of success, otherwise it gives E_WARNING if it fails."
},
{
"code": null,
"e": 1848,
"s": 1839,
"text": "Example:"
},
{
"code": null,
"e": 1852,
"s": 1848,
"text": "PHP"
},
{
"code": "<?php // Number in string format$stringvar = \"1000.3145635\"; // converts string into float with 6 decimals$floatvar = number_format($stringvar, 6); // prints the value of above variable as a stringecho \"Converted float = \".$floatvar; ?>",
"e": 2095,
"s": 1852,
"text": null
},
{
"code": null,
"e": 2103,
"s": 2095,
"text": "Output:"
},
{
"code": null,
"e": 2133,
"s": 2103,
"text": "Converted float = 1000.314564"
},
{
"code": null,
"e": 2146,
"s": 2133,
"text": "PHP-function"
},
{
"code": null,
"e": 2160,
"s": 2146,
"text": "PHP-Questions"
},
{
"code": null,
"e": 2167,
"s": 2160,
"text": "Picked"
},
{
"code": null,
"e": 2171,
"s": 2167,
"text": "PHP"
},
{
"code": null,
"e": 2188,
"s": 2171,
"text": "Web Technologies"
},
{
"code": null,
"e": 2192,
"s": 2188,
"text": "PHP"
},
{
"code": null,
"e": 2290,
"s": 2192,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2340,
"s": 2290,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2380,
"s": 2340,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2441,
"s": 2380,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2491,
"s": 2441,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2536,
"s": 2491,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2569,
"s": 2536,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2631,
"s": 2569,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2692,
"s": 2631,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2742,
"s": 2692,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
How to validate input field in the HTML Form ? | 13 Jan, 2022
In this article, we will see how to validate form input fields using HTML. To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form.
Syntax:
<input required>
Approach: In the below example, we will create a form with <label> and <input> tags and add required attribute with input tag to validate the input field using HTML.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <title> How to validate input field in HTML Form? </title></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to validate input field in HTML Form? </h3> <form action="#"> <label for="fname">First Name:</label> <input type="text" name="fname" id="fname" required> <br><br> <label for="lname">Last Name:</label> <input type="text" name="lname" id="lname" required> <br><br> <label for="email">Email Id:</label> <input type="email" name="email" id="email" required> <br><br> <input type="submit" value="Submit"> </form> </center></body> </html>
Output:
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 324,
"s": 28,
"text": "In this article, we will see how to validate form input fields using HTML. To validate the form using HTML, we will use HTML <input> required attribute. The <input> required attribute is a Boolean attribute that is used to specify the input element must be filled out before submitting the Form."
},
{
"code": null,
"e": 332,
"s": 324,
"text": "Syntax:"
},
{
"code": null,
"e": 349,
"s": 332,
"text": "<input required>"
},
{
"code": null,
"e": 515,
"s": 349,
"text": "Approach: In the below example, we will create a form with <label> and <input> tags and add required attribute with input tag to validate the input field using HTML."
},
{
"code": null,
"e": 524,
"s": 515,
"text": "Example:"
},
{
"code": null,
"e": 529,
"s": 524,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to validate input field in HTML Form? </title></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to validate input field in HTML Form? </h3> <form action=\"#\"> <label for=\"fname\">First Name:</label> <input type=\"text\" name=\"fname\" id=\"fname\" required> <br><br> <label for=\"lname\">Last Name:</label> <input type=\"text\" name=\"lname\" id=\"lname\" required> <br><br> <label for=\"email\">Email Id:</label> <input type=\"email\" name=\"email\" id=\"email\" required> <br><br> <input type=\"submit\" value=\"Submit\"> </form> </center></body> </html>",
"e": 1345,
"s": 529,
"text": null
},
{
"code": null,
"e": 1353,
"s": 1345,
"text": "Output:"
},
{
"code": null,
"e": 1368,
"s": 1353,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1375,
"s": 1368,
"text": "Picked"
},
{
"code": null,
"e": 1380,
"s": 1375,
"text": "HTML"
},
{
"code": null,
"e": 1397,
"s": 1380,
"text": "Web Technologies"
},
{
"code": null,
"e": 1402,
"s": 1397,
"text": "HTML"
},
{
"code": null,
"e": 1500,
"s": 1402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1524,
"s": 1500,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1563,
"s": 1524,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1602,
"s": 1563,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1622,
"s": 1602,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1651,
"s": 1622,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1684,
"s": 1651,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1745,
"s": 1684,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1788,
"s": 1745,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1860,
"s": 1788,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
Sum of array elements using recursion | 27 Jan, 2022
Given an array of integers, find sum of array elements using recursion. Examples:
Input : A[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6
Input : A[] = {15, 12, 13, 10}
Output : 50
We have discussed iterative solution in below post. Sum of elements in a given arrayIn this post, recursive solution is discussed.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of array// elements using recursion.#include <stdio.h> // Return sum of elements in A[0..N-1]// using recursion.int findSum(int A[], int N){ if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]);} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5 }; int N = sizeof(A) / sizeof(A[0]); printf("%dn", findSum(A, N)); return 0;}
// Java program to find sum of array// elements using recursion. class Test { static int arr[] = { 1, 2, 3, 4, 5 }; // Return sum of elements in A[0..N-1] // using recursion. static int findSum(int A[], int N) { if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]); } // Driver method public static void main(String[] args) { System.out.println(findSum(arr, arr.length)); }}
# Python program to find sum of array# elements using recursion. # Return sum of elements in A[0..N-1] # using recursion.def _findSum(arr, N): if len(arr)== 1: return arr[0] else: return arr[0]+_findSum(arr[1:], N) # driver codearr =[]# input values to listarr = [1, 2, 3, 4, 5] # calculating length of arrayN = len(arr) ans =_findSum(arr,N)print (ans) # This code is contributed by Khare Ishita
// C# program to find sum of array// elements using recursion.using System; class Test { static int []arr = {1, 2, 3, 4, 5}; // Return sum of elements in // A[0..N-1] using recursion. static int findSum(int []A, int N) { if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]); } // Driver Code public static void Main() { Console.Write(findSum(arr, arr.Length)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find sum// of array elements using// recursion. // Return sum of elements// in A[0..N-1] using recursion.function findSum($A, $N){ if ($N <= 0) return 0; return (findSum($A, $N - 1) + $A[$N - 1]);} // Driver code$A = array(1, 2, 3, 4, 5);$N = sizeof($A);echo findSum($A, $N); // This code is contributed// by ihritik?>
<script> // JavaScript program to find sum of array// elements using recursion. // Return sum of elements in A[0..N-1]// using recursion.function findSum(A, N) { if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]);} // Driver code let A = [1, 2, 3, 4, 5];let N = A.length;document.write(findSum(A, N)); </script>
Output:
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.
15
How does above recursive solution work?
Sum of array elements using recursion | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSum of array elements using recursion | 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:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=-tqsxDpp6NI" 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 Prakhar Agrawal. 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.
Khare Ishita
nitin mittal
ihritik
_saurabh_jaiswal
amartyaghoshgfg
Arrays
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 136,
"s": 52,
"text": "Given an array of integers, find sum of array elements using recursion. Examples: "
},
{
"code": null,
"e": 229,
"s": 136,
"text": "Input : A[] = {1, 2, 3}\nOutput : 6\n1 + 2 + 3 = 6\n\nInput : A[] = {15, 12, 13, 10}\nOutput : 50"
},
{
"code": null,
"e": 364,
"s": 231,
"text": "We have discussed iterative solution in below post. Sum of elements in a given arrayIn this post, recursive solution is discussed. "
},
{
"code": null,
"e": 368,
"s": 364,
"text": "C++"
},
{
"code": null,
"e": 373,
"s": 368,
"text": "Java"
},
{
"code": null,
"e": 381,
"s": 373,
"text": "Python3"
},
{
"code": null,
"e": 384,
"s": 381,
"text": "C#"
},
{
"code": null,
"e": 388,
"s": 384,
"text": "PHP"
},
{
"code": null,
"e": 399,
"s": 388,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of array// elements using recursion.#include <stdio.h> // Return sum of elements in A[0..N-1]// using recursion.int findSum(int A[], int N){ if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]);} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5 }; int N = sizeof(A) / sizeof(A[0]); printf(\"%dn\", findSum(A, N)); return 0;}",
"e": 784,
"s": 399,
"text": null
},
{
"code": "// Java program to find sum of array// elements using recursion. class Test { static int arr[] = { 1, 2, 3, 4, 5 }; // Return sum of elements in A[0..N-1] // using recursion. static int findSum(int A[], int N) { if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]); } // Driver method public static void main(String[] args) { System.out.println(findSum(arr, arr.length)); }}",
"e": 1230,
"s": 784,
"text": null
},
{
"code": "# Python program to find sum of array# elements using recursion. # Return sum of elements in A[0..N-1] # using recursion.def _findSum(arr, N): if len(arr)== 1: return arr[0] else: return arr[0]+_findSum(arr[1:], N) # driver codearr =[]# input values to listarr = [1, 2, 3, 4, 5] # calculating length of arrayN = len(arr) ans =_findSum(arr,N)print (ans) # This code is contributed by Khare Ishita",
"e": 1652,
"s": 1230,
"text": null
},
{
"code": "// C# program to find sum of array// elements using recursion.using System; class Test { static int []arr = {1, 2, 3, 4, 5}; // Return sum of elements in // A[0..N-1] using recursion. static int findSum(int []A, int N) { if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]); } // Driver Code public static void Main() { Console.Write(findSum(arr, arr.Length)); }} // This code is contributed by Nitin Mittal.",
"e": 2137,
"s": 1652,
"text": null
},
{
"code": "<?php// PHP program to find sum// of array elements using// recursion. // Return sum of elements// in A[0..N-1] using recursion.function findSum($A, $N){ if ($N <= 0) return 0; return (findSum($A, $N - 1) + $A[$N - 1]);} // Driver code$A = array(1, 2, 3, 4, 5);$N = sizeof($A);echo findSum($A, $N); // This code is contributed// by ihritik?>",
"e": 2515,
"s": 2137,
"text": null
},
{
"code": "<script> // JavaScript program to find sum of array// elements using recursion. // Return sum of elements in A[0..N-1]// using recursion.function findSum(A, N) { if (N <= 0) return 0; return (findSum(A, N - 1) + A[N - 1]);} // Driver code let A = [1, 2, 3, 4, 5];let N = A.length;document.write(findSum(A, N)); </script>",
"e": 2849,
"s": 2515,
"text": null
},
{
"code": null,
"e": 2859,
"s": 2849,
"text": "Output: "
},
{
"code": null,
"e": 2868,
"s": 2859,
"text": "Chapters"
},
{
"code": null,
"e": 2895,
"s": 2868,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 2945,
"s": 2895,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 2968,
"s": 2945,
"text": "captions off, selected"
},
{
"code": null,
"e": 2976,
"s": 2968,
"text": "English"
},
{
"code": null,
"e": 3000,
"s": 2976,
"text": "This is a modal window."
},
{
"code": null,
"e": 3069,
"s": 3000,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 3091,
"s": 3069,
"text": "End of dialog window."
},
{
"code": null,
"e": 3094,
"s": 3091,
"text": "15"
},
{
"code": null,
"e": 3136,
"s": 3094,
"text": "How does above recursive solution work? "
},
{
"code": null,
"e": 4030,
"s": 3138,
"text": "Sum of array elements using recursion | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSum of array elements using recursion | 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:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=-tqsxDpp6NI\" 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": 4453,
"s": 4030,
"text": "This article is contributed by Prakhar Agrawal. 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": 4466,
"s": 4453,
"text": "Khare Ishita"
},
{
"code": null,
"e": 4479,
"s": 4466,
"text": "nitin mittal"
},
{
"code": null,
"e": 4487,
"s": 4479,
"text": "ihritik"
},
{
"code": null,
"e": 4504,
"s": 4487,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 4520,
"s": 4504,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 4527,
"s": 4520,
"text": "Arrays"
},
{
"code": null,
"e": 4546,
"s": 4527,
"text": "School Programming"
},
{
"code": null,
"e": 4553,
"s": 4546,
"text": "Arrays"
},
{
"code": null,
"e": 4651,
"s": 4553,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4719,
"s": 4651,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 4763,
"s": 4719,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 4795,
"s": 4763,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4843,
"s": 4795,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 4857,
"s": 4843,
"text": "Linear Search"
},
{
"code": null,
"e": 4875,
"s": 4857,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4900,
"s": 4875,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4923,
"s": 4900,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4942,
"s": 4923,
"text": "Interfaces in Java"
}
]
|
Queue.CopyTo() Method in C# | 04 Feb, 2019
This method is used to copy the Queue elements to an existing one-dimensional Array, starting at the specified array index. The elements are copied to the Array in the same order in which the enumerator iterates through the Queue and this method is an O(n) operation, where n is Count. This method comes under System.Collections namespace.
Syntax:
public virtual void CopyTo (Array array, int index);
Parameters:
array: It is the one-dimensional Array that is the destination of the elements copied from Queue. The Array must have zero-based indexing.
index: It is the zero-based index in array at which copying begins.
Exceptions:
ArgumentNullException: If the array is null.
ArgumentOutOfRangeException: If the index is less than zero.
ArgumentException: If the array is multidimensional Or the number of elements in the source Queue is greater than the number of elements that the destination array can contain.
InvalidCastException: If the type of the source Queue cannot be cast automatically to the type of the destination array.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to illustrate the// Queue.CopyTo(Array, Int32)// Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an Queue Queue myq = new Queue(); // Adding elements to Queue myq.Enqueue("A"); myq.Enqueue("B"); myq.Enqueue("C"); myq.Enqueue("D"); // Creates and initializes the // one-dimensional target Array. String[] arr = new String[6]; // adding elements to Array arr[0] = "HTML"; arr[1] = "PHP"; arr[2] = "Java"; arr[3] = "Python"; arr[4] = "C#"; arr[5] = "OS"; Console.WriteLine("Before Method: "); Console.WriteLine("\nQueue Contains: "); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine("\nArray Contains: "); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine("arr[{0}] : {1}", i, arr[i]); } Console.WriteLine("After Method: "); // Copying the entire source Queue // to the target Array starting at // index 2. myq.CopyTo(arr, 2); Console.WriteLine("\nQueue Contains: "); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine("\nArray Contains: "); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine("arr[{0}] : {1}", i, arr[i]); } }}
Output:
Before Method:
Queue Contains:
A
B
C
D
Array Contains:
arr[0] : HTML
arr[1] : PHP
arr[2] : Java
arr[3] : Python
arr[4] : C#
arr[5] : OS
After Method:
Queue Contains:
A
B
C
D
Array Contains:
arr[0] : HTML
arr[1] : PHP
arr[2] : A
arr[3] : B
arr[4] : C
arr[5] : D
Example 2:
// C# code to illustrate the// Queue.CopyTo(Array, Int32)// Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an Queue Queue myq = new Queue(); // Adding elements to Queue myq.Enqueue("A"); myq.Enqueue("B"); myq.Enqueue("C"); myq.Enqueue("D"); // Creates and initializes the // one-dimensional target Array. String[] arr = new String[2]; // adding elements to Array arr[0] = "HTML"; arr[1] = "PHP"; arr[2] = "Java"; arr[3] = "Python"; arr[4] = "C#"; arr[5] = "OS"; Console.WriteLine("Before Method: "); Console.WriteLine("\nQueue Contains: "); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine("\nArray Contains: "); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine("arr[{0}] : {1}", i, arr[i]); } Console.WriteLine("After Method: "); // using Method but It will give // Runtime Error as number of elements // in the source Queue is greater // than the number of elements that // the destination array can contain myq.CopyTo(arr, 2); Console.WriteLine("\nQueue Contains: "); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine("\nArray Contains: "); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine("arr[{0}] : {1}", i, arr[i]); } }}
Runtime Error:
Unhandled Exception:System.IndexOutOfRangeException: Index was outside the bounds of the array.at (wrapper stelemref) System.Object.virt_stelemref_sealed_class(intptr, object)
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.copyto?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Feb, 2019"
},
{
"code": null,
"e": 368,
"s": 28,
"text": "This method is used to copy the Queue elements to an existing one-dimensional Array, starting at the specified array index. The elements are copied to the Array in the same order in which the enumerator iterates through the Queue and this method is an O(n) operation, where n is Count. This method comes under System.Collections namespace."
},
{
"code": null,
"e": 376,
"s": 368,
"text": "Syntax:"
},
{
"code": null,
"e": 429,
"s": 376,
"text": "public virtual void CopyTo (Array array, int index);"
},
{
"code": null,
"e": 441,
"s": 429,
"text": "Parameters:"
},
{
"code": null,
"e": 580,
"s": 441,
"text": "array: It is the one-dimensional Array that is the destination of the elements copied from Queue. The Array must have zero-based indexing."
},
{
"code": null,
"e": 648,
"s": 580,
"text": "index: It is the zero-based index in array at which copying begins."
},
{
"code": null,
"e": 660,
"s": 648,
"text": "Exceptions:"
},
{
"code": null,
"e": 705,
"s": 660,
"text": "ArgumentNullException: If the array is null."
},
{
"code": null,
"e": 766,
"s": 705,
"text": "ArgumentOutOfRangeException: If the index is less than zero."
},
{
"code": null,
"e": 943,
"s": 766,
"text": "ArgumentException: If the array is multidimensional Or the number of elements in the source Queue is greater than the number of elements that the destination array can contain."
},
{
"code": null,
"e": 1064,
"s": 943,
"text": "InvalidCastException: If the type of the source Queue cannot be cast automatically to the type of the destination array."
},
{
"code": null,
"e": 1125,
"s": 1064,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 1136,
"s": 1125,
"text": "Example 1:"
},
{
"code": "// C# code to illustrate the// Queue.CopyTo(Array, Int32)// Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an Queue Queue myq = new Queue(); // Adding elements to Queue myq.Enqueue(\"A\"); myq.Enqueue(\"B\"); myq.Enqueue(\"C\"); myq.Enqueue(\"D\"); // Creates and initializes the // one-dimensional target Array. String[] arr = new String[6]; // adding elements to Array arr[0] = \"HTML\"; arr[1] = \"PHP\"; arr[2] = \"Java\"; arr[3] = \"Python\"; arr[4] = \"C#\"; arr[5] = \"OS\"; Console.WriteLine(\"Before Method: \"); Console.WriteLine(\"\\nQueue Contains: \"); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine(\"\\nArray Contains: \"); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine(\"arr[{0}] : {1}\", i, arr[i]); } Console.WriteLine(\"After Method: \"); // Copying the entire source Queue // to the target Array starting at // index 2. myq.CopyTo(arr, 2); Console.WriteLine(\"\\nQueue Contains: \"); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine(\"\\nArray Contains: \"); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine(\"arr[{0}] : {1}\", i, arr[i]); } }}",
"e": 2807,
"s": 1136,
"text": null
},
{
"code": null,
"e": 2815,
"s": 2807,
"text": "Output:"
},
{
"code": null,
"e": 3087,
"s": 2815,
"text": "Before Method: \n\nQueue Contains: \nA\nB\nC\nD\n\nArray Contains: \narr[0] : HTML\narr[1] : PHP\narr[2] : Java\narr[3] : Python\narr[4] : C#\narr[5] : OS\nAfter Method: \n\nQueue Contains: \nA\nB\nC\nD\n\nArray Contains: \narr[0] : HTML\narr[1] : PHP\narr[2] : A\narr[3] : B\narr[4] : C\narr[5] : D\n"
},
{
"code": null,
"e": 3098,
"s": 3087,
"text": "Example 2:"
},
{
"code": "// C# code to illustrate the// Queue.CopyTo(Array, Int32)// Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an Queue Queue myq = new Queue(); // Adding elements to Queue myq.Enqueue(\"A\"); myq.Enqueue(\"B\"); myq.Enqueue(\"C\"); myq.Enqueue(\"D\"); // Creates and initializes the // one-dimensional target Array. String[] arr = new String[2]; // adding elements to Array arr[0] = \"HTML\"; arr[1] = \"PHP\"; arr[2] = \"Java\"; arr[3] = \"Python\"; arr[4] = \"C#\"; arr[5] = \"OS\"; Console.WriteLine(\"Before Method: \"); Console.WriteLine(\"\\nQueue Contains: \"); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine(\"\\nArray Contains: \"); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine(\"arr[{0}] : {1}\", i, arr[i]); } Console.WriteLine(\"After Method: \"); // using Method but It will give // Runtime Error as number of elements // in the source Queue is greater // than the number of elements that // the destination array can contain myq.CopyTo(arr, 2); Console.WriteLine(\"\\nQueue Contains: \"); // Displaying the elements in myq foreach(Object obj in myq) { Console.WriteLine(obj); } Console.WriteLine(\"\\nArray Contains: \"); // Displaying the elements in arr for (int i = 0; i < arr.Length; i++) { Console.WriteLine(\"arr[{0}] : {1}\", i, arr[i]); } }}",
"e": 4880,
"s": 3098,
"text": null
},
{
"code": null,
"e": 4895,
"s": 4880,
"text": "Runtime Error:"
},
{
"code": null,
"e": 5071,
"s": 4895,
"text": "Unhandled Exception:System.IndexOutOfRangeException: Index was outside the bounds of the array.at (wrapper stelemref) System.Object.virt_stelemref_sealed_class(intptr, object)"
},
{
"code": null,
"e": 5082,
"s": 5071,
"text": "Reference:"
},
{
"code": null,
"e": 5182,
"s": 5082,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.copyto?view=netframework-4.7.2"
},
{
"code": null,
"e": 5211,
"s": 5182,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 5236,
"s": 5211,
"text": "CSharp-Collections-Queue"
},
{
"code": null,
"e": 5250,
"s": 5236,
"text": "CSharp-method"
},
{
"code": null,
"e": 5253,
"s": 5250,
"text": "C#"
}
]
|
Maximum value of int in C++ | 09 Dec, 2020
In this article, we will discuss the int data type in C++. It is used to store a 32-bit integer.
Some properties of the int data type are:
Being a signed data type, it can store positive values as well as negative values.
Takes a size of 32 bits where 1 bit is used to store the sign of the integer.
A maximum integer value that can be stored in an int data type is typically 2, 147, 483, 647, around 231 – 1, but is compiler dependent.
The maximum value that can be stored in int is stored as a constant in <climits> header file whose value can be used as INT_MAX.
A minimum integer value that can be stored in an int data type is typically -2, 147, 483, 648, around -231, but is compiler dependent.
In case of overflow or underflow of data type, the value is wrapped around. For example, if -2, 147, 483, 648 is stored in an int data type and 1 is subtracted from it, the value in that variable will become equal to 2, 147, 483, 647. Similarly, in the case of overflow, the value will round back to -2, 147, 483, 648.
Below is the program to get the highest value that can be stored in int in C++:
C++
// C++ program to obtain the maximum// value that can be store in int#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file int valueFromLimits = INT_MAX; cout << "Value from climits " << "constant (maximum): "; cout << valueFromLimits << "\n"; valueFromLimits = INT_MIN; cout << "Value from climits " << "constant(minimum): "; cout << valueFromLimits << "\n"; // Using the wrap around property // of data types // Initialize two variables with // value -1 as previous and another // with 0 as present int previous = -1; int present = 0; // Keep on increasing both values // until the present increases to // the max limit and wraps around // to the negative value i.e., present // becomes less than previous value while (present > previous) { previous++; present++; } cout << "\nValue using the wrap " << "around property:\n"; cout << "Maximum: " << previous << "\n"; cout << "Minimum: " << present << "\n"; return 0;}
Value from climits constant (maximum): 2147483647
Value from climits constant(minimum): -2147483648
Value using the wrap around property:
Maximum: 2147483647
Minimum: -2147483648
cpp-data-types
Data Type
C++
C++ Programs
Data Type
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Dec, 2020"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "In this article, we will discuss the int data type in C++. It is used to store a 32-bit integer. "
},
{
"code": null,
"e": 168,
"s": 126,
"text": "Some properties of the int data type are:"
},
{
"code": null,
"e": 251,
"s": 168,
"text": "Being a signed data type, it can store positive values as well as negative values."
},
{
"code": null,
"e": 329,
"s": 251,
"text": "Takes a size of 32 bits where 1 bit is used to store the sign of the integer."
},
{
"code": null,
"e": 466,
"s": 329,
"text": "A maximum integer value that can be stored in an int data type is typically 2, 147, 483, 647, around 231 – 1, but is compiler dependent."
},
{
"code": null,
"e": 595,
"s": 466,
"text": "The maximum value that can be stored in int is stored as a constant in <climits> header file whose value can be used as INT_MAX."
},
{
"code": null,
"e": 730,
"s": 595,
"text": "A minimum integer value that can be stored in an int data type is typically -2, 147, 483, 648, around -231, but is compiler dependent."
},
{
"code": null,
"e": 1049,
"s": 730,
"text": "In case of overflow or underflow of data type, the value is wrapped around. For example, if -2, 147, 483, 648 is stored in an int data type and 1 is subtracted from it, the value in that variable will become equal to 2, 147, 483, 647. Similarly, in the case of overflow, the value will round back to -2, 147, 483, 648."
},
{
"code": null,
"e": 1129,
"s": 1049,
"text": "Below is the program to get the highest value that can be stored in int in C++:"
},
{
"code": null,
"e": 1133,
"s": 1129,
"text": "C++"
},
{
"code": "// C++ program to obtain the maximum// value that can be store in int#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file int valueFromLimits = INT_MAX; cout << \"Value from climits \" << \"constant (maximum): \"; cout << valueFromLimits << \"\\n\"; valueFromLimits = INT_MIN; cout << \"Value from climits \" << \"constant(minimum): \"; cout << valueFromLimits << \"\\n\"; // Using the wrap around property // of data types // Initialize two variables with // value -1 as previous and another // with 0 as present int previous = -1; int present = 0; // Keep on increasing both values // until the present increases to // the max limit and wraps around // to the negative value i.e., present // becomes less than previous value while (present > previous) { previous++; present++; } cout << \"\\nValue using the wrap \" << \"around property:\\n\"; cout << \"Maximum: \" << previous << \"\\n\"; cout << \"Minimum: \" << present << \"\\n\"; return 0;}",
"e": 2262,
"s": 1133,
"text": null
},
{
"code": null,
"e": 2443,
"s": 2262,
"text": "Value from climits constant (maximum): 2147483647\nValue from climits constant(minimum): -2147483648\n\nValue using the wrap around property:\nMaximum: 2147483647\nMinimum: -2147483648\n"
},
{
"code": null,
"e": 2458,
"s": 2443,
"text": "cpp-data-types"
},
{
"code": null,
"e": 2468,
"s": 2458,
"text": "Data Type"
},
{
"code": null,
"e": 2472,
"s": 2468,
"text": "C++"
},
{
"code": null,
"e": 2485,
"s": 2472,
"text": "C++ Programs"
},
{
"code": null,
"e": 2495,
"s": 2485,
"text": "Data Type"
},
{
"code": null,
"e": 2499,
"s": 2495,
"text": "CPP"
}
]
|
How to Enable or Disable SELinux in Different Modes? | 12 Mar, 2021
SELinux stands for Security-Enhanced Linux. SELinux is just like the Windows firewall, but it is more secure and private. It manages all the access control policies. We can control the status of SELinux security by using some direct commands or by actually going to the SELinux configuration file and editing the status. SELinux can have three values, enforcing, permissive and disabled. Enforcing means SELinux security policy is enforced. Permissive means SELinux is not enforcing but will print warnings. Disabled means it is not enforcing and also not print warning.
When SELinux is enforcing:
# getenforce
Enforcing
When SELinux is Permissive:
# getenforce
Permissive
Two ways to Enable or Disable SELinux:
Through commands.
Edit SELinux config file.
Through Command:
#setenforce Enforcing
#getenforce
setenforce enforcing
#setenforce Permissive
#getenforce
setenforce permissive
Instead of Enforcing and Permissive, you can also use 1 and 0 respectively. For example
#setenforce 0
#getenforce
setenforce 0
Edit SELinux Configuration File:
Open SELinux configuration file in vi editor. It is located at /etc/selinux/config
#vi /etc/selinux/config
config file
Now edit status to disabled
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these three values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted
~
~
~
~
~
~
~
~
"/etc/selinux/config" 14L, 548C
Now press ESC and type :wq and hit Enter to save it. Now check the status of SELinux using getenforce command.
# getenforce
selinux disabled
NOTE: You need to restart the system to actually see the changes occur. Hence, we have disabled the SELinux service by editing the configuration file.
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 599,
"s": 28,
"text": "SELinux stands for Security-Enhanced Linux. SELinux is just like the Windows firewall, but it is more secure and private. It manages all the access control policies. We can control the status of SELinux security by using some direct commands or by actually going to the SELinux configuration file and editing the status. SELinux can have three values, enforcing, permissive and disabled. Enforcing means SELinux security policy is enforced. Permissive means SELinux is not enforcing but will print warnings. Disabled means it is not enforcing and also not print warning."
},
{
"code": null,
"e": 626,
"s": 599,
"text": "When SELinux is enforcing:"
},
{
"code": null,
"e": 639,
"s": 626,
"text": "# getenforce"
},
{
"code": null,
"e": 649,
"s": 639,
"text": "Enforcing"
},
{
"code": null,
"e": 677,
"s": 649,
"text": "When SELinux is Permissive:"
},
{
"code": null,
"e": 690,
"s": 677,
"text": "# getenforce"
},
{
"code": null,
"e": 701,
"s": 690,
"text": "Permissive"
},
{
"code": null,
"e": 740,
"s": 701,
"text": "Two ways to Enable or Disable SELinux:"
},
{
"code": null,
"e": 758,
"s": 740,
"text": "Through commands."
},
{
"code": null,
"e": 784,
"s": 758,
"text": "Edit SELinux config file."
},
{
"code": null,
"e": 801,
"s": 784,
"text": "Through Command:"
},
{
"code": null,
"e": 835,
"s": 801,
"text": "#setenforce Enforcing\n#getenforce"
},
{
"code": null,
"e": 856,
"s": 835,
"text": "setenforce enforcing"
},
{
"code": null,
"e": 891,
"s": 856,
"text": "#setenforce Permissive\n#getenforce"
},
{
"code": null,
"e": 913,
"s": 891,
"text": "setenforce permissive"
},
{
"code": null,
"e": 1001,
"s": 913,
"text": "Instead of Enforcing and Permissive, you can also use 1 and 0 respectively. For example"
},
{
"code": null,
"e": 1027,
"s": 1001,
"text": "#setenforce 0\n#getenforce"
},
{
"code": null,
"e": 1040,
"s": 1027,
"text": "setenforce 0"
},
{
"code": null,
"e": 1073,
"s": 1040,
"text": "Edit SELinux Configuration File:"
},
{
"code": null,
"e": 1156,
"s": 1073,
"text": "Open SELinux configuration file in vi editor. It is located at /etc/selinux/config"
},
{
"code": null,
"e": 1180,
"s": 1156,
"text": "#vi /etc/selinux/config"
},
{
"code": null,
"e": 1192,
"s": 1180,
"text": "config file"
},
{
"code": null,
"e": 1220,
"s": 1192,
"text": "Now edit status to disabled"
},
{
"code": null,
"e": 2452,
"s": 1220,
"text": "# This file controls the state of SELinux on the system.\n# SELINUX= can take one of these three values:\n# enforcing - SELinux security policy is enforced.\n# permissive - SELinux prints warnings instead of enforcing.\n# disabled - No SELinux policy is loaded.\nSELINUX=disabled\n# SELINUXTYPE= can take one of these three values:\n# targeted - Targeted processes are protected,\n# minimum - Modification of targeted policy. Only selected processes are protected.\n# mls - Multi Level Security protection.\nSELINUXTYPE=targeted\n\n~ \n~ \n~ \n~ \n~ \n~ \n~ \n~ \n\"/etc/selinux/config\" 14L, 548C"
},
{
"code": null,
"e": 2563,
"s": 2452,
"text": "Now press ESC and type :wq and hit Enter to save it. Now check the status of SELinux using getenforce command."
},
{
"code": null,
"e": 2576,
"s": 2563,
"text": "# getenforce"
},
{
"code": null,
"e": 2593,
"s": 2576,
"text": "selinux disabled"
},
{
"code": null,
"e": 2744,
"s": 2593,
"text": "NOTE: You need to restart the system to actually see the changes occur. Hence, we have disabled the SELinux service by editing the configuration file."
},
{
"code": null,
"e": 2751,
"s": 2744,
"text": "How To"
},
{
"code": null,
"e": 2762,
"s": 2751,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2860,
"s": 2762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2909,
"s": 2860,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2951,
"s": 2909,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2990,
"s": 2951,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 3044,
"s": 2990,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 3102,
"s": 3044,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 3142,
"s": 3102,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 3182,
"s": 3142,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 3209,
"s": 3182,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 3244,
"s": 3209,
"text": "cut command in Linux with examples"
}
]
|
Python | PIL Attributes | 29 Jul, 2019
Attribute defines the various property of an object, element or file. In the image, attribute refers to the size, filename, format or mode, etc. of the image.
Image used is:
Instances of the Image class have the following attributes:
PIL.Image.filename: The filename or path of the source file. Only images created with the factory function open have a filename attribute. If the input is a file-like object, the filename attribute is set to an empty string.
Syntax: PIL.Image.filename
Type: py:class: string
from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG") im2 = im1.filenameprint(im2)
Output:
C:\Users\sadow984\Desktop\r1.PNG
PIL.Image.format: The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.
Syntax: PIL.Image.format
Type: string or None
from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG") im2 = im1.formatprint(im2)
Output:
PNG
PIL.Image.mode: Image mode. This is a string specifying the pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.” See Modes for a full list.
Syntax: PIL.Image.mode
Type: string
from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG") im2 = im1.modeprint(im2)
Output:
P
PIL.Image.size: Image size, in pixels. The size is given as a 2-tuple (width, height).
Syntax: PIL.Image.size
Type: (width, height)
from PIL import Imageim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG") im2 = im1.sizeprint(im2)
Output:
(225, 225)
nidhi_biet
Python-pil
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
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jul, 2019"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "Attribute defines the various property of an object, element or file. In the image, attribute refers to the size, filename, format or mode, etc. of the image."
},
{
"code": null,
"e": 202,
"s": 187,
"text": "Image used is:"
},
{
"code": null,
"e": 262,
"s": 202,
"text": "Instances of the Image class have the following attributes:"
},
{
"code": null,
"e": 487,
"s": 262,
"text": "PIL.Image.filename: The filename or path of the source file. Only images created with the factory function open have a filename attribute. If the input is a file-like object, the filename attribute is set to an empty string."
},
{
"code": null,
"e": 539,
"s": 487,
"text": "Syntax: PIL.Image.filename\n\nType: py:class: string\n"
},
{
"code": "from PIL import Imageim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i3.PNG\") im2 = im1.filenameprint(im2)",
"e": 644,
"s": 539,
"text": null
},
{
"code": null,
"e": 652,
"s": 644,
"text": "Output:"
},
{
"code": null,
"e": 685,
"s": 652,
"text": "C:\\Users\\sadow984\\Desktop\\r1.PNG"
},
{
"code": null,
"e": 883,
"s": 685,
"text": " PIL.Image.format: The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None."
},
{
"code": null,
"e": 931,
"s": 883,
"text": "Syntax: PIL.Image.format\n\nType: string or None\n"
},
{
"code": "from PIL import Imageim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i3.PNG\") im2 = im1.formatprint(im2)",
"e": 1034,
"s": 931,
"text": null
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Output:"
},
{
"code": null,
"e": 1046,
"s": 1042,
"text": "PNG"
},
{
"code": null,
"e": 1213,
"s": 1046,
"text": " PIL.Image.mode: Image mode. This is a string specifying the pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.” See Modes for a full list."
},
{
"code": null,
"e": 1252,
"s": 1213,
"text": "Syntax: PIL.Image.mode\n\nType: string \n"
},
{
"code": "from PIL import Imageim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i3.PNG\") im2 = im1.modeprint(im2)",
"e": 1353,
"s": 1252,
"text": null
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Output:"
},
{
"code": null,
"e": 1363,
"s": 1361,
"text": "P"
},
{
"code": null,
"e": 1451,
"s": 1363,
"text": " PIL.Image.size: Image size, in pixels. The size is given as a 2-tuple (width, height)."
},
{
"code": null,
"e": 1499,
"s": 1451,
"text": "Syntax: PIL.Image.size\n\nType: (width, height) \n"
},
{
"code": "from PIL import Imageim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i3.PNG\") im2 = im1.sizeprint(im2)",
"e": 1600,
"s": 1499,
"text": null
},
{
"code": null,
"e": 1608,
"s": 1600,
"text": "Output:"
},
{
"code": null,
"e": 1619,
"s": 1608,
"text": "(225, 225)"
},
{
"code": null,
"e": 1630,
"s": 1619,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1641,
"s": 1630,
"text": "Python-pil"
},
{
"code": null,
"e": 1648,
"s": 1641,
"text": "Python"
},
{
"code": null,
"e": 1746,
"s": 1648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1764,
"s": 1746,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1806,
"s": 1764,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1828,
"s": 1806,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1863,
"s": 1828,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1889,
"s": 1863,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1921,
"s": 1889,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1950,
"s": 1921,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1977,
"s": 1950,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2007,
"s": 1977,
"text": "Iterate over a list in Python"
}
]
|
MapStruct - Throwing Exception | Mapstruct mapper allows throwing specific exception. Consider a case of custom mapping method where we want to throw our custom exception in case of invalid data.
@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
CarEntity getCarEntity(Car car) throws ParseException;
}
Following example demonstrates the same.
Open project mapping as updated in Mapping Enum chapter in Eclipse.
Update UtilityMapper.java with following code −
UtilityMapper.java
package com.tutorialspoint.mapper;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.model.Car;
@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
Stream<String> getStream(Stream<Integer> source);
@ValueMapping(source = "EXTRA", target = "SPECIAL")
PlacedOrderType getEnum(OrderType order);
CarEntity getCarEntity(Car car) throws ParseException;
}
class DateMapper {
public String asString(GregorianCalendar date) {
return date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
.format( date.getTime() ) : null;
}
public GregorianCalendar asDate(String date) throws ParseException {
Date date1 = date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
.parse( date ) : null;
if(date1 != null) {
return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());
}
return null;
}
}
Update UtilityMapperTest.java with following code −
UtilityMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.ParseException;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.mapper.UtilityMapper;
import com.tutorialspoint.model.Car;
public class UtilityMapperTest {
private UtilityMapper utilityMapper = Mappers.getMapper(UtilityMapper.class);
@Test
public void testMapMapping() {
Map<Long, GregorianCalendar> source = new HashMap<>();
source.put(1L, new GregorianCalendar(2015, 3, 5));
Map<String, String> target = utilityMapper.getMap(source);
assertEquals("2015-04-05", target.get("1"));
}
@Test
public void testGetStream() {
Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
Stream<String> strings = utilityMapper.getStream(numbers);
assertEquals(4, strings.count());
}
@Test
public void testGetEnum() {
PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
}
@Test
public void testGetCar() {
Car car = new Car();
car.setId(1);
car.setManufacturingDate("11/10/2020");
boolean exceptionOccured = false;
try {
CarEntity carEntity = utilityMapper.getCarEntity(car);
} catch (ParseException e) {
exceptionOccured = true;
}
assertTrue(exceptionOccured);
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Results :
Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 | [
{
"code": null,
"e": 2557,
"s": 2394,
"text": "Mapstruct mapper allows throwing specific exception. Consider a case of custom mapping method where we want to throw our custom exception in case of invalid data."
},
{
"code": null,
"e": 2682,
"s": 2557,
"text": "@Mapper(uses=DateMapper.class)\npublic interface UtilityMapper {\n CarEntity getCarEntity(Car car) throws ParseException;\n}\n"
},
{
"code": null,
"e": 2723,
"s": 2682,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 2791,
"s": 2723,
"text": "Open project mapping as updated in Mapping Enum chapter in Eclipse."
},
{
"code": null,
"e": 2839,
"s": 2791,
"text": "Update UtilityMapper.java with following code −"
},
{
"code": null,
"e": 2858,
"s": 2839,
"text": "UtilityMapper.java"
},
{
"code": null,
"e": 4255,
"s": 2858,
"text": "package com.tutorialspoint.mapper;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\nimport java.util.Map;\nimport java.util.stream.Stream;\nimport org.mapstruct.MapMapping;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.ValueMapping;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\nimport com.tutorialspoint.model.Car;\n\n@Mapper(uses=DateMapper.class)\npublic interface UtilityMapper {\n @MapMapping(valueDateFormat = \"dd.MM.yyyy\")\n Map<String, String> getMap(Map<Long, GregorianCalendar> source);\n Stream<String> getStream(Stream<Integer> source);\n\n @ValueMapping(source = \"EXTRA\", target = \"SPECIAL\")\n PlacedOrderType getEnum(OrderType order);\n CarEntity getCarEntity(Car car) throws ParseException;\n}\nclass DateMapper {\n public String asString(GregorianCalendar date) {\n return date != null ? new SimpleDateFormat( \"yyyy-MM-dd\" )\n .format( date.getTime() ) : null;\n }\n public GregorianCalendar asDate(String date) throws ParseException {\n Date date1 = date != null ? new SimpleDateFormat( \"yyyy-MM-dd\" )\n .parse( date ) : null;\n if(date1 != null) {\n return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());\n }\n return null; \n }\n}"
},
{
"code": null,
"e": 4307,
"s": 4255,
"text": "Update UtilityMapperTest.java with following code −"
},
{
"code": null,
"e": 4330,
"s": 4307,
"text": "UtilityMapperTest.java"
},
{
"code": null,
"e": 6468,
"s": 4330,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\nimport java.text.ParseException;\nimport java.util.Arrays;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Stream;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\nimport com.tutorialspoint.mapper.UtilityMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class UtilityMapperTest {\n private UtilityMapper utilityMapper = Mappers.getMapper(UtilityMapper.class);\n\n @Test\n public void testMapMapping() {\n Map<Long, GregorianCalendar> source = new HashMap<>();\n source.put(1L, new GregorianCalendar(2015, 3, 5));\n\n Map<String, String> target = utilityMapper.getMap(source);\n assertEquals(\"2015-04-05\", target.get(\"1\"));\t\t\n }\n @Test\n public void testGetStream() {\n Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();\n Stream<String> strings = utilityMapper.getStream(numbers);\n assertEquals(4, strings.count());\t\t\t\n }\n @Test\n public void testGetEnum() {\n PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);\n PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);\n PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);\n assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());\n assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());\n assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());\n }\n @Test\n public void testGetCar() {\n Car car = new Car();\n car.setId(1);\n car.setManufacturingDate(\"11/10/2020\");\n boolean exceptionOccured = false;\n try {\n CarEntity carEntity = utilityMapper.getCarEntity(car);\n } catch (ParseException e) {\n exceptionOccured = true;\n }\n assertTrue(exceptionOccured);\n }\n}"
},
{
"code": null,
"e": 6516,
"s": 6468,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 6532,
"s": 6516,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 6579,
"s": 6532,
"text": "Once command is successful. Verify the output."
}
]
|
Python | Pandas dataframe.nunique() | 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.nunique() function return Series with number of distinct observations over requested axis. If we set the value of axis to be 0, then it finds the total number of unique observations over the index axis. If we set the value of axis to be 1, then it find the total number of unique observations over the column axis. It also provides the feature to exclude the NaN values from the count of unique numbers.
Syntax: DataFrame.nunique(axis=0, dropna=True)
Parameters :axis : {0 or ‘index’, 1 or ‘columns’}, default 0dropna : Don’t include NaN in the counts.
Returns : nunique : Series
Example #1: Use nunique() function to find the number of unique values over the column axis.
# importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({"A":[14, 4, 5, 4, 1], "B":[5, 2, 54, 3, 2], "C":[20, 20, 7, 3, 8], "D":[14, 3, 6, 2, 6]}) # Print the dataframedf
Let’s use the dataframe.nunique() function to find the unique values across the column axis.
# find unique valuesdf.nunique(axis = 1)
Output :As we can see in the output, the function prints the total no. of unique values in each row. Example #2: Use nunique() function to find the number of unique values over the index axis in a dataframe. The dataframe contains NaN values.
# importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({"A":["Sandy", "alex", "brook", "kelly", np.nan], "B":[np.nan, "olivia", "olivia", "", "amanda"], "C":[20 + 5j, 20 + 5j, 7, None, 8], "D":[14.8, 3, None, 6, 6]}) # apply the nunique() functiondf.nunique(axis = 0, dropna = True)
Output :The function is treating the empty string as a unique value in column 2.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\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": 663,
"s": 242,
"text": "Pandas dataframe.nunique() function return Series with number of distinct observations over requested axis. If we set the value of axis to be 0, then it finds the total number of unique observations over the index axis. If we set the value of axis to be 1, then it find the total number of unique observations over the column axis. It also provides the feature to exclude the NaN values from the count of unique numbers."
},
{
"code": null,
"e": 710,
"s": 663,
"text": "Syntax: DataFrame.nunique(axis=0, dropna=True)"
},
{
"code": null,
"e": 812,
"s": 710,
"text": "Parameters :axis : {0 or ‘index’, 1 or ‘columns’}, default 0dropna : Don’t include NaN in the counts."
},
{
"code": null,
"e": 839,
"s": 812,
"text": "Returns : nunique : Series"
},
{
"code": null,
"e": 932,
"s": 839,
"text": "Example #1: Use nunique() function to find the number of unique values over the column axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({\"A\":[14, 4, 5, 4, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 20, 7, 3, 8], \"D\":[14, 3, 6, 2, 6]}) # Print the dataframedf",
"e": 1197,
"s": 932,
"text": null
},
{
"code": null,
"e": 1290,
"s": 1197,
"text": "Let’s use the dataframe.nunique() function to find the unique values across the column axis."
},
{
"code": "# find unique valuesdf.nunique(axis = 1)",
"e": 1331,
"s": 1290,
"text": null
},
{
"code": null,
"e": 1574,
"s": 1331,
"text": "Output :As we can see in the output, the function prints the total no. of unique values in each row. Example #2: Use nunique() function to find the number of unique values over the index axis in a dataframe. The dataframe contains NaN values."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({\"A\":[\"Sandy\", \"alex\", \"brook\", \"kelly\", np.nan], \"B\":[np.nan, \"olivia\", \"olivia\", \"\", \"amanda\"], \"C\":[20 + 5j, 20 + 5j, 7, None, 8], \"D\":[14.8, 3, None, 6, 6]}) # apply the nunique() functiondf.nunique(axis = 0, dropna = True)",
"e": 1952,
"s": 1574,
"text": null
},
{
"code": null,
"e": 2033,
"s": 1952,
"text": "Output :The function is treating the empty string as a unique value in column 2."
},
{
"code": null,
"e": 2057,
"s": 2033,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2089,
"s": 2057,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2103,
"s": 2089,
"text": "Python-pandas"
},
{
"code": null,
"e": 2110,
"s": 2103,
"text": "Python"
}
]
|
Remove all occurrences of a character in a string | 22 Apr, 2022
Given a string. Write a program to remove all the occurrences of a character in the string.
Examples:
Input : s = "geeksforgeeks"
c = 'e'
Output : s = "gksforgks"
Input : s = "geeksforgeeks"
c = 'g'
Output : s = "eeksforeeks"
First Approach: The idea is to maintain an index of the resultant string.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to remove a particular character// from a string.#include <bits/stdc++.h>using namespace std; void removeChar(char* s, char c){ int j, n = strlen(s); for (int i = j = 0; i < n; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\0';} int main(){ char s[] = "geeksforgeeks"; removeChar(s, 'g'); cout << s; return 0;}
// Java program to remove// a particular character// from a string.class GFG{static void removeChar(String s, char c){ int j, count = 0, n = s.length(); char []t = s.toCharArray(); for (int i = j = 0; i < n; i++) { if (t[i] != c) t[j++] = t[i]; else count++; } while(count > 0) { t[j++] = '\0'; count--; } System.out.println(t);} // Driver Codepublic static void main(String[] args){ String s = "geeksforgeeks"; removeChar(s, 'g');}} // This code is contributed// by ChitraNayal
# Python3 program to remove# a particular character# from a string. # function for removing the# occurrence of characterdef removeChar(s, c) : # find total no. of # occurrence of character counts = s.count(c) # convert into list # of characters s = list(s) # keep looping until # counts become 0 while counts : # remove character # from the list s.remove(c) # decremented by one counts -= 1 # join all remaining characters # of the list with empty string s = '' . join(s) print(s) # Driver codeif __name__ == '__main__' : s = "geeksforgeeks" removeChar(s,'g') # This code is contributed# by Ankit Rai
// C# program to remove a// particular character// from a string.using System; class GFG{static void removeChar(string s, char c){ int j, count = 0, n = s.Length; char[] t = s.ToCharArray(); for (int i = j = 0; i < n; i++) { if (s[i] != c) t[j++] = s[i]; else count++; } while(count > 0) { t[j++] = '\0'; count--; } Console.Write(t);} // Driver Codepublic static void Main(){ string s = "geeksforgeeks"; removeChar(s, 'g');}} // This code is contributed// by ChitraNayal
<?php// PHP program to remove a// particular character// from a string. function removeChar($s, $c){ $n = strlen($s); $count = 0; for ($i = $j = 0; $i < $n; $i++) { if ($s[$i] != $c) $s[$j++] = $s[$i]; else $count++; } while($count--) { $s[$j++] = NULL; } echo $s;} // Driver code$s = "geeksforgeeks";removeChar($s, 'g'); // This code is contributed// by ChitraNayal?>
<script> // Javascript program to remove// a particular character// from a string.function removeChar(s, c){ let j, count = 0, n = s.length; let t = s.split(""); for(let i = j = 0; i < n; i++) { if (t[i] != c) t[j++] = t[i]; else count++; } while (count > 0) { t[j++] = '\0'; count--; } document.write(t.join(""));} // Driver Codelet s = "geeksforgeeks";removeChar(s, 'g'); // This code is contributed by avanitrachhadiya2155 </script>
eeksforeeks
Time Complexity : O(n) where n is length of input string. Auxiliary Space : O(1)
Second Approach in C++: We can also use the STL string class and erase function to delete any character at any position using the base addressing (string.begin()).
C++14
#include <bits/stdc++.h>using namespace std; string removechar(string& word,char& ch){ for(int i=0;i<word.length();i++) { if(word[i]==ch){ word.erase(word.begin()+i); i--; } } return word;} // driver's codeint main(){ string word="geeksforgeeks"; char ch='e'; cout<<removechar(word,ch); return 0;}
Time Complexity: O(n), where n is length of input string.
Auxiliary Space: O(1)
ankthon
ukasp
ManasChhabra2
nidhi_biet
shruti371sg
avanitrachhadiya2155
adnanirshad158
gabaa406
prophet1999
Searching
Strings
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search, insert and delete in an unsorted array
Median of two sorted arrays of different sizes
k largest(or smallest) elements in an array
Two Pointers Technique
Search, insert and delete in a sorted array
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
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 144,
"s": 52,
"text": "Given a string. Write a program to remove all the occurrences of a character in the string."
},
{
"code": null,
"e": 155,
"s": 144,
"text": "Examples: "
},
{
"code": null,
"e": 297,
"s": 155,
"text": "Input : s = \"geeksforgeeks\"\n c = 'e'\nOutput : s = \"gksforgks\"\n\n\nInput : s = \"geeksforgeeks\"\n c = 'g'\nOutput : s = \"eeksforeeks\""
},
{
"code": null,
"e": 373,
"s": 297,
"text": "First Approach: The idea is to maintain an index of the resultant string. "
},
{
"code": null,
"e": 377,
"s": 373,
"text": "C++"
},
{
"code": null,
"e": 382,
"s": 377,
"text": "Java"
},
{
"code": null,
"e": 390,
"s": 382,
"text": "Python3"
},
{
"code": null,
"e": 393,
"s": 390,
"text": "C#"
},
{
"code": null,
"e": 397,
"s": 393,
"text": "PHP"
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Javascript"
},
{
"code": "// C++ program to remove a particular character// from a string.#include <bits/stdc++.h>using namespace std; void removeChar(char* s, char c){ int j, n = strlen(s); for (int i = j = 0; i < n; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\\0';} int main(){ char s[] = \"geeksforgeeks\"; removeChar(s, 'g'); cout << s; return 0;}",
"e": 772,
"s": 408,
"text": null
},
{
"code": "// Java program to remove// a particular character// from a string.class GFG{static void removeChar(String s, char c){ int j, count = 0, n = s.length(); char []t = s.toCharArray(); for (int i = j = 0; i < n; i++) { if (t[i] != c) t[j++] = t[i]; else count++; } while(count > 0) { t[j++] = '\\0'; count--; } System.out.println(t);} // Driver Codepublic static void main(String[] args){ String s = \"geeksforgeeks\"; removeChar(s, 'g');}} // This code is contributed// by ChitraNayal",
"e": 1340,
"s": 772,
"text": null
},
{
"code": "# Python3 program to remove# a particular character# from a string. # function for removing the# occurrence of characterdef removeChar(s, c) : # find total no. of # occurrence of character counts = s.count(c) # convert into list # of characters s = list(s) # keep looping until # counts become 0 while counts : # remove character # from the list s.remove(c) # decremented by one counts -= 1 # join all remaining characters # of the list with empty string s = '' . join(s) print(s) # Driver codeif __name__ == '__main__' : s = \"geeksforgeeks\" removeChar(s,'g') # This code is contributed# by Ankit Rai",
"e": 2053,
"s": 1340,
"text": null
},
{
"code": "// C# program to remove a// particular character// from a string.using System; class GFG{static void removeChar(string s, char c){ int j, count = 0, n = s.Length; char[] t = s.ToCharArray(); for (int i = j = 0; i < n; i++) { if (s[i] != c) t[j++] = s[i]; else count++; } while(count > 0) { t[j++] = '\\0'; count--; } Console.Write(t);} // Driver Codepublic static void Main(){ string s = \"geeksforgeeks\"; removeChar(s, 'g');}} // This code is contributed// by ChitraNayal",
"e": 2635,
"s": 2053,
"text": null
},
{
"code": "<?php// PHP program to remove a// particular character// from a string. function removeChar($s, $c){ $n = strlen($s); $count = 0; for ($i = $j = 0; $i < $n; $i++) { if ($s[$i] != $c) $s[$j++] = $s[$i]; else $count++; } while($count--) { $s[$j++] = NULL; } echo $s;} // Driver code$s = \"geeksforgeeks\";removeChar($s, 'g'); // This code is contributed// by ChitraNayal?>",
"e": 3059,
"s": 2635,
"text": null
},
{
"code": "<script> // Javascript program to remove// a particular character// from a string.function removeChar(s, c){ let j, count = 0, n = s.length; let t = s.split(\"\"); for(let i = j = 0; i < n; i++) { if (t[i] != c) t[j++] = t[i]; else count++; } while (count > 0) { t[j++] = '\\0'; count--; } document.write(t.join(\"\"));} // Driver Codelet s = \"geeksforgeeks\";removeChar(s, 'g'); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 3583,
"s": 3059,
"text": null
},
{
"code": null,
"e": 3595,
"s": 3583,
"text": "eeksforeeks"
},
{
"code": null,
"e": 3678,
"s": 3597,
"text": "Time Complexity : O(n) where n is length of input string. Auxiliary Space : O(1)"
},
{
"code": null,
"e": 3842,
"s": 3678,
"text": "Second Approach in C++: We can also use the STL string class and erase function to delete any character at any position using the base addressing (string.begin())."
},
{
"code": null,
"e": 3848,
"s": 3842,
"text": "C++14"
},
{
"code": "#include <bits/stdc++.h>using namespace std; string removechar(string& word,char& ch){ for(int i=0;i<word.length();i++) { if(word[i]==ch){ word.erase(word.begin()+i); i--; } } return word;} // driver's codeint main(){ string word=\"geeksforgeeks\"; char ch='e'; cout<<removechar(word,ch); return 0;}",
"e": 4205,
"s": 3848,
"text": null
},
{
"code": null,
"e": 4264,
"s": 4205,
"text": "Time Complexity: O(n), where n is length of input string. "
},
{
"code": null,
"e": 4286,
"s": 4264,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4294,
"s": 4286,
"text": "ankthon"
},
{
"code": null,
"e": 4300,
"s": 4294,
"text": "ukasp"
},
{
"code": null,
"e": 4314,
"s": 4300,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4325,
"s": 4314,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4337,
"s": 4325,
"text": "shruti371sg"
},
{
"code": null,
"e": 4358,
"s": 4337,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 4373,
"s": 4358,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4382,
"s": 4373,
"text": "gabaa406"
},
{
"code": null,
"e": 4394,
"s": 4382,
"text": "prophet1999"
},
{
"code": null,
"e": 4404,
"s": 4394,
"text": "Searching"
},
{
"code": null,
"e": 4412,
"s": 4404,
"text": "Strings"
},
{
"code": null,
"e": 4422,
"s": 4412,
"text": "Searching"
},
{
"code": null,
"e": 4430,
"s": 4422,
"text": "Strings"
},
{
"code": null,
"e": 4528,
"s": 4430,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4575,
"s": 4528,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 4622,
"s": 4575,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 4666,
"s": 4622,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 4689,
"s": 4666,
"text": "Two Pointers Technique"
},
{
"code": null,
"e": 4733,
"s": 4689,
"text": "Search, insert and delete in a sorted array"
},
{
"code": null,
"e": 4779,
"s": 4733,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4804,
"s": 4779,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4864,
"s": 4804,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4879,
"s": 4864,
"text": "C++ Data Types"
}
]
|
C++ Program to implement Gift Wrapping Algorithm in Two Dimensions | We shall develop a C++ program to implement Gift Wrapping Algorithm in two dimensions. The Gift Wrapping Algorithm is an algorithm for computing the convex hull of a given set of points.
Begin
function convexHull() to find convex hull of a set of n points:
There must be at least three points.
Initialize the result.
Find the leftmost point.
Starting from leftmost point, keep moving counterclockwise
until reach the start point again.
Print the result.
End
Live Demo
#include <iostream>
using namespace std;
#define INF 10000
struct P {
int x;
int y;
};
int orient(P a, P b, P c) {
int v = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y);
if (v == 0)
return 0; // colinear
return (v >0) ? 1 : 2; // clock or counterclock wise
}
void convexHull(P points[], int m) {
if (m < 3)//at least three points required
return;
int n[m];
for (int i = 0; i < m; i++)
n[i] = -1;
int l = 0;//initialize result.
for (int i = 1; i < m; i++)
if (points[i].x < points[l].x)
l = i; //find left most point
int p = l, q;
do {
q = (p + 1) % m;
for (int i = 0; i < m; i++)
if (orient(points[p], points[i], points[q]) == 2)
q = i;
n[p] = q;
p = q;
} while (p != l);
for (int i = 0; i < m; i++) {
if (n[i] != -1)
cout << "(" << points[i].x << ", " << points[i].y << ")\n";
}
}
int main() {
P points[] = {{0, 4}, {2, 1}, {2, 3}, {4, 1}, {3, 0}, {1, 1}, {7, 6}};
cout << "The points in the convex hull are: ";
int n = sizeof(points) / sizeof(points[0]);
convexHull(points, n);
return 0;
}
The points in the convex hull are: (0, 4)
(4, 1)
(3, 0)
(1, 1)
(7, 6) | [
{
"code": null,
"e": 1249,
"s": 1062,
"text": "We shall develop a C++ program to implement Gift Wrapping Algorithm in two dimensions. The Gift Wrapping Algorithm is an algorithm for computing the convex hull of a given set of points."
},
{
"code": null,
"e": 1541,
"s": 1249,
"text": "Begin\n function convexHull() to find convex hull of a set of n points:\n There must be at least three points.\n Initialize the result.\n Find the leftmost point.\n Starting from leftmost point, keep moving counterclockwise\n until reach the start point again.\n Print the result.\nEnd"
},
{
"code": null,
"e": 1552,
"s": 1541,
"text": " Live Demo"
},
{
"code": null,
"e": 2729,
"s": 1552,
"text": "#include <iostream>\nusing namespace std;\n#define INF 10000\nstruct P {\n int x;\n int y;\n};\nint orient(P a, P b, P c) {\n int v = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y);\n if (v == 0)\n return 0; // colinear\n return (v >0) ? 1 : 2; // clock or counterclock wise\n}\nvoid convexHull(P points[], int m) {\n if (m < 3)//at least three points required\n return;\n int n[m];\n for (int i = 0; i < m; i++)\n n[i] = -1;\n int l = 0;//initialize result.\n for (int i = 1; i < m; i++)\n if (points[i].x < points[l].x)\n l = i; //find left most point\n int p = l, q;\n do {\n q = (p + 1) % m;\n for (int i = 0; i < m; i++)\n if (orient(points[p], points[i], points[q]) == 2)\n q = i;\n n[p] = q;\n p = q;\n } while (p != l);\n for (int i = 0; i < m; i++) {\n if (n[i] != -1)\n cout << \"(\" << points[i].x << \", \" << points[i].y << \")\\n\";\n }\n}\nint main() {\n P points[] = {{0, 4}, {2, 1}, {2, 3}, {4, 1}, {3, 0}, {1, 1}, {7, 6}};\n cout << \"The points in the convex hull are: \";\n int n = sizeof(points) / sizeof(points[0]);\n convexHull(points, n);\n return 0;\n}"
},
{
"code": null,
"e": 2799,
"s": 2729,
"text": "The points in the convex hull are: (0, 4)\n(4, 1)\n(3, 0)\n(1, 1)\n(7, 6)"
}
]
|
Program to print pyramid pattern - GeeksforGeeks | 20 Jan, 2022
Write to program to print the pyramid pattern formed of stars
Example :
Input: n = 6
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two for loops for every part of the pyramid. The two parts may be classified as upper part and lower part
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print Pyramid pattern#include<iostream>using namespace std; void pattern(int n){ // For printing the upper part of the pyramid for (int i = 1; i < n; i++){ for (int j = 1; j < i+1; j++){ cout <<" * "; } cout << endl ; } // For printing the lower part of pyramid for (int i = n; i > 0; i--){ for (int j = i; j > 0; j--){ cout << " * "; } cout << endl ; }} // Driver programint main(){ pattern(6); return 0;}
// Java program to print Pyramid patternimport java.io.*; class GFG{ public static void pattern(int n) { // For printing the upper // part of the pyramid for (int i = 1; i < n; i++) { for (int j = 1; j < i+1; j++) { System.out.print(" * "); } System.out.println(); } // For printing the lower // part of pyramid for (int i = n; i > 0; i--) { for (int j = i; j > 0; j--) { System.out.print(" * "); } System.out.println(); } } // Driver program public static void main(String args[]) { pattern(6); }} // This code is contributed by NIkita Tiwari.
# Python program to print Pyramid pattern def pattern(n): # For printing the upper part of pyramid for i in range (1, n+1): for j in range (1, i+1): print (" *",end=" ") print() # for printing the middle and lower part of pyramid for i in range (n, 1, -1): for j in range (i, 1, -1): print (" *",end=" ") print() # Driver programpattern(6)
// C# program to print Pyramid patternusing System; class GFG { public static void pattern(int n) { // For printing the upper // part of the pyramid for (int i = 1; i < n; i++) { for (int j = 1; j < i + 1; j++) { Console.Write(" * "); } Console.WriteLine(); } // For printing the lower // part of pyramid for (int i = n; i > 0; i--) { for (int j = i; j > 0; j--) { Console.Write(" * "); } Console.WriteLine(); } } // Driver program public static void Main() { pattern(6); }} // This code is contributed by vt_m.
<?php// PHP implementation to print// Pyramid pattern function pattern($n){ // For printing the upper part // of the pyramid for ($i = 1; $i < $n; $i++) { for ($j = 1; $j < $i+1; $j++) { echo " * "; } echo "\n" ; } // For printing the lower part // of pyramid for ($i = $n; $i > 0; $i--) { for ($j = $i; $j > 0; $j--) { echo " * "; } echo "\n" ; }} // Driver code$n=6;pattern($n); // This code is contributed by mits?>
<script> // JavaScript program to print Pyramid patternfunction pattern(n){ // For printing the upper // part of the pyramid for(var i = 1; i < n; i++) { for(var j = 1; j < i + 1; j++) { document.write(" * "); } document.write("<br>"); } // For printing the lower part of pyramid for(var i = n; i > 0; i--) { for(var j = i; j > 0; j--) { document.write(" * "); } document.write("<br>"); }} // Driver codepattern(6); // This code is contributed by rdtank </script>
Output :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Mithun Kumar
rdtank
amartyaghoshgfg
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Operator Overloading in C++
Overriding in Java
Friend class and function in C++
Polymorphism in C++
Types of Operating Systems
Python program to check if a string is palindrome or not
Inheritance in Java
Constructors in Java
Different ways of Reading a text file in Java | [
{
"code": null,
"e": 23806,
"s": 23778,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 23869,
"s": 23806,
"text": "Write to program to print the pyramid pattern formed of stars "
},
{
"code": null,
"e": 23880,
"s": 23869,
"text": "Example : "
},
{
"code": null,
"e": 24053,
"s": 23880,
"text": "Input: n = 6\nOutput:\n *\n * *\n * * *\n * * * *\n * * * * *\n * * * * * * \n * * * * *\n * * * *\n * * *\n * * \n *"
},
{
"code": null,
"e": 24258,
"s": 24053,
"text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two for loops for every part of the pyramid. The two parts may be classified as upper part and lower part "
},
{
"code": null,
"e": 24262,
"s": 24258,
"text": "C++"
},
{
"code": null,
"e": 24267,
"s": 24262,
"text": "Java"
},
{
"code": null,
"e": 24275,
"s": 24267,
"text": "Python3"
},
{
"code": null,
"e": 24278,
"s": 24275,
"text": "C#"
},
{
"code": null,
"e": 24282,
"s": 24278,
"text": "PHP"
},
{
"code": null,
"e": 24293,
"s": 24282,
"text": "Javascript"
},
{
"code": "// C++ program to print Pyramid pattern#include<iostream>using namespace std; void pattern(int n){ // For printing the upper part of the pyramid for (int i = 1; i < n; i++){ for (int j = 1; j < i+1; j++){ cout <<\" * \"; } cout << endl ; } // For printing the lower part of pyramid for (int i = n; i > 0; i--){ for (int j = i; j > 0; j--){ cout << \" * \"; } cout << endl ; }} // Driver programint main(){ pattern(6); return 0;}",
"e": 24811,
"s": 24293,
"text": null
},
{
"code": "// Java program to print Pyramid patternimport java.io.*; class GFG{ public static void pattern(int n) { // For printing the upper // part of the pyramid for (int i = 1; i < n; i++) { for (int j = 1; j < i+1; j++) { System.out.print(\" * \"); } System.out.println(); } // For printing the lower // part of pyramid for (int i = n; i > 0; i--) { for (int j = i; j > 0; j--) { System.out.print(\" * \"); } System.out.println(); } } // Driver program public static void main(String args[]) { pattern(6); }} // This code is contributed by NIkita Tiwari.",
"e": 25586,
"s": 24811,
"text": null
},
{
"code": "# Python program to print Pyramid pattern def pattern(n): # For printing the upper part of pyramid for i in range (1, n+1): for j in range (1, i+1): print (\" *\",end=\" \") print() # for printing the middle and lower part of pyramid for i in range (n, 1, -1): for j in range (i, 1, -1): print (\" *\",end=\" \") print() # Driver programpattern(6)",
"e": 25997,
"s": 25586,
"text": null
},
{
"code": "// C# program to print Pyramid patternusing System; class GFG { public static void pattern(int n) { // For printing the upper // part of the pyramid for (int i = 1; i < n; i++) { for (int j = 1; j < i + 1; j++) { Console.Write(\" * \"); } Console.WriteLine(); } // For printing the lower // part of pyramid for (int i = n; i > 0; i--) { for (int j = i; j > 0; j--) { Console.Write(\" * \"); } Console.WriteLine(); } } // Driver program public static void Main() { pattern(6); }} // This code is contributed by vt_m.",
"e": 26691,
"s": 25997,
"text": null
},
{
"code": "<?php// PHP implementation to print// Pyramid pattern function pattern($n){ // For printing the upper part // of the pyramid for ($i = 1; $i < $n; $i++) { for ($j = 1; $j < $i+1; $j++) { echo \" * \"; } echo \"\\n\" ; } // For printing the lower part // of pyramid for ($i = $n; $i > 0; $i--) { for ($j = $i; $j > 0; $j--) { echo \" * \"; } echo \"\\n\" ; }} // Driver code$n=6;pattern($n); // This code is contributed by mits?>",
"e": 27219,
"s": 26691,
"text": null
},
{
"code": "<script> // JavaScript program to print Pyramid patternfunction pattern(n){ // For printing the upper // part of the pyramid for(var i = 1; i < n; i++) { for(var j = 1; j < i + 1; j++) { document.write(\" * \"); } document.write(\"<br>\"); } // For printing the lower part of pyramid for(var i = n; i > 0; i--) { for(var j = i; j > 0; j--) { document.write(\" * \"); } document.write(\"<br>\"); }} // Driver codepattern(6); // This code is contributed by rdtank </script>",
"e": 27798,
"s": 27219,
"text": null
},
{
"code": null,
"e": 27808,
"s": 27798,
"text": "Output : "
},
{
"code": null,
"e": 27916,
"s": 27808,
"text": " *\n * *\n * * *\n * * * *\n * * * * *\n * * * * * *\n * * * * *\n * * * *\n * * *\n * *\n *"
},
{
"code": null,
"e": 28085,
"s": 27916,
"text": "This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 28098,
"s": 28085,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 28105,
"s": 28098,
"text": "rdtank"
},
{
"code": null,
"e": 28121,
"s": 28105,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 28138,
"s": 28121,
"text": "pattern-printing"
},
{
"code": null,
"e": 28157,
"s": 28138,
"text": "School Programming"
},
{
"code": null,
"e": 28174,
"s": 28157,
"text": "pattern-printing"
},
{
"code": null,
"e": 28272,
"s": 28174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28281,
"s": 28272,
"text": "Comments"
},
{
"code": null,
"e": 28294,
"s": 28281,
"text": "Old Comments"
},
{
"code": null,
"e": 28313,
"s": 28294,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28341,
"s": 28313,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28360,
"s": 28341,
"text": "Overriding in Java"
},
{
"code": null,
"e": 28393,
"s": 28360,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28413,
"s": 28393,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28440,
"s": 28413,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 28497,
"s": 28440,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 28517,
"s": 28497,
"text": "Inheritance in Java"
},
{
"code": null,
"e": 28538,
"s": 28517,
"text": "Constructors in Java"
}
]
|
Deep Learning in Java. Java, one of the most popular... | by Keerthan Vasist | Towards Data Science | Java has been one of the most popular programming languages in enterprise for a long time and has a massive ecosystem of libraries, and frameworks, and a large community of developers. However, there are very limited options offered in Java for deep learning applications. Currently, most deep learning models are written and trained in Python. This presents an additional barrier to entry for Java developers who want to enter this area, as they have to learn both a new programming language and the complex domain of deep learning. In order to lower the barrier of entry into deep learning for Java developers, AWS built Deep Java Library (DJL), an open source deep learning framework in Java to bridge the gap for Java developers by supporting any deep learning engine, such as Apache MXNet, PyTorch, or TensorFlow to run training and inference natively in Java. It also contains a powerful ModelZoo design that allows you to manage trained models and load them in a single line of code. The built-in ModelZoo currently supports more than 70 pre-trained and ready to use models from GluonCV, HuggingFace, TorchHub and Keras. If you’ve been a Java developer and are interested in exploring deep learning, Deep Java Library (DJL) is a great place to start. In this tutorial, we walk through an example demonstrating the training capabilities of DJL by training a simple model on the popular MNIST dataset.
Machine learning is the process of letting the computer learn the specifications of the given task from data through the use of various statistical techniques. This ability to learn the features of a task allows computers to perform complex tasks, such as detecting an object in an image, that were generally considered to be beyond the scope of computers because of the difficulty of providing exact specifications for every possible case. Deep learning is a branch of machine learning based on artificial neural networks. An artificial neural network is a programming paradigm inspired by the human brain that helps the computer learn and perform tasks based on observational data. Deep learning is a collection of powerful techniques that can be leveraged to help train large artificial neural networks to perform complex tasks. Deep learning techniques have proven to be very effective at solving complex tasks like object detection, action recognition, machine translation, natural language understanding among others.
You can use the following configuration in your gradle project to import the required dependencies. In this example, we use the api package which contains the core API of the DJL project, and the basicdataset package which contains some of the basic datasets in DJL. Since we are training with the MXNet engine, we are also going to import the mxnet-engine package, and the mxnet-native-auto package.
plugins { id 'java'}repositories { jcenter()}dependencies { implementation "ai.djl:api:0.8.0" implementation "ai.djl:basicdataset:0.8.0" // MXNet runtimeOnly "ai.djl.mxnet:mxnet-engine:0.8.0" runtimeOnly "ai.djl.mxnet:mxnet-native-auto:1.7.0-backport"}
NDArray is the core data structure for all mathematical computations in DJL. An NDArray represents a multidimensional, fixed-size homogeneous array. NDArray behaves similar to the python program numpy. NDManager is the manager of NDArray. NDManager manages the lifecycle of NDArray, and is an essential part of memory management in DJL. Every NDArray created by an instance of NDManager will be closed once that NDManager is closed. NDManager, and NDArray both extend AutoCloseable. To know and understand the usage of NDArray and NDManager better, see this blog post.
In DJL, training and inference start with a Model. In this article, we concentrate on the training process. To start the training process we create a new instance of the Model class. The Model class also extends AutoCloseable. So, it is created with a try-with-resources.
try (Model model = Model.newInstance()) { ... // training process takes place here ...}
The MNIST database (Modified National Institute of Standards and Technology database) is a large database of handwritten digits that is commonly used for training various image processing systems. The MNIST dataset is readily available in DJL. The shape of an individual image from the MNIST dataset in DJL is (28, 28). If you wish to train a model on your own dataset, you can do that by adding your own dataset by following the instructions here.
In order to train your model, you first need to load the dataset.
int batchSize = 32;Mnist trainingDataset = Mnist.builder() .optUsage(Usage.TRAIN) .setSampling(batchSize, true) .build();Mnist validationDataset = Mnist.builder() .optUsage(Usage.TEST) .setSampling(batchSize, true) .build();
This code creates training and validation datasets. The dataset is also configured to sample the dataset randomly. There are further configurations made on the dataset like applying transforms on the images, or limiting the size of the dataset.
Once the data is ready, you need to construct the neural network that you want to train. In DJL, a neural network is represented by a Block. A Block is a composable function that forms a neural network. They can represent single operation, parts of a neural network, and even the whole neural network. A Block can have parameters and child blocks. During the training process, the parameters are updated, and the child blocks are also trained. This recursively updates the parameters of all its children as well. When building these block functions, the easiest way is to use composition. Blocks can be built by combining other blocks. We refer to the containing block as the parent and the sub-blocks as the children. We provide several helpers to make it easy to build common block composition structures. SequentialBlock is a container block whose children form a chain of blocks where each child block feeds its output to the next child block in a sequence. ParallelBlock is a container block whose children are executed in parallel, and the output of the blocks are combined according to a combining function specified. LambdaBlock is a block with an operating function that has to be specified by the user.
We are going to build a simple MLP (Multi-layer Perceptron). A multilayer perceptron (MLP) is a feedforward artificial neural network that generates a set of outputs from a set of inputs. An MLP is characterized by several layers of input nodes connected as a directed graph between the input and output layers. It can be constructed by using a number of LinearBlock within a SequentialBlock.
int input = 768;int output = 10;int[] hidden = new int[] {128, 64};SequentialBlock sequentialBlock = new SequentialBlock();sequentialBlock.add(Blocks.batchFlattenBlock(input));for (int hiddenSize : hidden) { sequentialBlock.add(Linear.builder().setUnits(hiddenSize).build()); sequentialBlock.add(activation);}sequentialBlock.add(Linear.builder().setUnits(output).build());
DJL also provides a pre-constructed Mlp block that we can use directly.
Block block = new Mlp( Mnist.IMAGE_HEIGHT * Mnist.IMAGE_WIDTH, Mnist.NUM_CLASSES, new int[] {128, 64});
Now that you have created a new instance of the model, prepared the dataset, and constructed a block, you are ready to start training. In deep learning, training involves the following steps:
Initialization: This step initializes the blocks, and creates its corresponding parameters according to the specified Initializer schemes.
Forward: This step executes the computations represented by the Block, and generates the output.
Loss computation: In this step, you compute the loss by applying the specified Loss function to the output and label provided.
Backward: During this step, you use the loss, and back-propagate the gradients along the neural network.
Step: During this step, you update the values of the parameters of the block based on the specified Optimizer.
However, DJL abstracts all of these steps through the Trainer. The Trainer can be created by specifying the training configurations such as the Initializer, Loss, and Optimizer. These configurations and more can be set by using the TrainingConfig. Some of the other configurations that can be set are:
Device - the devices on which the training must occur
TrainingListeners - listeners that listen for various stages during the training process and execute specific functions like logging and evaluation. Users can implement custom TrainingListener as necessary.
DefaultTrainingConfig config = new DefaultTrainingConfig(Loss.softmaxCrossEntropyLoss()) .addEvaluator(new Accuracy()) .optDevices(Device.getDevices(arguments.getMaxGpus())) .addTrainingListeners(TrainingListener.Defaults.logging(arguments.getOutputDir()));try (Trainer trainer = model.newTrainer(config)){ // training happens here}
Once a trainer is created, it has to be initialized with the Shape of the inputs. Then, you call the fit() method to start training. The fit() method trains the model on the dataset for a specified number of epochs, runs validation, and saves the model in the specified directory in the filesystem.
/** MNIST is 28x28 grayscale image and pre processed into 28 * 28 NDArray.* 1st axis is batch axis, we can use 1 for initialization.*/Shape inputShape = new Shape(1, Mnist.IMAGE_HEIGHT * Mnist.IMAGE_WIDTH);int numEpoch = 5;String outputDir = "/build/model";// initialize trainer with proper input shapetrainer.initialize(inputShape);TrainingUtils.fit(trainer, numEpoch, trainingSet, validateSet, outputDir, "mlp");
That’s it. Congratulations! You have trained your first deep learning model using DJL! You can monitor the training process on the console, or however the listeners are implemented. If you use the default listeners, your output should be similar to the following.
[INFO ] - Downloading libmxnet.dylib ...[INFO ] - Training on: cpu().[INFO ] - Load MXNet Engine Version 1.7.0 in 0.131 ms.Training: 100% |████████████████████████████████████████| Accuracy: 0.93, SoftmaxCrossEntropyLoss: 0.24, speed: 1235.20 items/secValidating: 100% |████████████████████████████████████████|[INFO ] - Epoch 1 finished.[INFO ] - Train: Accuracy: 0.93, SoftmaxCrossEntropyLoss: 0.24[INFO ] - Validate: Accuracy: 0.95, SoftmaxCrossEntropyLoss: 0.14Training: 100% |████████████████████████████████████████| Accuracy: 0.97, SoftmaxCrossEntropyLoss: 0.10, speed: 2851.06 items/secValidating: 100% |████████████████████████████████████████|[INFO ] - Epoch 2 finished.NG [1m 41s][INFO ] - Train: Accuracy: 0.97, SoftmaxCrossEntropyLoss: 0.10[INFO ] - Validate: Accuracy: 0.97, SoftmaxCrossEntropyLoss: 0.09[INFO ] - train P50: 12.756 ms, P90: 21.044 ms[INFO ] - forward P50: 0.375 ms, P90: 0.607 ms[INFO ] - training-metrics P50: 0.021 ms, P90: 0.034 ms[INFO ] - backward P50: 0.608 ms, P90: 0.973 ms[INFO ] - step P50: 0.543 ms, P90: 0.869 ms[INFO ] - epoch P50: 35.989 s, P90: 35.989 s
Once training is complete, we can use the trained model to run inference to get the predictions. You can follow the Inference with your model jupyter notebook to run inference on a saved model. You can also run the complete code directly by following the instructions in Train Handwritten Digit Recognition using Multilayer Perceptron (MLP) model.
In this article, we introduced you to deep learning and walked-through a simple training example using DJL. While the example is a simple example, DJL offers the same abstractions for more complex deep learning models. Follow our GitHub, demo repository, Slack channel and Twitter for more documentation and examples of DJL! | [
{
"code": null,
"e": 1583,
"s": 172,
"text": "Java has been one of the most popular programming languages in enterprise for a long time and has a massive ecosystem of libraries, and frameworks, and a large community of developers. However, there are very limited options offered in Java for deep learning applications. Currently, most deep learning models are written and trained in Python. This presents an additional barrier to entry for Java developers who want to enter this area, as they have to learn both a new programming language and the complex domain of deep learning. In order to lower the barrier of entry into deep learning for Java developers, AWS built Deep Java Library (DJL), an open source deep learning framework in Java to bridge the gap for Java developers by supporting any deep learning engine, such as Apache MXNet, PyTorch, or TensorFlow to run training and inference natively in Java. It also contains a powerful ModelZoo design that allows you to manage trained models and load them in a single line of code. The built-in ModelZoo currently supports more than 70 pre-trained and ready to use models from GluonCV, HuggingFace, TorchHub and Keras. If you’ve been a Java developer and are interested in exploring deep learning, Deep Java Library (DJL) is a great place to start. In this tutorial, we walk through an example demonstrating the training capabilities of DJL by training a simple model on the popular MNIST dataset."
},
{
"code": null,
"e": 2608,
"s": 1583,
"text": "Machine learning is the process of letting the computer learn the specifications of the given task from data through the use of various statistical techniques. This ability to learn the features of a task allows computers to perform complex tasks, such as detecting an object in an image, that were generally considered to be beyond the scope of computers because of the difficulty of providing exact specifications for every possible case. Deep learning is a branch of machine learning based on artificial neural networks. An artificial neural network is a programming paradigm inspired by the human brain that helps the computer learn and perform tasks based on observational data. Deep learning is a collection of powerful techniques that can be leveraged to help train large artificial neural networks to perform complex tasks. Deep learning techniques have proven to be very effective at solving complex tasks like object detection, action recognition, machine translation, natural language understanding among others."
},
{
"code": null,
"e": 3009,
"s": 2608,
"text": "You can use the following configuration in your gradle project to import the required dependencies. In this example, we use the api package which contains the core API of the DJL project, and the basicdataset package which contains some of the basic datasets in DJL. Since we are training with the MXNet engine, we are also going to import the mxnet-engine package, and the mxnet-native-auto package."
},
{
"code": null,
"e": 3310,
"s": 3009,
"text": "plugins { id 'java'}repositories { jcenter()}dependencies { implementation \"ai.djl:api:0.8.0\" implementation \"ai.djl:basicdataset:0.8.0\" // MXNet runtimeOnly \"ai.djl.mxnet:mxnet-engine:0.8.0\" runtimeOnly \"ai.djl.mxnet:mxnet-native-auto:1.7.0-backport\"}"
},
{
"code": null,
"e": 3881,
"s": 3310,
"text": "NDArray is the core data structure for all mathematical computations in DJL. An NDArray represents a multidimensional, fixed-size homogeneous array. NDArray behaves similar to the python program numpy. NDManager is the manager of NDArray. NDManager manages the lifecycle of NDArray, and is an essential part of memory management in DJL. Every NDArray created by an instance of NDManager will be closed once that NDManager is closed. NDManager, and NDArray both extend AutoCloseable. To know and understand the usage of NDArray and NDManager better, see this blog post."
},
{
"code": null,
"e": 4153,
"s": 3881,
"text": "In DJL, training and inference start with a Model. In this article, we concentrate on the training process. To start the training process we create a new instance of the Model class. The Model class also extends AutoCloseable. So, it is created with a try-with-resources."
},
{
"code": null,
"e": 4250,
"s": 4153,
"text": "try (Model model = Model.newInstance()) { ... // training process takes place here ...}"
},
{
"code": null,
"e": 4699,
"s": 4250,
"text": "The MNIST database (Modified National Institute of Standards and Technology database) is a large database of handwritten digits that is commonly used for training various image processing systems. The MNIST dataset is readily available in DJL. The shape of an individual image from the MNIST dataset in DJL is (28, 28). If you wish to train a model on your own dataset, you can do that by adding your own dataset by following the instructions here."
},
{
"code": null,
"e": 4765,
"s": 4699,
"text": "In order to train your model, you first need to load the dataset."
},
{
"code": null,
"e": 5032,
"s": 4765,
"text": "int batchSize = 32;Mnist trainingDataset = Mnist.builder() .optUsage(Usage.TRAIN) .setSampling(batchSize, true) .build();Mnist validationDataset = Mnist.builder() .optUsage(Usage.TEST) .setSampling(batchSize, true) .build();"
},
{
"code": null,
"e": 5277,
"s": 5032,
"text": "This code creates training and validation datasets. The dataset is also configured to sample the dataset randomly. There are further configurations made on the dataset like applying transforms on the images, or limiting the size of the dataset."
},
{
"code": null,
"e": 6493,
"s": 5277,
"text": "Once the data is ready, you need to construct the neural network that you want to train. In DJL, a neural network is represented by a Block. A Block is a composable function that forms a neural network. They can represent single operation, parts of a neural network, and even the whole neural network. A Block can have parameters and child blocks. During the training process, the parameters are updated, and the child blocks are also trained. This recursively updates the parameters of all its children as well. When building these block functions, the easiest way is to use composition. Blocks can be built by combining other blocks. We refer to the containing block as the parent and the sub-blocks as the children. We provide several helpers to make it easy to build common block composition structures. SequentialBlock is a container block whose children form a chain of blocks where each child block feeds its output to the next child block in a sequence. ParallelBlock is a container block whose children are executed in parallel, and the output of the blocks are combined according to a combining function specified. LambdaBlock is a block with an operating function that has to be specified by the user."
},
{
"code": null,
"e": 6886,
"s": 6493,
"text": "We are going to build a simple MLP (Multi-layer Perceptron). A multilayer perceptron (MLP) is a feedforward artificial neural network that generates a set of outputs from a set of inputs. An MLP is characterized by several layers of input nodes connected as a directed graph between the input and output layers. It can be constructed by using a number of LinearBlock within a SequentialBlock."
},
{
"code": null,
"e": 7265,
"s": 6886,
"text": "int input = 768;int output = 10;int[] hidden = new int[] {128, 64};SequentialBlock sequentialBlock = new SequentialBlock();sequentialBlock.add(Blocks.batchFlattenBlock(input));for (int hiddenSize : hidden) { sequentialBlock.add(Linear.builder().setUnits(hiddenSize).build()); sequentialBlock.add(activation);}sequentialBlock.add(Linear.builder().setUnits(output).build());"
},
{
"code": null,
"e": 7337,
"s": 7265,
"text": "DJL also provides a pre-constructed Mlp block that we can use directly."
},
{
"code": null,
"e": 7462,
"s": 7337,
"text": "Block block = new Mlp( Mnist.IMAGE_HEIGHT * Mnist.IMAGE_WIDTH, Mnist.NUM_CLASSES, new int[] {128, 64});"
},
{
"code": null,
"e": 7654,
"s": 7462,
"text": "Now that you have created a new instance of the model, prepared the dataset, and constructed a block, you are ready to start training. In deep learning, training involves the following steps:"
},
{
"code": null,
"e": 7793,
"s": 7654,
"text": "Initialization: This step initializes the blocks, and creates its corresponding parameters according to the specified Initializer schemes."
},
{
"code": null,
"e": 7890,
"s": 7793,
"text": "Forward: This step executes the computations represented by the Block, and generates the output."
},
{
"code": null,
"e": 8017,
"s": 7890,
"text": "Loss computation: In this step, you compute the loss by applying the specified Loss function to the output and label provided."
},
{
"code": null,
"e": 8122,
"s": 8017,
"text": "Backward: During this step, you use the loss, and back-propagate the gradients along the neural network."
},
{
"code": null,
"e": 8233,
"s": 8122,
"text": "Step: During this step, you update the values of the parameters of the block based on the specified Optimizer."
},
{
"code": null,
"e": 8535,
"s": 8233,
"text": "However, DJL abstracts all of these steps through the Trainer. The Trainer can be created by specifying the training configurations such as the Initializer, Loss, and Optimizer. These configurations and more can be set by using the TrainingConfig. Some of the other configurations that can be set are:"
},
{
"code": null,
"e": 8589,
"s": 8535,
"text": "Device - the devices on which the training must occur"
},
{
"code": null,
"e": 8796,
"s": 8589,
"text": "TrainingListeners - listeners that listen for various stages during the training process and execute specific functions like logging and evaluation. Users can implement custom TrainingListener as necessary."
},
{
"code": null,
"e": 9177,
"s": 8796,
"text": "DefaultTrainingConfig config = new DefaultTrainingConfig(Loss.softmaxCrossEntropyLoss()) .addEvaluator(new Accuracy()) .optDevices(Device.getDevices(arguments.getMaxGpus())) .addTrainingListeners(TrainingListener.Defaults.logging(arguments.getOutputDir()));try (Trainer trainer = model.newTrainer(config)){ // training happens here}"
},
{
"code": null,
"e": 9476,
"s": 9177,
"text": "Once a trainer is created, it has to be initialized with the Shape of the inputs. Then, you call the fit() method to start training. The fit() method trains the model on the dataset for a specified number of epochs, runs validation, and saves the model in the specified directory in the filesystem."
},
{
"code": null,
"e": 9891,
"s": 9476,
"text": "/** MNIST is 28x28 grayscale image and pre processed into 28 * 28 NDArray.* 1st axis is batch axis, we can use 1 for initialization.*/Shape inputShape = new Shape(1, Mnist.IMAGE_HEIGHT * Mnist.IMAGE_WIDTH);int numEpoch = 5;String outputDir = \"/build/model\";// initialize trainer with proper input shapetrainer.initialize(inputShape);TrainingUtils.fit(trainer, numEpoch, trainingSet, validateSet, outputDir, \"mlp\");"
},
{
"code": null,
"e": 10155,
"s": 9891,
"text": "That’s it. Congratulations! You have trained your first deep learning model using DJL! You can monitor the training process on the console, or however the listeners are implemented. If you use the default listeners, your output should be similar to the following."
},
{
"code": null,
"e": 11263,
"s": 10155,
"text": "[INFO ] - Downloading libmxnet.dylib ...[INFO ] - Training on: cpu().[INFO ] - Load MXNet Engine Version 1.7.0 in 0.131 ms.Training: 100% |████████████████████████████████████████| Accuracy: 0.93, SoftmaxCrossEntropyLoss: 0.24, speed: 1235.20 items/secValidating: 100% |████████████████████████████████████████|[INFO ] - Epoch 1 finished.[INFO ] - Train: Accuracy: 0.93, SoftmaxCrossEntropyLoss: 0.24[INFO ] - Validate: Accuracy: 0.95, SoftmaxCrossEntropyLoss: 0.14Training: 100% |████████████████████████████████████████| Accuracy: 0.97, SoftmaxCrossEntropyLoss: 0.10, speed: 2851.06 items/secValidating: 100% |████████████████████████████████████████|[INFO ] - Epoch 2 finished.NG [1m 41s][INFO ] - Train: Accuracy: 0.97, SoftmaxCrossEntropyLoss: 0.10[INFO ] - Validate: Accuracy: 0.97, SoftmaxCrossEntropyLoss: 0.09[INFO ] - train P50: 12.756 ms, P90: 21.044 ms[INFO ] - forward P50: 0.375 ms, P90: 0.607 ms[INFO ] - training-metrics P50: 0.021 ms, P90: 0.034 ms[INFO ] - backward P50: 0.608 ms, P90: 0.973 ms[INFO ] - step P50: 0.543 ms, P90: 0.869 ms[INFO ] - epoch P50: 35.989 s, P90: 35.989 s"
},
{
"code": null,
"e": 11611,
"s": 11263,
"text": "Once training is complete, we can use the trained model to run inference to get the predictions. You can follow the Inference with your model jupyter notebook to run inference on a saved model. You can also run the complete code directly by following the instructions in Train Handwritten Digit Recognition using Multilayer Perceptron (MLP) model."
}
]
|
How to Generate Word Clouds in R. Simple Steps on How and When to Use... | by Céline Van den Rul | Towards Data Science | In the following section, I show you 4 simple steps to follow if you want to generate a word cloud with R.
To generate word clouds, you need to download the wordcloud package in R as well as the RcolorBrewer package for the colours. Note that there is also a wordcloud2 package, with a slightly different design and fun applications. I will show you how to use both packages.
install.packages("wordcloud")library(wordcloud)install.packages("RColorBrewer")library(RColorBrewer)install.packages("wordcloud2)library(wordcloud2)
Most often, word clouds are used to analyse twitter data or a corpus of text. If you’re analysing twitter data, simply upload your data by using the rtweet package (see this article for more info on this). If you’re working on a speech, article or any other type of text, make sure to load your text data as a corpus. A useful way to do this is to use the tm package.
install.packages("tm")library(tm)#Create a vector containing only the texttext <- data$text# Create a corpus docs <- Corpus(VectorSource(text))
Cleaning is an essential step to take before you generate your wordcloud. Indeed, for your analysis to bring useful insights, you may want to remove special characters, numbers or punctuation from your text. In addition, you should remove common stop words in order to produce meaningful results and avoid the most common frequent words such as “I” or “the” to appear in the word cloud.
If you’re working with tweets, use the following line of code to clean your text.
gsub("https\\S*", "", tweets$text) gsub("@\\S*", "", tweets$text) gsub("amp", "", tweets$text) gsub("[\r\n]", "", tweets$text)gsub("[[:punct:]]", "", data$text)
If you’re working with a corpus, there are several packages you can use to clean your text. The following lines of code show you how to do this using the tm package.
docs <- docs %>% tm_map(removeNumbers) %>% tm_map(removePunctuation) %>% tm_map(stripWhitespace)docs <- tm_map(docs, content_transformer(tolower))docs <- tm_map(docs, removeWords, stopwords("english"))
What you want to do as a next step is to have a dataframe containing each word in your first column and their frequency in the second column.
This can be done by creating a document term matrix with the TermDocumentMatrix function from the tm package.
dtm <- TermDocumentMatrix(docs) matrix <- as.matrix(dtm) words <- sort(rowSums(matrix),decreasing=TRUE) df <- data.frame(word = names(words),freq=words)
Alternatively, and especially if you’re using tweets, you can use the tidytext package.
tweets_words <- tweets %>% select(text) %>% unnest_tokens(word, text)words <- tweets_words %>% count(word, sort=TRUE)
The wordcloud package is the most classic way to generate a word cloud. The following line of code shows you how to properly set the arguments. As an example, I chose to work with the speeches given by US Presidents at the United Nations General Assembly.
set.seed(1234) # for reproducibility wordcloud(words = df$word, freq = df$freq, min.freq = 1, max.words=200, random.order=FALSE, rot.per=0.35, colors=brewer.pal(8, "Dark2"))
It may happen that your word cloud crops certain words or simply doesn’t show them. If this happens, make sure to add the argument scale=c(3.5,0.25) and play around with the numbers to make the word cloud fit.
Another common mistake with word clouds is to show too many words that have little frequency. If this is the case, make sure to adjust the minimum frequency argument (min.freq=...) in order to render your word cloud more meaningful.
The wordcloud2 package is a bit more fun to use, allowing us to do some more advanced visualisations. For instance, you can choose your wordcloud to appear in a specific shape or even letter (see this vignette for a useful tutorial). As an example, I used the same corpus of UN speeches and generated the two word clouds shown below. Cool, right?
wordcloud2(data=df, size=1.6, color='random-dark')
wordcloud2(data=df, size = 0.7, shape = 'pentagon')
Word clouds are killer visualisation tools. They present text data in a simple and clear format, that of a cloud in which the size of the words depends on their respective frequencies. As such, they are visually nice to look at as well as easy and quick to understand.
Word clouds are great communication tools. They are incredibly handy for anyone wishing to communicate a basic insight based on text data — whether it’s to analyse a speech, capture the conversation on social media or report on customer reviews.
Word clouds are insightful. Visually engaging, word clouds allow us to draw several insights quickly, allowing for some flexibility in their interpretation. Their visual format stimulates us to think and draw the best insight depending on what we wish to analyse.
Yes, word clouds are insightful, great communication and visualisation tools. Nonetheless, they also have their limits and understanding this is key to know when to use them and therefore also when not to.
Word clouds are essentially a descriptive tool. They should therefore only be used to capture basic qualitative insights. Visually attractive, they are a great tool to start a conversation, a presentation or an analysis. However, their analysis is limited to insights that simply don’t have the same calibre as more extensive statistical analysis.
I regularly write articles about Data Science and Natural Language Processing. Follow me on Twitter or Medium to check out more articles like these or simply to keep updated about the next ones. Thanks for reading! | [
{
"code": null,
"e": 279,
"s": 172,
"text": "In the following section, I show you 4 simple steps to follow if you want to generate a word cloud with R."
},
{
"code": null,
"e": 548,
"s": 279,
"text": "To generate word clouds, you need to download the wordcloud package in R as well as the RcolorBrewer package for the colours. Note that there is also a wordcloud2 package, with a slightly different design and fun applications. I will show you how to use both packages."
},
{
"code": null,
"e": 697,
"s": 548,
"text": "install.packages(\"wordcloud\")library(wordcloud)install.packages(\"RColorBrewer\")library(RColorBrewer)install.packages(\"wordcloud2)library(wordcloud2)"
},
{
"code": null,
"e": 1065,
"s": 697,
"text": "Most often, word clouds are used to analyse twitter data or a corpus of text. If you’re analysing twitter data, simply upload your data by using the rtweet package (see this article for more info on this). If you’re working on a speech, article or any other type of text, make sure to load your text data as a corpus. A useful way to do this is to use the tm package."
},
{
"code": null,
"e": 1210,
"s": 1065,
"text": "install.packages(\"tm\")library(tm)#Create a vector containing only the texttext <- data$text# Create a corpus docs <- Corpus(VectorSource(text))"
},
{
"code": null,
"e": 1597,
"s": 1210,
"text": "Cleaning is an essential step to take before you generate your wordcloud. Indeed, for your analysis to bring useful insights, you may want to remove special characters, numbers or punctuation from your text. In addition, you should remove common stop words in order to produce meaningful results and avoid the most common frequent words such as “I” or “the” to appear in the word cloud."
},
{
"code": null,
"e": 1679,
"s": 1597,
"text": "If you’re working with tweets, use the following line of code to clean your text."
},
{
"code": null,
"e": 1840,
"s": 1679,
"text": "gsub(\"https\\\\S*\", \"\", tweets$text) gsub(\"@\\\\S*\", \"\", tweets$text) gsub(\"amp\", \"\", tweets$text) gsub(\"[\\r\\n]\", \"\", tweets$text)gsub(\"[[:punct:]]\", \"\", data$text)"
},
{
"code": null,
"e": 2006,
"s": 1840,
"text": "If you’re working with a corpus, there are several packages you can use to clean your text. The following lines of code show you how to do this using the tm package."
},
{
"code": null,
"e": 2211,
"s": 2006,
"text": "docs <- docs %>% tm_map(removeNumbers) %>% tm_map(removePunctuation) %>% tm_map(stripWhitespace)docs <- tm_map(docs, content_transformer(tolower))docs <- tm_map(docs, removeWords, stopwords(\"english\"))"
},
{
"code": null,
"e": 2353,
"s": 2211,
"text": "What you want to do as a next step is to have a dataframe containing each word in your first column and their frequency in the second column."
},
{
"code": null,
"e": 2463,
"s": 2353,
"text": "This can be done by creating a document term matrix with the TermDocumentMatrix function from the tm package."
},
{
"code": null,
"e": 2616,
"s": 2463,
"text": "dtm <- TermDocumentMatrix(docs) matrix <- as.matrix(dtm) words <- sort(rowSums(matrix),decreasing=TRUE) df <- data.frame(word = names(words),freq=words)"
},
{
"code": null,
"e": 2704,
"s": 2616,
"text": "Alternatively, and especially if you’re using tweets, you can use the tidytext package."
},
{
"code": null,
"e": 2823,
"s": 2704,
"text": "tweets_words <- tweets %>% select(text) %>% unnest_tokens(word, text)words <- tweets_words %>% count(word, sort=TRUE)"
},
{
"code": null,
"e": 3079,
"s": 2823,
"text": "The wordcloud package is the most classic way to generate a word cloud. The following line of code shows you how to properly set the arguments. As an example, I chose to work with the speeches given by US Presidents at the United Nations General Assembly."
},
{
"code": null,
"e": 3274,
"s": 3079,
"text": "set.seed(1234) # for reproducibility wordcloud(words = df$word, freq = df$freq, min.freq = 1, max.words=200, random.order=FALSE, rot.per=0.35, colors=brewer.pal(8, \"Dark2\"))"
},
{
"code": null,
"e": 3484,
"s": 3274,
"text": "It may happen that your word cloud crops certain words or simply doesn’t show them. If this happens, make sure to add the argument scale=c(3.5,0.25) and play around with the numbers to make the word cloud fit."
},
{
"code": null,
"e": 3717,
"s": 3484,
"text": "Another common mistake with word clouds is to show too many words that have little frequency. If this is the case, make sure to adjust the minimum frequency argument (min.freq=...) in order to render your word cloud more meaningful."
},
{
"code": null,
"e": 4064,
"s": 3717,
"text": "The wordcloud2 package is a bit more fun to use, allowing us to do some more advanced visualisations. For instance, you can choose your wordcloud to appear in a specific shape or even letter (see this vignette for a useful tutorial). As an example, I used the same corpus of UN speeches and generated the two word clouds shown below. Cool, right?"
},
{
"code": null,
"e": 4115,
"s": 4064,
"text": "wordcloud2(data=df, size=1.6, color='random-dark')"
},
{
"code": null,
"e": 4167,
"s": 4115,
"text": "wordcloud2(data=df, size = 0.7, shape = 'pentagon')"
},
{
"code": null,
"e": 4436,
"s": 4167,
"text": "Word clouds are killer visualisation tools. They present text data in a simple and clear format, that of a cloud in which the size of the words depends on their respective frequencies. As such, they are visually nice to look at as well as easy and quick to understand."
},
{
"code": null,
"e": 4682,
"s": 4436,
"text": "Word clouds are great communication tools. They are incredibly handy for anyone wishing to communicate a basic insight based on text data — whether it’s to analyse a speech, capture the conversation on social media or report on customer reviews."
},
{
"code": null,
"e": 4946,
"s": 4682,
"text": "Word clouds are insightful. Visually engaging, word clouds allow us to draw several insights quickly, allowing for some flexibility in their interpretation. Their visual format stimulates us to think and draw the best insight depending on what we wish to analyse."
},
{
"code": null,
"e": 5152,
"s": 4946,
"text": "Yes, word clouds are insightful, great communication and visualisation tools. Nonetheless, they also have their limits and understanding this is key to know when to use them and therefore also when not to."
},
{
"code": null,
"e": 5500,
"s": 5152,
"text": "Word clouds are essentially a descriptive tool. They should therefore only be used to capture basic qualitative insights. Visually attractive, they are a great tool to start a conversation, a presentation or an analysis. However, their analysis is limited to insights that simply don’t have the same calibre as more extensive statistical analysis."
}
]
|
Row wise sorting in 2D array - GeeksforGeeks | 06 Jul, 2021
Given a 2D array, sort each row of this array and print the result.Examples:
Input :
77 11 22 3
11 89 1 12
32 11 56 7
11 22 44 33
Output :
3 11 22 77
1 11 12 89
7 11 32 56
11 22 33 44
Input :
8 6 4 5
3 5 2 1
9 7 4 2
7 8 9 5
Output :
4 5 6 8
1 2 3 5
2 4 7 9
5 7 8 9
Method 1 (Using Bubble Sort) Start iterating through each row of the given 2D array, and sort elements of each row using an efficient sorting algorithm.
C++
Java
Python3
C#
Javascript
// C++ code to// sort 2D matrix row-wise#include<bits/stdc++.h>using namespace std; void sortRowWise(int m[][4], int r, int c){ // loop for rows of matrix for (int i = 0; i < r; i++) { // loop for column of matrix for (int j = 0; j < c; j++) { // loop for comparison and swapping for (int k = 0; k < c - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements swap(m[i][k], m[i][k + 1]); } } } } // printing the sorted matrix for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout << m[i][j] << " "; cout << endl; }} // Driver codeint main(){ int m[][4] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; int c = sizeof(m[0]) / sizeof(m[0][0]); int r = sizeof(m) / sizeof(m[0]); sortRowWise(m, r, c); return 0;} // This code is contributed by Rutvik_56
// Java code to sort 2D matrix row-wiseimport java.io.*; public class Sort2DMatrix { static int sortRowWise(int m[][]) { // loop for rows of matrix for (int i = 0; i < m.length; i++) { // loop for column of matrix for (int j = 0; j < m[i].length; j++) { // loop for comparison and swapping for (int k = 0; k < m[i].length - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements int t = m[i][k]; m[i][k] = m[i][k + 1]; m[i][k + 1] = t; } } } } // printing the sorted matrix for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) System.out.print(m[i][j] + " "); System.out.println(); } return 0; } // driver code public static void main(String args[]) { int m[][] = { { 9, 8, 7, 1 }, { 7, 3, 0, 2 }, { 9, 5, 3, 2 }, { 6, 3, 1, 2 } }; sortRowWise(m); }}
# Python3 code to sort 2D matrix row-wisedef sortRowWise(m): # loop for rows of matrix for i in range(len(m)): # loop for column of matrix for j in range(len(m[i])): # loop for comparison and swapping for k in range(len(m[i]) - j - 1): if (m[i][k] > m[i][k + 1]): # swapping of elements t = m[i][k] m[i][k] = m[i][k + 1] m[i][k + 1] = t # printing the sorted matrix for i in range(len(m)): for j in range(len(m[i])): print(m[i][j], end=" ") print() # Driver codem = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2],[ 6, 3, 1, 2 ]]sortRowWise(m) # This code is contributed by shubhamsingh10
// C# code to sort 2D matrix row-wiseusing System; class GFG{static int sortRowWise(int [,]m){ // loop for rows of matrix for (int i = 0; i < m.GetLength(0); i++) { // loop for column of matrix for (int j = 0; j < m.GetLength(1); j++) { // loop for comparison and swapping for (int k = 0; k < m.GetLength(1) - j - 1; k++) { if (m[i, k] > m[i, k + 1]) { // swapping of elements int t = m[i, k]; m[i, k] = m[i, k + 1]; m[i, k + 1] = t; } } } } // printing the sorted matrix for (int i = 0; i < m.GetLength(0); i++) { for (int j = 0; j < m.GetLength(1); j++) Console.Write(m[i, j] + " "); Console.WriteLine(); } return 0;} // Driver Codepublic static void Main(String []args){ int [,]m = {{ 9, 8, 7, 1 }, { 7, 3, 0, 2 }, { 9, 5, 3, 2 }, { 6, 3, 1, 2 }}; sortRowWise(m);}} // This code is contributed by 29AjayKumar
<script> // JavaScript Program to sort 2D matrix row-wise function sortRowWise(m) { // loop for rows of matrix for (let i = 0; i < m.length; i++) { // loop for column of matrix for (let j = 0; j < m[i].length; j++) { // loop for comparison and swapping for (let k = 0; k < m[i].length - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements let t = m[i][k]; m[i][k] = m[i][k + 1]; m[i][k + 1] = t; } } } } // printing the sorted matrix for (let i = 0; i < m.length; i++) { for (let j = 0; j < m[i].length; j++) document.write(m[i][j] + " "); document.write("<br/>"); } return 0; } // Driver code let m = [[ 9, 8, 7, 1 ], [ 7, 3, 0, 2 ], [ 9, 5, 3, 2 ], [ 6, 3, 1, 2 ]]; sortRowWise(m); // This code is contributed by sanjoy_62.</script>
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Method 2 (Using Library Function) The idea is to use Arrays.sort() for every row of the matrix.
C++
Java
Python3
C#
Javascript
// C++ code to sort 2D// matrix row-wise#include <bits/stdc++.h>using namespace std;#define M 4#define N 4 int sortRowWise(int m[M][N]){ // One by one sort // individual rows. for (int i = 0; i < M; i++) sort(m[i], m[i] + N); // Printing the sorted matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << (m[i][j]) << " "; cout << endl; }} // Driver codeint main(){ int m[M][N] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; sortRowWise(m);} // This code is contributed by gauravrajput1
// Java code to sort 2D matrix row-wiseimport java.io.*;import java.util.Arrays; public class Sort2DMatrix { static int sortRowWise(int m[][]) { // One by one sort individual rows. for (int i = 0; i < m.length; i++) Arrays.sort(m[i]); // printing the sorted matrix for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) System.out.print(m[i][j] + " "); System.out.println(); } return 0; } // driver code public static void main(String args[]) { int m[][] = { { 9, 8, 7, 1 }, { 7, 3, 0, 2 }, { 9, 5, 3, 2 }, { 6, 3, 1, 2 } }; sortRowWise(m); }}
# Python3 code to sort 2D matrix row-wisedef sortRowWise(m): # One by one sort individual rows. for i in range(len(m)): m[i].sort() # printing the sorted matrix for i in range(len(m)): for j in range(len(m[i])): print(m[i][j], end=" ") print() return 0 # Driver codem = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2 ],[ 6, 3, 1, 2]] sortRowWise(m) # This code is contributed by shubhamsingh10
// C# code to sort 2D// matrix row-wise using System;using System.Collections.Generic;class Sort2DMatrix{ public static int[] GetRow(int[,] matrix, int row){ var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector;} static int sortRowWise(int [,]m){ // One by one sort individual // rows. for (int i = 0; i < m.GetLength(0); i++) { for (int k = 0; k < m.GetLength(1); k++) for (int j = 0; j < m.GetLength(1) - k - 1; j++) if (m[i, j] > m[i, j + 1]) { // swap temp and arr[i] int temp = m[i, j]; m[i, j] = m[i, j + 1]; m[i, j + 1] = temp; } } // Printing the sorted matrix for (int i = 0; i < m.GetLength(0); i++) { for (int j = 0; j < m.GetLength(1); j++) Console.Write(m[i, j] + " "); Console.WriteLine(); } return 0;} // Driver codepublic static void Main(String []args){ int [,]m = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; sortRowWise(m);}} // This code is contributed by gauravrajput1
<script> // JavaScript code to sort 2D// matrix row-wise function GetRow(matrix, row){ var rowLength = matrix[0].length; var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row][i]; return rowVector;} function sortRowWise(m){ // One by one sort individual // rows. for (var i = 0; i < m.length; i++) { for (var k = 0; k < m[0].length; k++) for (var j = 0; j < m[0].length - k - 1; j++) if (m[i][j] > m[i][j + 1]) { // swap temp and arr[i] var temp = m[i][j]; m[i][j] = m[i][j + 1]; m[i][j + 1] = temp; } } // Printing the sorted matrix for (var i = 0; i < m.length; i++) { for (var j = 0; j < m[0].length; j++) document.write(m[i][j] + " "); document.write("<br>"); } return 0;} // Driver codevar m = [[9, 8, 7, 1], [7, 3, 0, 2], [9, 5, 3, 2], [6, 3, 1, 2]];sortRowWise(m); </script>
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Kadhir M
29AjayKumar
SHUBHAMSINGH10
rutvik_56
GauravRajput1
sanjoy_62
pratyushsingh034
noob2000
Java-Arrays
Matrix
Sorting
Sorting
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
Min Cost Path | DP-6 | [
{
"code": null,
"e": 24676,
"s": 24648,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 24754,
"s": 24676,
"text": "Given a 2D array, sort each row of this array and print the result.Examples: "
},
{
"code": null,
"e": 24943,
"s": 24754,
"text": "Input :\n77 11 22 3\n11 89 1 12\n32 11 56 7\n11 22 44 33\nOutput :\n3 11 22 77\n1 11 12 89\n7 11 32 56\n11 22 33 44\n\nInput :\n8 6 4 5\n3 5 2 1\n9 7 4 2\n7 8 9 5\nOutput :\n4 5 6 8\n1 2 3 5\n2 4 7 9\n5 7 8 9"
},
{
"code": null,
"e": 25098,
"s": 24943,
"text": "Method 1 (Using Bubble Sort) Start iterating through each row of the given 2D array, and sort elements of each row using an efficient sorting algorithm. "
},
{
"code": null,
"e": 25102,
"s": 25098,
"text": "C++"
},
{
"code": null,
"e": 25107,
"s": 25102,
"text": "Java"
},
{
"code": null,
"e": 25115,
"s": 25107,
"text": "Python3"
},
{
"code": null,
"e": 25118,
"s": 25115,
"text": "C#"
},
{
"code": null,
"e": 25129,
"s": 25118,
"text": "Javascript"
},
{
"code": "// C++ code to// sort 2D matrix row-wise#include<bits/stdc++.h>using namespace std; void sortRowWise(int m[][4], int r, int c){ // loop for rows of matrix for (int i = 0; i < r; i++) { // loop for column of matrix for (int j = 0; j < c; j++) { // loop for comparison and swapping for (int k = 0; k < c - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements swap(m[i][k], m[i][k + 1]); } } } } // printing the sorted matrix for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout << m[i][j] << \" \"; cout << endl; }} // Driver codeint main(){ int m[][4] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; int c = sizeof(m[0]) / sizeof(m[0][0]); int r = sizeof(m) / sizeof(m[0]); sortRowWise(m, r, c); return 0;} // This code is contributed by Rutvik_56",
"e": 26067,
"s": 25129,
"text": null
},
{
"code": "// Java code to sort 2D matrix row-wiseimport java.io.*; public class Sort2DMatrix { static int sortRowWise(int m[][]) { // loop for rows of matrix for (int i = 0; i < m.length; i++) { // loop for column of matrix for (int j = 0; j < m[i].length; j++) { // loop for comparison and swapping for (int k = 0; k < m[i].length - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements int t = m[i][k]; m[i][k] = m[i][k + 1]; m[i][k + 1] = t; } } } } // printing the sorted matrix for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) System.out.print(m[i][j] + \" \"); System.out.println(); } return 0; } // driver code public static void main(String args[]) { int m[][] = { { 9, 8, 7, 1 }, { 7, 3, 0, 2 }, { 9, 5, 3, 2 }, { 6, 3, 1, 2 } }; sortRowWise(m); }}",
"e": 27251,
"s": 26067,
"text": null
},
{
"code": "# Python3 code to sort 2D matrix row-wisedef sortRowWise(m): # loop for rows of matrix for i in range(len(m)): # loop for column of matrix for j in range(len(m[i])): # loop for comparison and swapping for k in range(len(m[i]) - j - 1): if (m[i][k] > m[i][k + 1]): # swapping of elements t = m[i][k] m[i][k] = m[i][k + 1] m[i][k + 1] = t # printing the sorted matrix for i in range(len(m)): for j in range(len(m[i])): print(m[i][j], end=\" \") print() # Driver codem = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2],[ 6, 3, 1, 2 ]]sortRowWise(m) # This code is contributed by shubhamsingh10",
"e": 28083,
"s": 27251,
"text": null
},
{
"code": "// C# code to sort 2D matrix row-wiseusing System; class GFG{static int sortRowWise(int [,]m){ // loop for rows of matrix for (int i = 0; i < m.GetLength(0); i++) { // loop for column of matrix for (int j = 0; j < m.GetLength(1); j++) { // loop for comparison and swapping for (int k = 0; k < m.GetLength(1) - j - 1; k++) { if (m[i, k] > m[i, k + 1]) { // swapping of elements int t = m[i, k]; m[i, k] = m[i, k + 1]; m[i, k + 1] = t; } } } } // printing the sorted matrix for (int i = 0; i < m.GetLength(0); i++) { for (int j = 0; j < m.GetLength(1); j++) Console.Write(m[i, j] + \" \"); Console.WriteLine(); } return 0;} // Driver Codepublic static void Main(String []args){ int [,]m = {{ 9, 8, 7, 1 }, { 7, 3, 0, 2 }, { 9, 5, 3, 2 }, { 6, 3, 1, 2 }}; sortRowWise(m);}} // This code is contributed by 29AjayKumar",
"e": 29271,
"s": 28083,
"text": null
},
{
"code": "<script> // JavaScript Program to sort 2D matrix row-wise function sortRowWise(m) { // loop for rows of matrix for (let i = 0; i < m.length; i++) { // loop for column of matrix for (let j = 0; j < m[i].length; j++) { // loop for comparison and swapping for (let k = 0; k < m[i].length - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements let t = m[i][k]; m[i][k] = m[i][k + 1]; m[i][k + 1] = t; } } } } // printing the sorted matrix for (let i = 0; i < m.length; i++) { for (let j = 0; j < m[i].length; j++) document.write(m[i][j] + \" \"); document.write(\"<br/>\"); } return 0; } // Driver code let m = [[ 9, 8, 7, 1 ], [ 7, 3, 0, 2 ], [ 9, 5, 3, 2 ], [ 6, 3, 1, 2 ]]; sortRowWise(m); // This code is contributed by sanjoy_62.</script>",
"e": 30413,
"s": 29271,
"text": null
},
{
"code": null,
"e": 30449,
"s": 30413,
"text": "1 7 8 9 \n0 2 3 7 \n2 3 5 9 \n1 2 3 6 "
},
{
"code": null,
"e": 30546,
"s": 30449,
"text": "Method 2 (Using Library Function) The idea is to use Arrays.sort() for every row of the matrix. "
},
{
"code": null,
"e": 30550,
"s": 30546,
"text": "C++"
},
{
"code": null,
"e": 30555,
"s": 30550,
"text": "Java"
},
{
"code": null,
"e": 30563,
"s": 30555,
"text": "Python3"
},
{
"code": null,
"e": 30566,
"s": 30563,
"text": "C#"
},
{
"code": null,
"e": 30577,
"s": 30566,
"text": "Javascript"
},
{
"code": "// C++ code to sort 2D// matrix row-wise#include <bits/stdc++.h>using namespace std;#define M 4#define N 4 int sortRowWise(int m[M][N]){ // One by one sort // individual rows. for (int i = 0; i < M; i++) sort(m[i], m[i] + N); // Printing the sorted matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << (m[i][j]) << \" \"; cout << endl; }} // Driver codeint main(){ int m[M][N] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; sortRowWise(m);} // This code is contributed by gauravrajput1",
"e": 31166,
"s": 30577,
"text": null
},
{
"code": "// Java code to sort 2D matrix row-wiseimport java.io.*;import java.util.Arrays; public class Sort2DMatrix { static int sortRowWise(int m[][]) { // One by one sort individual rows. for (int i = 0; i < m.length; i++) Arrays.sort(m[i]); // printing the sorted matrix for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) System.out.print(m[i][j] + \" \"); System.out.println(); } return 0; } // driver code public static void main(String args[]) { int m[][] = { { 9, 8, 7, 1 }, { 7, 3, 0, 2 }, { 9, 5, 3, 2 }, { 6, 3, 1, 2 } }; sortRowWise(m); }}",
"e": 31923,
"s": 31166,
"text": null
},
{
"code": "# Python3 code to sort 2D matrix row-wisedef sortRowWise(m): # One by one sort individual rows. for i in range(len(m)): m[i].sort() # printing the sorted matrix for i in range(len(m)): for j in range(len(m[i])): print(m[i][j], end=\" \") print() return 0 # Driver codem = [[9, 8, 7, 1 ],[7, 3, 0, 2],[9, 5, 3, 2 ],[ 6, 3, 1, 2]] sortRowWise(m) # This code is contributed by shubhamsingh10",
"e": 32380,
"s": 31923,
"text": null
},
{
"code": "// C# code to sort 2D// matrix row-wise using System;using System.Collections.Generic;class Sort2DMatrix{ public static int[] GetRow(int[,] matrix, int row){ var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector;} static int sortRowWise(int [,]m){ // One by one sort individual // rows. for (int i = 0; i < m.GetLength(0); i++) { for (int k = 0; k < m.GetLength(1); k++) for (int j = 0; j < m.GetLength(1) - k - 1; j++) if (m[i, j] > m[i, j + 1]) { // swap temp and arr[i] int temp = m[i, j]; m[i, j] = m[i, j + 1]; m[i, j + 1] = temp; } } // Printing the sorted matrix for (int i = 0; i < m.GetLength(0); i++) { for (int j = 0; j < m.GetLength(1); j++) Console.Write(m[i, j] + \" \"); Console.WriteLine(); } return 0;} // Driver codepublic static void Main(String []args){ int [,]m = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; sortRowWise(m);}} // This code is contributed by gauravrajput1",
"e": 33612,
"s": 32380,
"text": null
},
{
"code": "<script> // JavaScript code to sort 2D// matrix row-wise function GetRow(matrix, row){ var rowLength = matrix[0].length; var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row][i]; return rowVector;} function sortRowWise(m){ // One by one sort individual // rows. for (var i = 0; i < m.length; i++) { for (var k = 0; k < m[0].length; k++) for (var j = 0; j < m[0].length - k - 1; j++) if (m[i][j] > m[i][j + 1]) { // swap temp and arr[i] var temp = m[i][j]; m[i][j] = m[i][j + 1]; m[i][j + 1] = temp; } } // Printing the sorted matrix for (var i = 0; i < m.length; i++) { for (var j = 0; j < m[0].length; j++) document.write(m[i][j] + \" \"); document.write(\"<br>\"); } return 0;} // Driver codevar m = [[9, 8, 7, 1], [7, 3, 0, 2], [9, 5, 3, 2], [6, 3, 1, 2]];sortRowWise(m); </script>",
"e": 34630,
"s": 33612,
"text": null
},
{
"code": null,
"e": 34666,
"s": 34630,
"text": "1 7 8 9 \n0 2 3 7 \n2 3 5 9 \n1 2 3 6 "
},
{
"code": null,
"e": 34675,
"s": 34666,
"text": "Kadhir M"
},
{
"code": null,
"e": 34687,
"s": 34675,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34702,
"s": 34687,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 34712,
"s": 34702,
"text": "rutvik_56"
},
{
"code": null,
"e": 34726,
"s": 34712,
"text": "GauravRajput1"
},
{
"code": null,
"e": 34736,
"s": 34726,
"text": "sanjoy_62"
},
{
"code": null,
"e": 34753,
"s": 34736,
"text": "pratyushsingh034"
},
{
"code": null,
"e": 34762,
"s": 34753,
"text": "noob2000"
},
{
"code": null,
"e": 34774,
"s": 34762,
"text": "Java-Arrays"
},
{
"code": null,
"e": 34781,
"s": 34774,
"text": "Matrix"
},
{
"code": null,
"e": 34789,
"s": 34781,
"text": "Sorting"
},
{
"code": null,
"e": 34797,
"s": 34789,
"text": "Sorting"
},
{
"code": null,
"e": 34804,
"s": 34797,
"text": "Matrix"
},
{
"code": null,
"e": 34902,
"s": 34804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34911,
"s": 34902,
"text": "Comments"
},
{
"code": null,
"e": 34924,
"s": 34911,
"text": "Old Comments"
},
{
"code": null,
"e": 34948,
"s": 34924,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 35010,
"s": 34948,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 35043,
"s": 35010,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 35094,
"s": 35043,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
}
]
|
Babylonian method for square root - GeeksforGeeks | 26 Oct, 2021
Algorithm: This method can be derived from (but predates) Newton–Raphson method.
1 Start with an arbitrary positive start value x (the closer to the
root, the better).
2 Initialize y = 1.
3. Do following until desired approximation is achieved.
a) Get the next approximation for root using average of x and y
b) Set y = n/x
Implementation:
C++
C
Java
Python 3
C#
PHP
Javascript
#include <iostream>using namespace std;class gfg { /*Returns the square root of n. Note that the function */public: float squareRoot(float n) { /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; float e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; }}; /* Driver program to test above function*/int main(){ gfg g; int n = 50; cout << "Square root of " << n << " is " << g.squareRoot(n); getchar();}
#include <stdio.h> /*Returns the square root of n. Note that the function */float squareRoot(float n){ /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; float e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n / x; } return x;} /* Driver program to test above function*/int main(){ int n = 50; printf("Square root of %d is %f", n, squareRoot(n)); getchar();}
class GFG { /*Returns the square root of n. Note that the function */ static float squareRoot(float n) { /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; // e decides the accuracy level double e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } /* Driver program to test above function*/ public static void main(String[] args) { int n = 50; System.out.printf("Square root of " + n + " is " + squareRoot(n)); }} // This code is contributed by// Smitha DInesh Semwal
# Returns the square root of n.# Note that the functiondef squareRoot(n): # We are using n itself as # initial approximation This # can definitely be improved x = n y = 1 # e decides the accuracy level e = 0.000001 while(x - y > e): x = (x + y)/2 y = n / x return x # Driver program to test# above functionn = 50 print("Square root of", n, "is", round(squareRoot(n), 6)) # This code is contributed by# Smitha Dinesh Semwal
// C# Program for Babylonian// method of square rootusing System; class GFG { // Returns the square root of n. // Note that the function static float squareRoot(float n) { // We are using n itself as // initial approximation This // can definitely be improved float x = n; float y = 1; // e decides the // accuracy level double e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } // Driver Code public static void Main() { int n = 50; Console.Write("Square root of " + n + " is " + squareRoot(n)); }} // This code is contributed by nitin mittal.
<?php // Returns the square root of n.// Note that the functionfunction squareRoot($n){ // We are using n itself // as initial approximation // This can definitely be // improved $x = $n; $y = 1; /* e decides the accuracy level */ $e = 0.000001; while($x - $y > $e) { $x = ($x + $y)/2; $y = $n / $x; } return $x;} // Driver Code{ $n = 50; echo "Square root of $n is ", squareRoot($n);} // This code is contributed by nitin mittal.?>
<script>// javascript Program to find the area// of triangle /*Returns the square root of n. Note that the function */function squareRoot( n){ /*We are using n itself as initial approximation This can definitely be improved */ let x = n; let y = 1; let e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n / x; } return x;} /* Driver program to test above function*/ let n = 50; document.write( "Square root of "+n+" is " + squareRoot(n).toFixed(6)); // This code is contributed by todaysgaurav </script>
Output :
Square root of 50 is 7.071068
Time Complexity: O(n1/2)
Auxiliary Space: O(1)Example:
n = 4 /*n itself is used for initial approximation*/
Initialize x = 4, y = 1
Next Approximation x = (x + y)/2 (= 2.500000),
y = n/x (=1.600000)
Next Approximation x = 2.050000,
y = 1.951220
Next Approximation x = 2.000610,
y = 1.999390
Next Approximation x = 2.000000,
y = 2.000000
Terminate as (x - y) > e now.
If we are sure that n is a perfect square, then we can use following method. The method can go in infinite loop for non-perfect-square numbers. For example, for 3 the below while loop will never terminate.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for Babylonian// method for square root#include <iostream>using namespace std; class gfg { /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/public: float squareRoot(float n) { /* We are using n itself as an initial approximation. This can definitely be improved */ float x = n; float y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return x; }}; /* Driver code*/int main(){ gfg g; int n = 49; cout << "Square root of " << n << " is " << g.squareRoot(n); getchar();} // This code is edited by Dark_Dante_
// C program for Babylonian// method for square root#include <stdio.h> /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/unsigned int squareRoot(int n){ int x = n; int y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return x;} // Driver Codeint main(){ int n = 49; printf("root of %d is %d", n, squareRoot(n)); getchar();}
// Java program for Babylonian// method for square rootimport java.io.*; public class GFG { /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/ static long squareRoot(int n) { int x = n; int y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return (long)x; } // Driver Code static public void main(String[] args) { int n = 49; System.out.println("root of " + n + " is " + squareRoot(n)); }} // This code is contributed by anuj_67.
# python3 program for Babylonian# method for square root # Returns the square root of n.# Note that the function# will not work for numbers# which are not perfect squares def squareRoot(n): x = n; y = 1; while(x > y): x = (x + y) / 2; y = n / x; return x; # Driver Coden = 49;print("root of", n, "is", squareRoot(n)); # This code is contributed by mits.
// C# program for Babylonian// method for square root using System; public class GFG { /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/ static uint squareRoot(int n) { int x = n; int y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return (uint)x; } // Driver Code static public void Main() { int n = 49; Console.WriteLine("root of " + n + " is " + squareRoot(n)); }} // This code is contributed by anuj_67.
<?php// PHP program for Babylonian// method for square root /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares */function squareRoot( $n){ $x = $n; $y = 1; while($x > $y) { $x = ($x + $y) / 2; $y =$n / $x; } return $x;} // Driver Code$n = 49;echo " root of ", $n, " is ", squareRoot($n); // This code is contributed by anuj_67.?>
<script>// javascript program for Babylonian// method for square root /* * Returns the square root of n. Note that the function will not work for * numbers which are not perfect squares */ function squareRoot(n) { var x = n; var y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return x; } // Driver Code var n = 49; document.write("root of " + n + " is " + squareRoot(n)); // This code contributed by shikhasingrajput</script>
Output :
root of 49 is 7
Time Complexity: O(n1/2)
Auxiliary Space: O(1)References; http://en.wikipedia.org/wiki/Square_root http://en.wikipedia.org/wiki/Babylonian_method#Babylonian_methodAsked by SnehalPlease write comments if you find any bug in the above program/algorithm, or if you want to share more information about Babylonian method.
Smitha Dinesh Semwal
nitin mittal
vt_m
Mithun Kumar
SoumikMondal
shadow_monarch
todaysgaurav
shikhasingrajput
bunnyram19
simmytarika5
subhammahato348
surindertarika1234
Amazon
Mathematical
Amazon
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Program for Decimal to Binary Conversion
Program to find sum of elements in a given array
Sieve of Eratosthenes
Program for factorial of a number | [
{
"code": null,
"e": 34205,
"s": 34177,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 34288,
"s": 34205,
"text": "Algorithm: This method can be derived from (but predates) Newton–Raphson method. "
},
{
"code": null,
"e": 34539,
"s": 34288,
"text": "1 Start with an arbitrary positive start value x (the closer to the \n root, the better).\n2 Initialize y = 1.\n3. Do following until desired approximation is achieved.\n a) Get the next approximation for root using average of x and y\n b) Set y = n/x"
},
{
"code": null,
"e": 34557,
"s": 34539,
"text": "Implementation: "
},
{
"code": null,
"e": 34561,
"s": 34557,
"text": "C++"
},
{
"code": null,
"e": 34563,
"s": 34561,
"text": "C"
},
{
"code": null,
"e": 34568,
"s": 34563,
"text": "Java"
},
{
"code": null,
"e": 34577,
"s": 34568,
"text": "Python 3"
},
{
"code": null,
"e": 34580,
"s": 34577,
"text": "C#"
},
{
"code": null,
"e": 34584,
"s": 34580,
"text": "PHP"
},
{
"code": null,
"e": 34595,
"s": 34584,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std;class gfg { /*Returns the square root of n. Note that the function */public: float squareRoot(float n) { /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; float e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; }}; /* Driver program to test above function*/int main(){ gfg g; int n = 50; cout << \"Square root of \" << n << \" is \" << g.squareRoot(n); getchar();}",
"e": 35217,
"s": 34595,
"text": null
},
{
"code": "#include <stdio.h> /*Returns the square root of n. Note that the function */float squareRoot(float n){ /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; float e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n / x; } return x;} /* Driver program to test above function*/int main(){ int n = 50; printf(\"Square root of %d is %f\", n, squareRoot(n)); getchar();}",
"e": 35722,
"s": 35217,
"text": null
},
{
"code": "class GFG { /*Returns the square root of n. Note that the function */ static float squareRoot(float n) { /*We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; // e decides the accuracy level double e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } /* Driver program to test above function*/ public static void main(String[] args) { int n = 50; System.out.printf(\"Square root of \" + n + \" is \" + squareRoot(n)); }} // This code is contributed by// Smitha DInesh Semwal",
"e": 36438,
"s": 35722,
"text": null
},
{
"code": "# Returns the square root of n.# Note that the functiondef squareRoot(n): # We are using n itself as # initial approximation This # can definitely be improved x = n y = 1 # e decides the accuracy level e = 0.000001 while(x - y > e): x = (x + y)/2 y = n / x return x # Driver program to test# above functionn = 50 print(\"Square root of\", n, \"is\", round(squareRoot(n), 6)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 36967,
"s": 36438,
"text": null
},
{
"code": "// C# Program for Babylonian// method of square rootusing System; class GFG { // Returns the square root of n. // Note that the function static float squareRoot(float n) { // We are using n itself as // initial approximation This // can definitely be improved float x = n; float y = 1; // e decides the // accuracy level double e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } // Driver Code public static void Main() { int n = 50; Console.Write(\"Square root of \" + n + \" is \" + squareRoot(n)); }} // This code is contributed by nitin mittal.",
"e": 37702,
"s": 36967,
"text": null
},
{
"code": "<?php // Returns the square root of n.// Note that the functionfunction squareRoot($n){ // We are using n itself // as initial approximation // This can definitely be // improved $x = $n; $y = 1; /* e decides the accuracy level */ $e = 0.000001; while($x - $y > $e) { $x = ($x + $y)/2; $y = $n / $x; } return $x;} // Driver Code{ $n = 50; echo \"Square root of $n is \", squareRoot($n);} // This code is contributed by nitin mittal.?>",
"e": 38207,
"s": 37702,
"text": null
},
{
"code": "<script>// javascript Program to find the area// of triangle /*Returns the square root of n. Note that the function */function squareRoot( n){ /*We are using n itself as initial approximation This can definitely be improved */ let x = n; let y = 1; let e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n / x; } return x;} /* Driver program to test above function*/ let n = 50; document.write( \"Square root of \"+n+\" is \" + squareRoot(n).toFixed(6)); // This code is contributed by todaysgaurav </script>",
"e": 38793,
"s": 38207,
"text": null
},
{
"code": null,
"e": 38803,
"s": 38793,
"text": "Output : "
},
{
"code": null,
"e": 38833,
"s": 38803,
"text": "Square root of 50 is 7.071068"
},
{
"code": null,
"e": 38858,
"s": 38833,
"text": "Time Complexity: O(n1/2)"
},
{
"code": null,
"e": 38888,
"s": 38858,
"text": "Auxiliary Space: O(1)Example:"
},
{
"code": null,
"e": 39203,
"s": 38888,
"text": "n = 4 /*n itself is used for initial approximation*/\nInitialize x = 4, y = 1\nNext Approximation x = (x + y)/2 (= 2.500000), \ny = n/x (=1.600000)\nNext Approximation x = 2.050000,\ny = 1.951220\nNext Approximation x = 2.000610,\ny = 1.999390\nNext Approximation x = 2.000000, \ny = 2.000000\nTerminate as (x - y) > e now."
},
{
"code": null,
"e": 39411,
"s": 39203,
"text": "If we are sure that n is a perfect square, then we can use following method. The method can go in infinite loop for non-perfect-square numbers. For example, for 3 the below while loop will never terminate. "
},
{
"code": null,
"e": 39415,
"s": 39411,
"text": "C++"
},
{
"code": null,
"e": 39417,
"s": 39415,
"text": "C"
},
{
"code": null,
"e": 39422,
"s": 39417,
"text": "Java"
},
{
"code": null,
"e": 39430,
"s": 39422,
"text": "Python3"
},
{
"code": null,
"e": 39433,
"s": 39430,
"text": "C#"
},
{
"code": null,
"e": 39437,
"s": 39433,
"text": "PHP"
},
{
"code": null,
"e": 39448,
"s": 39437,
"text": "Javascript"
},
{
"code": "// C++ program for Babylonian// method for square root#include <iostream>using namespace std; class gfg { /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/public: float squareRoot(float n) { /* We are using n itself as an initial approximation. This can definitely be improved */ float x = n; float y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return x; }}; /* Driver code*/int main(){ gfg g; int n = 49; cout << \"Square root of \" << n << \" is \" << g.squareRoot(n); getchar();} // This code is edited by Dark_Dante_",
"e": 40153,
"s": 39448,
"text": null
},
{
"code": "// C program for Babylonian// method for square root#include <stdio.h> /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/unsigned int squareRoot(int n){ int x = n; int y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return x;} // Driver Codeint main(){ int n = 49; printf(\"root of %d is %d\", n, squareRoot(n)); getchar();}",
"e": 40590,
"s": 40153,
"text": null
},
{
"code": "// Java program for Babylonian// method for square rootimport java.io.*; public class GFG { /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/ static long squareRoot(int n) { int x = n; int y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return (long)x; } // Driver Code static public void main(String[] args) { int n = 49; System.out.println(\"root of \" + n + \" is \" + squareRoot(n)); }} // This code is contributed by anuj_67.",
"e": 41221,
"s": 40590,
"text": null
},
{
"code": "# python3 program for Babylonian# method for square root # Returns the square root of n.# Note that the function# will not work for numbers# which are not perfect squares def squareRoot(n): x = n; y = 1; while(x > y): x = (x + y) / 2; y = n / x; return x; # Driver Coden = 49;print(\"root of\", n, \"is\", squareRoot(n)); # This code is contributed by mits.",
"e": 41601,
"s": 41221,
"text": null
},
{
"code": "// C# program for Babylonian// method for square root using System; public class GFG { /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares*/ static uint squareRoot(int n) { int x = n; int y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return (uint)x; } // Driver Code static public void Main() { int n = 49; Console.WriteLine(\"root of \" + n + \" is \" + squareRoot(n)); }} // This code is contributed by anuj_67.",
"e": 42212,
"s": 41601,
"text": null
},
{
"code": "<?php// PHP program for Babylonian// method for square root /* Returns the square root of n. Note that the function will not work for numbers which are not perfect squares */function squareRoot( $n){ $x = $n; $y = 1; while($x > $y) { $x = ($x + $y) / 2; $y =$n / $x; } return $x;} // Driver Code$n = 49;echo \" root of \", $n, \" is \", squareRoot($n); // This code is contributed by anuj_67.?>",
"e": 42653,
"s": 42212,
"text": null
},
{
"code": "<script>// javascript program for Babylonian// method for square root /* * Returns the square root of n. Note that the function will not work for * numbers which are not perfect squares */ function squareRoot(n) { var x = n; var y = 1; while (x > y) { x = (x + y) / 2; y = n / x; } return x; } // Driver Code var n = 49; document.write(\"root of \" + n + \" is \" + squareRoot(n)); // This code contributed by shikhasingrajput</script>",
"e": 43183,
"s": 42653,
"text": null
},
{
"code": null,
"e": 43194,
"s": 43183,
"text": "Output : "
},
{
"code": null,
"e": 43211,
"s": 43194,
"text": " root of 49 is 7"
},
{
"code": null,
"e": 43236,
"s": 43211,
"text": "Time Complexity: O(n1/2)"
},
{
"code": null,
"e": 43530,
"s": 43236,
"text": "Auxiliary Space: O(1)References; http://en.wikipedia.org/wiki/Square_root http://en.wikipedia.org/wiki/Babylonian_method#Babylonian_methodAsked by SnehalPlease write comments if you find any bug in the above program/algorithm, or if you want to share more information about Babylonian method. "
},
{
"code": null,
"e": 43551,
"s": 43530,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 43564,
"s": 43551,
"text": "nitin mittal"
},
{
"code": null,
"e": 43569,
"s": 43564,
"text": "vt_m"
},
{
"code": null,
"e": 43582,
"s": 43569,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 43595,
"s": 43582,
"text": "SoumikMondal"
},
{
"code": null,
"e": 43610,
"s": 43595,
"text": "shadow_monarch"
},
{
"code": null,
"e": 43623,
"s": 43610,
"text": "todaysgaurav"
},
{
"code": null,
"e": 43640,
"s": 43623,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 43651,
"s": 43640,
"text": "bunnyram19"
},
{
"code": null,
"e": 43664,
"s": 43651,
"text": "simmytarika5"
},
{
"code": null,
"e": 43680,
"s": 43664,
"text": "subhammahato348"
},
{
"code": null,
"e": 43699,
"s": 43680,
"text": "surindertarika1234"
},
{
"code": null,
"e": 43706,
"s": 43699,
"text": "Amazon"
},
{
"code": null,
"e": 43719,
"s": 43706,
"text": "Mathematical"
},
{
"code": null,
"e": 43726,
"s": 43719,
"text": "Amazon"
},
{
"code": null,
"e": 43739,
"s": 43726,
"text": "Mathematical"
},
{
"code": null,
"e": 43837,
"s": 43739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43846,
"s": 43837,
"text": "Comments"
},
{
"code": null,
"e": 43859,
"s": 43846,
"text": "Old Comments"
},
{
"code": null,
"e": 43874,
"s": 43859,
"text": "C++ Data Types"
},
{
"code": null,
"e": 43917,
"s": 43874,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 43941,
"s": 43917,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 43984,
"s": 43941,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 43998,
"s": 43984,
"text": "Prime Numbers"
},
{
"code": null,
"e": 44040,
"s": 43998,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 44081,
"s": 44040,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 44130,
"s": 44081,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 44152,
"s": 44130,
"text": "Sieve of Eratosthenes"
}
]
|
Kubernetes - Namespace | Namespace provides an additional qualification to a resource name. This is helpful when multiple teams are using the same cluster and there is a potential of name collision. It can be as a virtual wall between multiple clusters.
Following are some of the important functionalities of a Namespace in Kubernetes −
Namespaces help pod-to-pod communication using the same namespace.
Namespaces help pod-to-pod communication using the same namespace.
Namespaces are virtual clusters that can sit on top of the same physical cluster.
Namespaces are virtual clusters that can sit on top of the same physical cluster.
They provide logical separation between the teams and their environments.
They provide logical separation between the teams and their environments.
The following command is used to create a namespace.
apiVersion: v1
kind: Namespce
metadata
name: elk
The following command is used to control the namespace.
$ kubectl create –f namespace.yml ---------> 1
$ kubectl get namespace -----------------> 2
$ kubectl get namespace <Namespace name> ------->3
$ kubectl describe namespace <Namespace name> ---->4
$ kubectl delete namespace <Namespace name>
In the above code,
We are using the command to create a namespace.
This will list all the available namespace.
This will get a particular namespace whose name is specified in the command.
This will describe the complete details about the service.
This will delete a particular namespace present in the cluster.
Following is an example of a sample file for using namespace in service.
apiVersion: v1
kind: Service
metadata:
name: elasticsearch
namespace: elk
labels:
component: elasticsearch
spec:
type: LoadBalancer
selector:
component: elasticsearch
ports:
- name: http
port: 9200
protocol: TCP
- name: transport
port: 9300
protocol: TCP
In the above code, we are using the same namespace under service metadata with the name of elk.
41 Lectures
5 hours
AR Shankar
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Nigel Poulton
25 Lectures
1.5 hours
Pranjal Srivastava
18 Lectures
1 hours
Pranjal Srivastava
26 Lectures
1.5 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2424,
"s": 2195,
"text": "Namespace provides an additional qualification to a resource name. This is helpful when multiple teams are using the same cluster and there is a potential of name collision. It can be as a virtual wall between multiple clusters."
},
{
"code": null,
"e": 2507,
"s": 2424,
"text": "Following are some of the important functionalities of a Namespace in Kubernetes −"
},
{
"code": null,
"e": 2574,
"s": 2507,
"text": "Namespaces help pod-to-pod communication using the same namespace."
},
{
"code": null,
"e": 2641,
"s": 2574,
"text": "Namespaces help pod-to-pod communication using the same namespace."
},
{
"code": null,
"e": 2723,
"s": 2641,
"text": "Namespaces are virtual clusters that can sit on top of the same physical cluster."
},
{
"code": null,
"e": 2805,
"s": 2723,
"text": "Namespaces are virtual clusters that can sit on top of the same physical cluster."
},
{
"code": null,
"e": 2879,
"s": 2805,
"text": "They provide logical separation between the teams and their environments."
},
{
"code": null,
"e": 2953,
"s": 2879,
"text": "They provide logical separation between the teams and their environments."
},
{
"code": null,
"e": 3006,
"s": 2953,
"text": "The following command is used to create a namespace."
},
{
"code": null,
"e": 3059,
"s": 3006,
"text": "apiVersion: v1\nkind: Namespce\nmetadata\n name: elk\n"
},
{
"code": null,
"e": 3115,
"s": 3059,
"text": "The following command is used to control the namespace."
},
{
"code": null,
"e": 3356,
"s": 3115,
"text": "$ kubectl create –f namespace.yml ---------> 1\n$ kubectl get namespace -----------------> 2\n$ kubectl get namespace <Namespace name> ------->3\n$ kubectl describe namespace <Namespace name> ---->4\n$ kubectl delete namespace <Namespace name>\n"
},
{
"code": null,
"e": 3375,
"s": 3356,
"text": "In the above code,"
},
{
"code": null,
"e": 3423,
"s": 3375,
"text": "We are using the command to create a namespace."
},
{
"code": null,
"e": 3467,
"s": 3423,
"text": "This will list all the available namespace."
},
{
"code": null,
"e": 3544,
"s": 3467,
"text": "This will get a particular namespace whose name is specified in the command."
},
{
"code": null,
"e": 3603,
"s": 3544,
"text": "This will describe the complete details about the service."
},
{
"code": null,
"e": 3667,
"s": 3603,
"text": "This will delete a particular namespace present in the cluster."
},
{
"code": null,
"e": 3740,
"s": 3667,
"text": "Following is an example of a sample file for using namespace in service."
},
{
"code": null,
"e": 4056,
"s": 3740,
"text": "apiVersion: v1\nkind: Service\nmetadata:\n name: elasticsearch\n namespace: elk\n labels:\n component: elasticsearch\nspec:\n type: LoadBalancer\n selector:\n component: elasticsearch\n ports:\n - name: http\n port: 9200\n protocol: TCP\n - name: transport\n port: 9300\n protocol: TCP\n"
},
{
"code": null,
"e": 4152,
"s": 4056,
"text": "In the above code, we are using the same namespace under service metadata with the name of elk."
},
{
"code": null,
"e": 4185,
"s": 4152,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4197,
"s": 4185,
"text": " AR Shankar"
},
{
"code": null,
"e": 4230,
"s": 4197,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4270,
"s": 4230,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 4305,
"s": 4270,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4320,
"s": 4305,
"text": " Nigel Poulton"
},
{
"code": null,
"e": 4355,
"s": 4320,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4375,
"s": 4355,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4408,
"s": 4375,
"text": "\n 18 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4428,
"s": 4408,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4463,
"s": 4428,
"text": "\n 26 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4483,
"s": 4463,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4490,
"s": 4483,
"text": " Print"
},
{
"code": null,
"e": 4501,
"s": 4490,
"text": " Add Notes"
}
]
|
HTML5 - IndexedDB | The indexeddb is a new HTML5 concept to store the data inside user's browser. indexeddb is more power than local storage and useful for applications that requires to store large amount of the data. These applications can run more efficiency and load faster.
The W3C has announced that the Web SQL database is a deprecated local storage specification so web developer should not use this technology any more. indexeddb is an alternative for web SQL data base and more effective than older technologies.
it stores key-pair values
it is not a relational database
IndexedDB API is mostly asynchronous
it is not a structured query language
it has supported to access the data from same domain
Before enter into an indexeddb, we need to add some prefixes of implementation as shown below
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB ||
window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction ||
window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange ||
window.webkitIDBKeyRange || window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
Before creating a database, we have to prepare some data for the data base.let's start with company employee details.
const employeeData = [
{ id: "01", name: "Gopal K Varma", age: 35, email: "[email protected]" },
{ id: "02", name: "Prasad", age: 24, email: "[email protected]" }
];
Here adding some data manually into the data as shown below −
function add() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "01", name: "prasad", age: 24, email: "[email protected]" });
request.onsuccess = function(event) {
alert("Prasad has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nPrasad is already exist in your database! ");
}
}
We can retrieve the data from the data base using with get()
function read() {
var transaction = db.transaction(["employee"]);
var objectStore = transaction.objectStore("employee");
var request = objectStore.get("00-03");
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
if(request.result) {
alert("Name: " + request.result.name + ", Age:
" + request.result.age + ", Email: " + request.result.email);
} else {
alert("Kenny couldn't be found in your database!");
}
};
}
Using with get(), we can store the data in object instead of that we can store the data in cursor and we can retrieve the data from cursor.
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " + cursor.value.name + ",
Age: " + cursor.value.age + ", Email: " + cursor.value.email);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
We can remove the data from IndexedDB with remove().Here is how the code looks like
function remove() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.delete("02");
request.onsuccess = function(event) {
alert("prasad entry has been removed from your database.");
};
}
To show all the data we need to use onClick event as shown below code −
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<title>IndexedDb Demo | onlyWebPro.com</title>
</head>
<body>
<button onclick = "read()">Read </button>
<button onclick = "readAll()"></button>
<button onclick = "add()"></button>
<button onclick = "remove()">Delete </button>
</body>
</html>
The final code should be as −
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<script type = "text/javascript">
//prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||
window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
const employeeData = [
{ id: "00-01", name: "gopal", age: 35, email: "[email protected]" },
{ id: "00-02", name: "prasad", age: 32, email: "[email protected]" }
];
var db;
var request = window.indexedDB.open("newDatabase", 1);
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("employee", {keyPath: "id"});
for (var i in employeeData) {
objectStore.add(employeeData[i]);
}
}
function read() {
var transaction = db.transaction(["employee"]);
var objectStore = transaction.objectStore("employee");
var request = objectStore.get("00-03");
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
// Do something with the request.result!
if(request.result) {
alert("Name: " + request.result.name + ",
Age: " + request.result.age + ", Email: " + request.result.email);
} else {
alert("Kenny couldn't be found in your database!");
}
};
}
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " + cursor.value.name + ",
Age: " + cursor.value.age + ", Email: " + cursor.value.email);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
function add() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "00-03", name: "Kenny", age: 19, email: "[email protected]" });
request.onsuccess = function(event) {
alert("Kenny has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nKenny is aready exist in your database! ");
}
}
function remove() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.delete("00-03");
request.onsuccess = function(event) {
alert("Kenny's entry has been removed from your database.");
};
}
</script>
</head>
<body>
<button onclick = "read()">Read </button>
<button onclick = "readAll()">Read all </button>
<button onclick = "add()">Add data </button>
<button onclick = "remove()">Delete data </button>
</body>
</html>
It will produce the following output −
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2866,
"s": 2608,
"text": "The indexeddb is a new HTML5 concept to store the data inside user's browser. indexeddb is more power than local storage and useful for applications that requires to store large amount of the data. These applications can run more efficiency and load faster."
},
{
"code": null,
"e": 3111,
"s": 2866,
"text": "The W3C has announced that the Web SQL database is a deprecated local storage specification so web developer should not use this technology any more. indexeddb is an alternative for web SQL data base and more effective than older technologies. "
},
{
"code": null,
"e": 3137,
"s": 3111,
"text": "it stores key-pair values"
},
{
"code": null,
"e": 3169,
"s": 3137,
"text": "it is not a relational database"
},
{
"code": null,
"e": 3206,
"s": 3169,
"text": "IndexedDB API is mostly asynchronous"
},
{
"code": null,
"e": 3244,
"s": 3206,
"text": "it is not a structured query language"
},
{
"code": null,
"e": 3297,
"s": 3244,
"text": "it has supported to access the data from same domain"
},
{
"code": null,
"e": 3391,
"s": 3297,
"text": "Before enter into an indexeddb, we need to add some prefixes of implementation as shown below"
},
{
"code": null,
"e": 3809,
"s": 3391,
"text": "window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || \nwindow.msIndexedDB;\n \nwindow.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || \nwindow.msIDBTransaction;\nwindow.IDBKeyRange = window.IDBKeyRange || \nwindow.webkitIDBKeyRange || window.msIDBKeyRange\n \nif (!window.indexedDB) {\n window.alert(\"Your browser doesn't support a stable version of IndexedDB.\")\n}"
},
{
"code": null,
"e": 3927,
"s": 3809,
"text": "Before creating a database, we have to prepare some data for the data base.let's start with company employee details."
},
{
"code": null,
"e": 4116,
"s": 3927,
"text": "const employeeData = [\n { id: \"01\", name: \"Gopal K Varma\", age: 35, email: \"[email protected]\" },\n { id: \"02\", name: \"Prasad\", age: 24, email: \"[email protected]\" }\n];"
},
{
"code": null,
"e": 4178,
"s": 4116,
"text": "Here adding some data manually into the data as shown below −"
},
{
"code": null,
"e": 4604,
"s": 4178,
"text": "function add() {\n var request = db.transaction([\"employee\"], \"readwrite\")\n .objectStore(\"employee\")\n .add({ id: \"01\", name: \"prasad\", age: 24, email: \"[email protected]\" });\n \n request.onsuccess = function(event) {\n alert(\"Prasad has been added to your database.\");\n };\n \n request.onerror = function(event) {\n alert(\"Unable to add data\\r\\nPrasad is already exist in your database! \");\n }\n}"
},
{
"code": null,
"e": 4665,
"s": 4604,
"text": "We can retrieve the data from the data base using with get()"
},
{
"code": null,
"e": 5242,
"s": 4665,
"text": "function read() {\n var transaction = db.transaction([\"employee\"]);\n var objectStore = transaction.objectStore(\"employee\");\n var request = objectStore.get(\"00-03\");\n \n request.onerror = function(event) {\n alert(\"Unable to retrieve daa from database!\");\n };\n \n request.onsuccess = function(event) {\n \n if(request.result) {\n alert(\"Name: \" + request.result.name + \", Age: \n \" + request.result.age + \", Email: \" + request.result.email);\n } else {\n alert(\"Kenny couldn't be found in your database!\"); \n }\n };\n}"
},
{
"code": null,
"e": 5382,
"s": 5242,
"text": "Using with get(), we can store the data in object instead of that we can store the data in cursor and we can retrieve the data from cursor."
},
{
"code": null,
"e": 5853,
"s": 5382,
"text": "function readAll() {\n var objectStore = db.transaction(\"employee\").objectStore(\"employee\");\n \n objectStore.openCursor().onsuccess = function(event) {\n var cursor = event.target.result;\n \n if (cursor) {\n alert(\"Name for id \" + cursor.key + \" is \" + cursor.value.name + \", \n Age: \" + cursor.value.age + \", Email: \" + cursor.value.email);\n cursor.continue();\n } else {\n alert(\"No more entries!\");\n }\n };\n}"
},
{
"code": null,
"e": 5937,
"s": 5853,
"text": "We can remove the data from IndexedDB with remove().Here is how the code looks like"
},
{
"code": null,
"e": 6181,
"s": 5937,
"text": "function remove() {\n var request = db.transaction([\"employee\"], \"readwrite\")\n .objectStore(\"employee\")\n .delete(\"02\");\n \n request.onsuccess = function(event) {\n alert(\"prasad entry has been removed from your database.\");\n };\n}"
},
{
"code": null,
"e": 6253,
"s": 6181,
"text": "To show all the data we need to use onClick event as shown below code −"
},
{
"code": null,
"e": 6654,
"s": 6253,
"text": "<!DOCTYPE html>\n\n<html>\n <head>\n <meta http-equiv = \"Content-Type\" content = \"text/html; charset = utf-8\" />\n <title>IndexedDb Demo | onlyWebPro.com</title>\n </head>\n \n <body>\n <button onclick = \"read()\">Read </button>\n <button onclick = \"readAll()\"></button>\n <button onclick = \"add()\"></button>\n <button onclick = \"remove()\">Delete </button>\n </body>\n</html>"
},
{
"code": null,
"e": 6684,
"s": 6654,
"text": "The final code should be as −"
},
{
"code": null,
"e": 10908,
"s": 6684,
"text": "<!DOCTYPE html>\n\n<html>\n <head>\n <meta http-equiv = \"Content-Type\" content = \"text/html; charset = utf-8\" />\n <script type = \"text/javascript\">\n \n //prefixes of implementation that we want to test\n window.indexedDB = window.indexedDB || window.mozIndexedDB || \n window.webkitIndexedDB || window.msIndexedDB;\n \n //prefixes of window.IDB objects\n window.IDBTransaction = window.IDBTransaction || \n window.webkitIDBTransaction || window.msIDBTransaction;\n window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || \n window.msIDBKeyRange\n \n if (!window.indexedDB) {\n window.alert(\"Your browser doesn't support a stable version of IndexedDB.\")\n }\n \n const employeeData = [\n { id: \"00-01\", name: \"gopal\", age: 35, email: \"[email protected]\" },\n { id: \"00-02\", name: \"prasad\", age: 32, email: \"[email protected]\" }\n ];\n var db;\n var request = window.indexedDB.open(\"newDatabase\", 1);\n \n request.onerror = function(event) {\n console.log(\"error: \");\n };\n \n request.onsuccess = function(event) {\n db = request.result;\n console.log(\"success: \"+ db);\n };\n \n request.onupgradeneeded = function(event) {\n var db = event.target.result;\n var objectStore = db.createObjectStore(\"employee\", {keyPath: \"id\"});\n \n for (var i in employeeData) {\n objectStore.add(employeeData[i]);\n }\n }\n \n function read() {\n var transaction = db.transaction([\"employee\"]);\n var objectStore = transaction.objectStore(\"employee\");\n var request = objectStore.get(\"00-03\");\n \n request.onerror = function(event) {\n alert(\"Unable to retrieve daa from database!\");\n };\n \n request.onsuccess = function(event) {\n // Do something with the request.result!\n if(request.result) {\n alert(\"Name: \" + request.result.name + \", \n Age: \" + request.result.age + \", Email: \" + request.result.email);\n } else {\n alert(\"Kenny couldn't be found in your database!\");\n }\n };\n }\n \n function readAll() {\n var objectStore = db.transaction(\"employee\").objectStore(\"employee\");\n \n objectStore.openCursor().onsuccess = function(event) {\n var cursor = event.target.result;\n \n if (cursor) {\n alert(\"Name for id \" + cursor.key + \" is \" + cursor.value.name + \", \n Age: \" + cursor.value.age + \", Email: \" + cursor.value.email);\n cursor.continue();\n } else {\n alert(\"No more entries!\");\n }\n };\n }\n \n function add() {\n var request = db.transaction([\"employee\"], \"readwrite\")\n .objectStore(\"employee\")\n .add({ id: \"00-03\", name: \"Kenny\", age: 19, email: \"[email protected]\" });\n \n request.onsuccess = function(event) {\n alert(\"Kenny has been added to your database.\");\n };\n \n request.onerror = function(event) {\n alert(\"Unable to add data\\r\\nKenny is aready exist in your database! \");\n }\n }\n \n function remove() {\n var request = db.transaction([\"employee\"], \"readwrite\")\n .objectStore(\"employee\")\n .delete(\"00-03\");\n \n request.onsuccess = function(event) {\n alert(\"Kenny's entry has been removed from your database.\");\n };\n }\n </script>\n \n </head>\n <body>\n <button onclick = \"read()\">Read </button>\n <button onclick = \"readAll()\">Read all </button>\n <button onclick = \"add()\">Add data </button>\n <button onclick = \"remove()\">Delete data </button>\n </body>\n</html>"
},
{
"code": null,
"e": 10947,
"s": 10908,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 10980,
"s": 10947,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10994,
"s": 10980,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11029,
"s": 10994,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11043,
"s": 11029,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11078,
"s": 11043,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11095,
"s": 11078,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11130,
"s": 11095,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 11161,
"s": 11130,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11194,
"s": 11161,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11225,
"s": 11194,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11260,
"s": 11225,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 11291,
"s": 11260,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 11298,
"s": 11291,
"text": " Print"
},
{
"code": null,
"e": 11309,
"s": 11298,
"text": " Add Notes"
}
]
|
What is difference between a pointer and reference parameter in C++? | Pointer variables are used to store the address of variable.
Type *pointer;
Type *pointer;
Pointer=variable name;
When a parameter is declared as reference, it becomes an alternative name for an existing parameter.
Type &newname=existing name;
Type &pointer;
Pointer=variable name;
The main differences between pointers and reference parameters are −
References are used to refer an existing variable in another name whereas pointers are used to store address of variable.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable.
References cannot have a null value assigned but pointer can.
References cannot have a null value assigned but pointer can.
A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
A reference must be initialized on declaration while it is not necessary in case of pointer.
A reference must be initialized on declaration while it is not necessary in case of pointer.
A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack.
A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack. | [
{
"code": null,
"e": 1123,
"s": 1062,
"text": "Pointer variables are used to store the address of variable."
},
{
"code": null,
"e": 1138,
"s": 1123,
"text": "Type *pointer;"
},
{
"code": null,
"e": 1176,
"s": 1138,
"text": "Type *pointer;\nPointer=variable name;"
},
{
"code": null,
"e": 1277,
"s": 1176,
"text": "When a parameter is declared as reference, it becomes an alternative name for an existing parameter."
},
{
"code": null,
"e": 1306,
"s": 1277,
"text": "Type &newname=existing name;"
},
{
"code": null,
"e": 1344,
"s": 1306,
"text": "Type &pointer;\nPointer=variable name;"
},
{
"code": null,
"e": 1413,
"s": 1344,
"text": "The main differences between pointers and reference parameters are −"
},
{
"code": null,
"e": 1535,
"s": 1413,
"text": "References are used to refer an existing variable in another name whereas pointers are used to store address of variable."
},
{
"code": null,
"e": 1657,
"s": 1535,
"text": "References are used to refer an existing variable in another name whereas pointers are used to store address of variable."
},
{
"code": null,
"e": 1719,
"s": 1657,
"text": "References cannot have a null value assigned but pointer can."
},
{
"code": null,
"e": 1781,
"s": 1719,
"text": "References cannot have a null value assigned but pointer can."
},
{
"code": null,
"e": 1895,
"s": 1781,
"text": "A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference."
},
{
"code": null,
"e": 2009,
"s": 1895,
"text": "A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference."
},
{
"code": null,
"e": 2102,
"s": 2009,
"text": "A reference must be initialized on declaration while it is not necessary in case of pointer."
},
{
"code": null,
"e": 2195,
"s": 2102,
"text": "A reference must be initialized on declaration while it is not necessary in case of pointer."
},
{
"code": null,
"e": 2375,
"s": 2195,
"text": "A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack."
},
{
"code": null,
"e": 2555,
"s": 2375,
"text": "A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack."
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.