title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python | Sort all sublists in given list of strings | 28 Feb, 2019
Given a list of lists, the task is to sort each sublist in the given list of strings.
Example:
Input:
lst = [['Machine', 'London', 'Canada', 'France'],
['Spain', 'Munich'],
['Australia', 'Mandi']]
Output:
flist = [['Canada', 'France', 'London', 'Machine'],
['Munich', 'Spain'],
['Australia', 'Mandi']]
There are multiple ways to sort each list in alphabetical order.
Method #1 : Using map
# Python code to sort all sublists # in given list of strings # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'], ['Spain', 'Munich'], ['Australia', 'Mandi']] # Using map for sortingOutput = list(map(sorted, Input)) # Printing outputprint(Output)
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
Method #2 : Using lambda and sorted
# Python code to sort all sublists# in given list of strings # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'], ['Spain', 'Munich'], ['Australia', 'Mandi']] # using lambda and sortedOutput = [sorted(x, key = lambda x:x[0]) for x in Input] # Printing outputprint(Output)
[[‘Canada’, ‘France’, ‘London’, ‘Lanka’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
Method #3 : Using iteration and sort
# Python code to sort all sublists# in given list of strings # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'], ['Spain', 'Munich'], ['Australia', 'Mandi']] # sorting sublistfor sublist in Input: sublist.sort() # Printing outputprint(Input)
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
Python list-programs
python-list
Python
Python Programs
python-list
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2019"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "Given a list of lists, the task is to sort each sublist in the given list of strings."
},
{
"code": null,
"e": 123,
"s": 114,
"text": "Example:"
},
{
"code": null,
"e": 364,
"s": 123,
"text": "Input:\nlst = [['Machine', 'London', 'Canada', 'France'],\n ['Spain', 'Munich'],\n ['Australia', 'Mandi']]\n\nOutput:\nflist = [['Canada', 'France', 'London', 'Machine'],\n ['Munich', 'Spain'],\n ['Australia', 'Mandi']]\n"
},
{
"code": null,
"e": 429,
"s": 364,
"text": "There are multiple ways to sort each list in alphabetical order."
},
{
"code": null,
"e": 451,
"s": 429,
"text": "Method #1 : Using map"
},
{
"code": "# Python code to sort all sublists # in given list of strings # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'], ['Spain', 'Munich'], ['Australia', 'Mandi']] # Using map for sortingOutput = list(map(sorted, Input)) # Printing outputprint(Output)",
"e": 748,
"s": 451,
"text": null
},
{
"code": null,
"e": 846,
"s": 748,
"text": "[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]"
},
{
"code": null,
"e": 883,
"s": 846,
"text": " Method #2 : Using lambda and sorted"
},
{
"code": "# Python code to sort all sublists# in given list of strings # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'], ['Spain', 'Munich'], ['Australia', 'Mandi']] # using lambda and sortedOutput = [sorted(x, key = lambda x:x[0]) for x in Input] # Printing outputprint(Output)",
"e": 1204,
"s": 883,
"text": null
},
{
"code": null,
"e": 1302,
"s": 1204,
"text": "[[‘Canada’, ‘France’, ‘London’, ‘Lanka’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]"
},
{
"code": null,
"e": 1340,
"s": 1302,
"text": " Method #3 : Using iteration and sort"
},
{
"code": "# Python code to sort all sublists# in given list of strings # List initializationInput = [['Machine', 'London', 'Canada', 'France', 'Lanka'], ['Spain', 'Munich'], ['Australia', 'Mandi']] # sorting sublistfor sublist in Input: sublist.sort() # Printing outputprint(Input)",
"e": 1635,
"s": 1340,
"text": null
},
{
"code": null,
"e": 1733,
"s": 1635,
"text": "[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]"
},
{
"code": null,
"e": 1754,
"s": 1733,
"text": "Python list-programs"
},
{
"code": null,
"e": 1766,
"s": 1754,
"text": "python-list"
},
{
"code": null,
"e": 1773,
"s": 1766,
"text": "Python"
},
{
"code": null,
"e": 1789,
"s": 1773,
"text": "Python Programs"
},
{
"code": null,
"e": 1801,
"s": 1789,
"text": "python-list"
},
{
"code": null,
"e": 1899,
"s": 1801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1931,
"s": 1899,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1958,
"s": 1931,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1979,
"s": 1958,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2002,
"s": 1979,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2033,
"s": 2002,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2055,
"s": 2033,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2094,
"s": 2055,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2132,
"s": 2094,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2169,
"s": 2132,
"text": "Python Program for Fibonacci numbers"
}
] |
How to concatenate two strings in Python? | Concatenating two strings refers to the merging of both the strings together. Concatenation of “Tutorials” and “Point” will result in “TutorialsPoint”.
We will be discussing different methods of concatenating two strings in Python.
Two strings can be concatenated in Python by simply using the ‘+’ operator between them.
More than two strings can be concatenated using ‘+’ operator.
Live Demo
s1="Tutorials"
s2="Point"
s3=s1+s2
s4=s1+" "+s2
print(s3)
print(s4)
TutorialsPoint
Tutorials Point
We can use the % operator to combine two string in Python. Its implementation is shown in the below example.
Live Demo
s1="Tutorials"
s2="Point"
s3="%s %s"%(s1,s2)
s4="%s%s"%(s1,s2)
print(s3)
print(s4)
Tutorials Point
TutorialsPoint
The %s denotes string data type. The space between the two strings in the output depends on the space between “%s %s”, which is clear from the example above.
The join() is a string method that is used to join a sequence of elements. This method can be used to combine two strings.
Live Demo
s1="Tutorials"
s2="Point"
s3="".join([s1,s2])
s4=" ".join([s1,s2])
print(s3)
print(s4)
TutorialsPoint
Tutorials Point
The format() is a string formatting function. It can be used to concatenate two strings.
Live Demo
s1="Tutorials"
s2="Point"
s3="{}{}".format(s1,s2)
s4="{} {}".format(s1,s2)
print(s3)
print(s4)
TutorialsPoint
Tutorials Point
The {} set the position of the string variables. The space between the ‘{} {}’ is responsible for the space between the two concatenated strings in the output. | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "Concatenating two strings refers to the merging of both the strings together. Concatenation of “Tutorials” and “Point” will result in “TutorialsPoint”."
},
{
"code": null,
"e": 1294,
"s": 1214,
"text": "We will be discussing different methods of concatenating two strings in Python."
},
{
"code": null,
"e": 1383,
"s": 1294,
"text": "Two strings can be concatenated in Python by simply using the ‘+’ operator between them."
},
{
"code": null,
"e": 1445,
"s": 1383,
"text": "More than two strings can be concatenated using ‘+’ operator."
},
{
"code": null,
"e": 1456,
"s": 1445,
"text": " Live Demo"
},
{
"code": null,
"e": 1524,
"s": 1456,
"text": "s1=\"Tutorials\"\ns2=\"Point\"\ns3=s1+s2\ns4=s1+\" \"+s2\nprint(s3)\nprint(s4)"
},
{
"code": null,
"e": 1555,
"s": 1524,
"text": "TutorialsPoint\nTutorials Point"
},
{
"code": null,
"e": 1664,
"s": 1555,
"text": "We can use the % operator to combine two string in Python. Its implementation is shown in the below example."
},
{
"code": null,
"e": 1675,
"s": 1664,
"text": " Live Demo"
},
{
"code": null,
"e": 1758,
"s": 1675,
"text": "s1=\"Tutorials\"\ns2=\"Point\"\ns3=\"%s %s\"%(s1,s2)\ns4=\"%s%s\"%(s1,s2)\nprint(s3)\nprint(s4)"
},
{
"code": null,
"e": 1789,
"s": 1758,
"text": "Tutorials Point\nTutorialsPoint"
},
{
"code": null,
"e": 1947,
"s": 1789,
"text": "The %s denotes string data type. The space between the two strings in the output depends on the space between “%s %s”, which is clear from the example above."
},
{
"code": null,
"e": 2070,
"s": 1947,
"text": "The join() is a string method that is used to join a sequence of elements. This method can be used to combine two strings."
},
{
"code": null,
"e": 2081,
"s": 2070,
"text": " Live Demo"
},
{
"code": null,
"e": 2168,
"s": 2081,
"text": "s1=\"Tutorials\"\ns2=\"Point\"\ns3=\"\".join([s1,s2])\ns4=\" \".join([s1,s2])\nprint(s3)\nprint(s4)"
},
{
"code": null,
"e": 2199,
"s": 2168,
"text": "TutorialsPoint\nTutorials Point"
},
{
"code": null,
"e": 2288,
"s": 2199,
"text": "The format() is a string formatting function. It can be used to concatenate two strings."
},
{
"code": null,
"e": 2299,
"s": 2288,
"text": " Live Demo"
},
{
"code": null,
"e": 2394,
"s": 2299,
"text": "s1=\"Tutorials\"\ns2=\"Point\"\ns3=\"{}{}\".format(s1,s2)\ns4=\"{} {}\".format(s1,s2)\nprint(s3)\nprint(s4)"
},
{
"code": null,
"e": 2425,
"s": 2394,
"text": "TutorialsPoint\nTutorials Point"
},
{
"code": null,
"e": 2585,
"s": 2425,
"text": "The {} set the position of the string variables. The space between the ‘{} {}’ is responsible for the space between the two concatenated strings in the output."
}
] |
How to work with document.images in JavaScript? | Use the document.images property in JavaScript to get the number of <img> tags in a document.
You can try to run the following code to implement document.images property in JavaScript.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<h1>TutorialsPoint Tutorials</h1>
<img src="/javascript/images/javascript-mini-logo.jpg"/><br>
<img src="/html5/images/html5-mini-logo.jpg"/>
<script>
var num = document.images.length;
document.write("<br>How many images? "+num);
</script>
</body>
</html> | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "Use the document.images property in JavaScript to get the number of <img> tags in a document."
},
{
"code": null,
"e": 1247,
"s": 1156,
"text": "You can try to run the following code to implement document.images property in JavaScript."
},
{
"code": null,
"e": 1257,
"s": 1247,
"text": "Live Demo"
},
{
"code": null,
"e": 1658,
"s": 1257,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>JavaScript Example</title>\n </head>\n <body>\n <h1>TutorialsPoint Tutorials</h1>\n <img src=\"/javascript/images/javascript-mini-logo.jpg\"/><br>\n <img src=\"/html5/images/html5-mini-logo.jpg\"/>\n <script>\n var num = document.images.length;\n document.write(\"<br>How many images? \"+num);\n </script>\n </body>\n</html>"
}
] |
Collections unmodifiableList() method in Java with Examples - GeeksforGeeks | 08 Oct, 2018
The unmodifiableList() method of java.util.Collections class is used to return an unmodifiable view of the specified list. This method allows modules to provide users with “read-only” access to internal lists. Query operations on the returned list “read through” to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.
The returned list will be serializable if the specified list is serializable. Similarly, the returned list will implement RandomAccess if the specified list does.
Syntax:
public static <T> ListT>
unmodifiableList(List<? extends T> list)
Parameters: This method takes the list as a parameter for which an unmodifiable view is to be returned.
Return Value: This method returns an unmodifiable view of the specified list.
Below are the examples to illustrate the unmodifiableList() method
Example 1:
// Java program to demonstrate// unmodifiableList() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println("Initial list: " + list); // getting unmodifiable list // using unmodifiableList() method List<Character> immutablelist = Collections .unmodifiableList(list); // printing the list System.out.println("Unmodifiable list: " + immutablelist); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }}
Initial list: [X, Y]
Unmodifiable list: [X, Y]
Example 2: For UnsupportedOperationException
// Java program to demonstrate// unmodifiableList() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println("Initial list: " + list); // getting unmodifiable list // using unmodifiableList() method List<Character> immutablelist = Collections .unmodifiableList(list); // Adding element to new Collection System.out.println("\nTrying to modify" + " the unmodifiablelist"); immutablelist.add('Z'); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }}
Initial list: [X, Y]
Trying to modify the unmodifiablelist
Exception thrown : java.lang.UnsupportedOperationException
Java - util package
Java-Collections
Java-Functions
Java Programs
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Java Programming Examples
How to Iterate HashMap in Java?
Factory method design pattern in Java
Traverse Through a HashMap in Java
Iterate through List in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Iterate Over the Characters of a String in Java
Min Heap in Java
How to Get Elements By Index from HashSet in Java? | [
{
"code": null,
"e": 24235,
"s": 24207,
"text": "\n08 Oct, 2018"
},
{
"code": null,
"e": 24643,
"s": 24235,
"text": "The unmodifiableList() method of java.util.Collections class is used to return an unmodifiable view of the specified list. This method allows modules to provide users with “read-only” access to internal lists. Query operations on the returned list “read through” to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException."
},
{
"code": null,
"e": 24806,
"s": 24643,
"text": "The returned list will be serializable if the specified list is serializable. Similarly, the returned list will implement RandomAccess if the specified list does."
},
{
"code": null,
"e": 24814,
"s": 24806,
"text": "Syntax:"
},
{
"code": null,
"e": 24885,
"s": 24814,
"text": "public static <T> ListT> \n unmodifiableList(List<? extends T> list)"
},
{
"code": null,
"e": 24989,
"s": 24885,
"text": "Parameters: This method takes the list as a parameter for which an unmodifiable view is to be returned."
},
{
"code": null,
"e": 25067,
"s": 24989,
"text": "Return Value: This method returns an unmodifiable view of the specified list."
},
{
"code": null,
"e": 25134,
"s": 25067,
"text": "Below are the examples to illustrate the unmodifiableList() method"
},
{
"code": null,
"e": 25145,
"s": 25134,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// unmodifiableList() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println(\"Initial list: \" + list); // getting unmodifiable list // using unmodifiableList() method List<Character> immutablelist = Collections .unmodifiableList(list); // printing the list System.out.println(\"Unmodifiable list: \" + immutablelist); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 26106,
"s": 25145,
"text": null
},
{
"code": null,
"e": 26154,
"s": 26106,
"text": "Initial list: [X, Y]\nUnmodifiable list: [X, Y]\n"
},
{
"code": null,
"e": 26199,
"s": 26154,
"text": "Example 2: For UnsupportedOperationException"
},
{
"code": "// Java program to demonstrate// unmodifiableList() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of ArrayList<Character> List<Character> list = new ArrayList<Character>(); // populate the list list.add('X'); list.add('Y'); // printing the list System.out.println(\"Initial list: \" + list); // getting unmodifiable list // using unmodifiableList() method List<Character> immutablelist = Collections .unmodifiableList(list); // Adding element to new Collection System.out.println(\"\\nTrying to modify\" + \" the unmodifiablelist\"); immutablelist.add('Z'); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27219,
"s": 26199,
"text": null
},
{
"code": null,
"e": 27339,
"s": 27219,
"text": "Initial list: [X, Y]\n\nTrying to modify the unmodifiablelist\nException thrown : java.lang.UnsupportedOperationException\n"
},
{
"code": null,
"e": 27359,
"s": 27339,
"text": "Java - util package"
},
{
"code": null,
"e": 27376,
"s": 27359,
"text": "Java-Collections"
},
{
"code": null,
"e": 27391,
"s": 27376,
"text": "Java-Functions"
},
{
"code": null,
"e": 27405,
"s": 27391,
"text": "Java Programs"
},
{
"code": null,
"e": 27422,
"s": 27405,
"text": "Java-Collections"
},
{
"code": null,
"e": 27520,
"s": 27422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27529,
"s": 27520,
"text": "Comments"
},
{
"code": null,
"e": 27542,
"s": 27529,
"text": "Old Comments"
},
{
"code": null,
"e": 27568,
"s": 27542,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27600,
"s": 27568,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 27638,
"s": 27600,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 27673,
"s": 27638,
"text": "Traverse Through a HashMap in Java"
},
{
"code": null,
"e": 27702,
"s": 27673,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 27759,
"s": 27702,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 27840,
"s": 27759,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 27888,
"s": 27840,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 27905,
"s": 27888,
"text": "Min Heap in Java"
}
] |
Element left after performing alternate OR & XOR operation | Practice | GeeksforGeeks | Given an array A of N integers and a 2D matrix denoting q queries. Each query consists of two elements, index and value. Update value at index in A for each query and then perform the following operations to get the result for that query.
1. Perform bitwise OR on each pair
2. Perform bitwise XOR on each pair
Do this alternately till you are left with only a single element in A.
Example 1:
Input:
N = 4
A = {1, 4, 5, 6}
q = 2
query = {{0, 2}, {3, 5}}
Output: 1 3
Explaination:
1st query:
Update the value of A[0] to 2 as given in
the query pair.The array becomes {2, 4, 5, 6}.
1st iteration: Perform bitwise OR on pairs
{2,4} and {5,6}. The array becomes {6,7}.
2nd iteration: Perform bitwise XOR on pairs
{6,7}. The array becomes {1}.
2nd query:
Update the value of A[3] to 5 as given in
the query pair. The array becomes {2, 4, 5, 5}.
1st iteration: Perform bitwise OR on pairs
{2,4} and {5,5}. The array becomes {6,5}.
2nd iteration: 6^5=3. The array becomes {3}.
Your Task:
You do not need to read input or print anything. Your task is to complete the function left() which takes N, A[], q and query as input parameters and returns a list of integers denoting the result for each query.
Expected Time Complexity:O(q*logN)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ N ≤ 105
1 ≤ A[i] ≤ 105
1 ≤ q ≤ 104
0
vjvish982 months ago
//can anyone tell me what's wrong in this code.. plz
?????????????
vector<int> left(int N, int A[], int q, vector<pair<int, int>> query)
{
vector<int>v;
vector<int>b;
for(int i=0;i<N;i++)
{
b.push_back(A[i]);
}
for(int i=0;i<q;i++)
{
int x=0;
int ind=query[i].first;
int val=query[i].second;
b[ind]=val;
for(int j=1;j<b.size();)
{
x^=b[j]|b[j-1];
j++;j++;
}
v.push_back(x);
}
return v;
}
0
kaditya213 months ago
My answer is correct, there is issue in the driver code which is responsible for printing.
0
hemant3 years ago
hemant
Here is my Solution using Segment Tree:https://ide.geeksforgeeks.o...Time complexity: O(Q*log(n))Space complexity: O(n)
0
Rahul Tandekar3 years ago
Rahul Tandekar
please help me how can i apply bitwise | on first 2 elements in given arrayA[]={1,4,3,6}
0
manav 3 years ago
manav
https://ide.geeksforgeeks.o...
please tell me what is wrong with this code.
0
yogesh kothari4 years ago
yogesh kothari
Here is my solution of complexity O ( Q * log n)where q=no. of querieshttps://ide.geeksforgeeks.o...A simple array implementation of binary tree
0
Johan Reji4 years ago
Johan Reji
Your program took more time than expected.Time Limit ExceededExpected Time Limit < 1.32sec
Please help me optimize my code
https://ide.geeksforgeeks.o...
0
pagala_bhanra4 years ago
pagala_bhanra
import java.util.*;import java.lang.*;import java.io.*;
class segment_tree{ int []input; int []seg; int n; segment_tree(int []inp) { n = inp.length; input = new int[n]; int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int max_size = 2 * (int) Math.pow(2, x) - 1; seg = new int[max_size]; for(int i=0;i<n;i++) input[i]="inp[i];" int="" pow="(int)(Math.log(n)/Math.log(2));" if(pow%2="=" 0)="" construct_tree(0,n="" -="" 1,0,1);="" exor="" else="" construct_tree(0,n="" -="" 1,0,0);="" or="" }="" public="" void="" construct_tree(int="" l,int="" h,int="" pos,int="" op)="" {="" if(l="=h)" seg[pos]="input[l];" else="" {="" int="" mid="(l+h)/2;" construct_tree(l,mid,2*pos="" +="" 1,op^1);="" construct_tree(mid+1,h,2*pos="" +="" 2,op^1);="" if(op="=" 0)="" seg[pos]="seg[2*pos" +="" 1]="" |="" seg[2*pos="" +="" 2]="" ;="" else="" seg[pos]="seg[2*pos" +="" 1]="" ^="" seg[2*pos="" +="" 2]="" ;="" }="" }="" public="" void="" update(int="" index,int="" val,int="" node,int="" se,int="" ss,int="" op)="" {="" if(index="" <="" se="" ||="" index=""> ss) return; if(se == ss) { seg[node] = val; return; } int mid = (se + ss)/2; update(index,val,2*node + 1,se,mid,op^1); update(index,val,2*node + 2,mid + 1,ss,op^1); if(op == 0) seg[node] = seg[2*node + 1] | seg[2*node + 2] ; else seg[node] = seg[2*node + 1] ^ seg[2*node + 2] ; }public static void main (String[] args) {//codeScanner in = new Scanner(System.in);int t = in.nextInt();while(t-->0){ int n = in.nextInt(); int []ar = new int[n]; for(int i=0;i<n;i++) ar[i]="in.nextInt();" segment_tree="" st="new" segment_tree(ar);="" int="" temp="(int)(Math.log(n)/Math.log(2));" int="" base_op="0;" if(temp%2="=" 0)="" base_op="1;" else="" base_op="0;" int="" m="in.nextInt();" while(m--="">0) { int ind = in.nextInt(); int val = in.nextInt(); if(ind >= n || ind < 0) System.out.println("-1"); else { st.update(ind,val,0,0,n - 1,base_op); System.out.println(st.seg[0]); } }}}}
0
Vijil Vijay4 years ago
Vijil Vijay
https://ide.geeksforgeeks.o...
0
Anshul Sharma4 years ago
Anshul Sharma
https://ide.geeksforgeeks.o...
Please check it. Every input is giving correct output but when I submit it, it says ArrayIndexOutOfBoundsException 1, though it will not come.
Please check it.
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": 622,
"s": 238,
"text": "Given an array A of N integers and a 2D matrix denoting q queries. Each query consists of two elements, index and value. Update value at index in A for each query and then perform the following operations to get the result for that query.\n1. Perform bitwise OR on each pair \n2. Perform bitwise XOR on each pair \nDo this alternately till you are left with only a single element in A. "
},
{
"code": null,
"e": 634,
"s": 622,
"text": "\nExample 1:"
},
{
"code": null,
"e": 1226,
"s": 634,
"text": "Input: \nN = 4\nA = {1, 4, 5, 6}\nq = 2\nquery = {{0, 2}, {3, 5}}\n\nOutput: 1 3\n\nExplaination: \n1st query: \nUpdate the value of A[0] to 2 as given in \nthe query pair.The array becomes {2, 4, 5, 6}.\n1st iteration: Perform bitwise OR on pairs \n{2,4} and {5,6}. The array becomes {6,7}.\n2nd iteration: Perform bitwise XOR on pairs \n{6,7}. The array becomes {1}.\n\n\n2nd query: \nUpdate the value of A[3] to 5 as given in \nthe query pair. The array becomes {2, 4, 5, 5}.\n1st iteration: Perform bitwise OR on pairs \n{2,4} and {5,5}. The array becomes {6,5}.\n2nd iteration: 6^5=3. The array becomes {3}.\n\n"
},
{
"code": null,
"e": 1451,
"s": 1226,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function left() which takes N, A[], q and query as input parameters and returns a list of integers denoting the result for each query."
},
{
"code": null,
"e": 1518,
"s": 1451,
"text": "\nExpected Time Complexity:O(q*logN)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1571,
"s": 1518,
"text": "\nConstraints:\n1 ≤ N ≤ 105\n1 ≤ A[i] ≤ 105\n1 ≤ q ≤ 104"
},
{
"code": null,
"e": 1573,
"s": 1571,
"text": "0"
},
{
"code": null,
"e": 1594,
"s": 1573,
"text": "vjvish982 months ago"
},
{
"code": null,
"e": 2172,
"s": 1594,
"text": "//can anyone tell me what's wrong in this code.. plz\n?????????????\n vector<int> left(int N, int A[], int q, vector<pair<int, int>> query)\n {\n vector<int>v;\n vector<int>b;\n for(int i=0;i<N;i++)\n {\n b.push_back(A[i]);\n }\n for(int i=0;i<q;i++)\n { \n int x=0;\n int ind=query[i].first;\n int val=query[i].second;\n b[ind]=val;\n for(int j=1;j<b.size();)\n {\n x^=b[j]|b[j-1];\n j++;j++;\n }\n v.push_back(x);\n }\n return v;\n }"
},
{
"code": null,
"e": 2190,
"s": 2188,
"text": "0"
},
{
"code": null,
"e": 2212,
"s": 2190,
"text": "kaditya213 months ago"
},
{
"code": null,
"e": 2303,
"s": 2212,
"text": "My answer is correct, there is issue in the driver code which is responsible for printing."
},
{
"code": null,
"e": 2305,
"s": 2303,
"text": "0"
},
{
"code": null,
"e": 2323,
"s": 2305,
"text": "hemant3 years ago"
},
{
"code": null,
"e": 2330,
"s": 2323,
"text": "hemant"
},
{
"code": null,
"e": 2450,
"s": 2330,
"text": "Here is my Solution using Segment Tree:https://ide.geeksforgeeks.o...Time complexity: O(Q*log(n))Space complexity: O(n)"
},
{
"code": null,
"e": 2452,
"s": 2450,
"text": "0"
},
{
"code": null,
"e": 2478,
"s": 2452,
"text": "Rahul Tandekar3 years ago"
},
{
"code": null,
"e": 2493,
"s": 2478,
"text": "Rahul Tandekar"
},
{
"code": null,
"e": 2583,
"s": 2493,
"text": "please help me how can i apply bitwise | on first 2 elements in given arrayA[]={1,4,3,6}"
},
{
"code": null,
"e": 2585,
"s": 2583,
"text": "0"
},
{
"code": null,
"e": 2603,
"s": 2585,
"text": "manav 3 years ago"
},
{
"code": null,
"e": 2610,
"s": 2603,
"text": "manav "
},
{
"code": null,
"e": 2641,
"s": 2610,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 2686,
"s": 2641,
"text": "please tell me what is wrong with this code."
},
{
"code": null,
"e": 2688,
"s": 2686,
"text": "0"
},
{
"code": null,
"e": 2714,
"s": 2688,
"text": "yogesh kothari4 years ago"
},
{
"code": null,
"e": 2729,
"s": 2714,
"text": "yogesh kothari"
},
{
"code": null,
"e": 2874,
"s": 2729,
"text": "Here is my solution of complexity O ( Q * log n)where q=no. of querieshttps://ide.geeksforgeeks.o...A simple array implementation of binary tree"
},
{
"code": null,
"e": 2876,
"s": 2874,
"text": "0"
},
{
"code": null,
"e": 2898,
"s": 2876,
"text": "Johan Reji4 years ago"
},
{
"code": null,
"e": 2909,
"s": 2898,
"text": "Johan Reji"
},
{
"code": null,
"e": 3000,
"s": 2909,
"text": "Your program took more time than expected.Time Limit ExceededExpected Time Limit < 1.32sec"
},
{
"code": null,
"e": 3032,
"s": 3000,
"text": "Please help me optimize my code"
},
{
"code": null,
"e": 3063,
"s": 3032,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 3065,
"s": 3063,
"text": "0"
},
{
"code": null,
"e": 3090,
"s": 3065,
"text": "pagala_bhanra4 years ago"
},
{
"code": null,
"e": 3104,
"s": 3090,
"text": "pagala_bhanra"
},
{
"code": null,
"e": 3160,
"s": 3104,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 5273,
"s": 3160,
"text": "class segment_tree{ int []input; int []seg; int n; segment_tree(int []inp) { n = inp.length; input = new int[n]; int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int max_size = 2 * (int) Math.pow(2, x) - 1; seg = new int[max_size]; for(int i=0;i<n;i++) input[i]=\"inp[i];\" int=\"\" pow=\"(int)(Math.log(n)/Math.log(2));\" if(pow%2=\"=\" 0)=\"\" construct_tree(0,n=\"\" -=\"\" 1,0,1);=\"\" exor=\"\" else=\"\" construct_tree(0,n=\"\" -=\"\" 1,0,0);=\"\" or=\"\" }=\"\" public=\"\" void=\"\" construct_tree(int=\"\" l,int=\"\" h,int=\"\" pos,int=\"\" op)=\"\" {=\"\" if(l=\"=h)\" seg[pos]=\"input[l];\" else=\"\" {=\"\" int=\"\" mid=\"(l+h)/2;\" construct_tree(l,mid,2*pos=\"\" +=\"\" 1,op^1);=\"\" construct_tree(mid+1,h,2*pos=\"\" +=\"\" 2,op^1);=\"\" if(op=\"=\" 0)=\"\" seg[pos]=\"seg[2*pos\" +=\"\" 1]=\"\" |=\"\" seg[2*pos=\"\" +=\"\" 2]=\"\" ;=\"\" else=\"\" seg[pos]=\"seg[2*pos\" +=\"\" 1]=\"\" ^=\"\" seg[2*pos=\"\" +=\"\" 2]=\"\" ;=\"\" }=\"\" }=\"\" public=\"\" void=\"\" update(int=\"\" index,int=\"\" val,int=\"\" node,int=\"\" se,int=\"\" ss,int=\"\" op)=\"\" {=\"\" if(index=\"\" <=\"\" se=\"\" ||=\"\" index=\"\"> ss) return; if(se == ss) { seg[node] = val; return; } int mid = (se + ss)/2; update(index,val,2*node + 1,se,mid,op^1); update(index,val,2*node + 2,mid + 1,ss,op^1); if(op == 0) seg[node] = seg[2*node + 1] | seg[2*node + 2] ; else seg[node] = seg[2*node + 1] ^ seg[2*node + 2] ; }public static void main (String[] args) {//codeScanner in = new Scanner(System.in);int t = in.nextInt();while(t-->0){ int n = in.nextInt(); int []ar = new int[n]; for(int i=0;i<n;i++) ar[i]=\"in.nextInt();\" segment_tree=\"\" st=\"new\" segment_tree(ar);=\"\" int=\"\" temp=\"(int)(Math.log(n)/Math.log(2));\" int=\"\" base_op=\"0;\" if(temp%2=\"=\" 0)=\"\" base_op=\"1;\" else=\"\" base_op=\"0;\" int=\"\" m=\"in.nextInt();\" while(m--=\"\">0) { int ind = in.nextInt(); int val = in.nextInt(); if(ind >= n || ind < 0) System.out.println(\"-1\"); else { st.update(ind,val,0,0,n - 1,base_op); System.out.println(st.seg[0]); } }}}}"
},
{
"code": null,
"e": 5275,
"s": 5273,
"text": "0"
},
{
"code": null,
"e": 5298,
"s": 5275,
"text": "Vijil Vijay4 years ago"
},
{
"code": null,
"e": 5310,
"s": 5298,
"text": "Vijil Vijay"
},
{
"code": null,
"e": 5341,
"s": 5310,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5343,
"s": 5341,
"text": "0"
},
{
"code": null,
"e": 5368,
"s": 5343,
"text": "Anshul Sharma4 years ago"
},
{
"code": null,
"e": 5382,
"s": 5368,
"text": "Anshul Sharma"
},
{
"code": null,
"e": 5413,
"s": 5382,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5556,
"s": 5413,
"text": "Please check it. Every input is giving correct output but when I submit it, it says ArrayIndexOutOfBoundsException 1, though it will not come."
},
{
"code": null,
"e": 5573,
"s": 5556,
"text": "Please check it."
},
{
"code": null,
"e": 5719,
"s": 5573,
"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": 5755,
"s": 5719,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5765,
"s": 5755,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5775,
"s": 5765,
"text": "\nContest\n"
},
{
"code": null,
"e": 5838,
"s": 5775,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5986,
"s": 5838,
"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": 6194,
"s": 5986,
"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": 6300,
"s": 6194,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Scala - Strings | This chapter takes you through the Scala Strings. In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java.lang.String class.
The following code can be used to create a String −
var greeting = "Hello world!";
or
var greeting:String = "Hello world!";
Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”. String keyword can also be given in alternate declaration as shown above.
Try the following example program.
object Demo {
val greeting: String = "Hello, world!"
def main(args: Array[String]) {
println( greeting )
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Hello, world!
As mentioned earlier, String class is immutable. String object once created cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then use String Builder Class available in Scala!.
Methods used to obtain information about an object are known as accessor methods. One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object.
Use the following code segment to find the length of a string −
object Demo {
def main(args: Array[String]) {
var palindrome = "Dot saw I was Tod";
var len = palindrome.length();
println( "String Length is : " + len );
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
String Length is : 17
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
Which results in −
"Hello, world!"
The following lines of code to find string length.
object Demo {
def main(args: Array[String]) {
var str1 = "Dot saw I was ";
var str2 = "Tod";
println("Dot " + str1 + str2);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Dot Dot saw I was Tod
You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.
Try the following example program, which makes use of printf() method −
object Demo {
def main(args: Array[String]) {
var floatVar = 12.456
var intVar = 2000
var stringVar = "Hello, Scala!"
var fs = printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string" + "is %s", floatVar, intVar, stringVar);
println(fs)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
The value of the float variable is 12.456000,
while the value of the integer variable is 2000,
and the string is Hello, Scala!()
String Interpolation is the new way to create Strings in Scala programming language. This feature supports the versions of Scala-2.10 and later. String Interpolation: The mechanism to embed variable references directly in process string literal.
There are three types (interpolators) of implementations in String Interpolation.
The literal ‘s’ allows the usage of variable directly in processing a string, when you prepend ‘s’ to it. Any String variable with in a scope that can be used with in a String. The following are the different usages of ‘s’ String interpolator.
The following example code snippet for the implementation of ‘s’ interpolator in appending String variable ($name) to a normal String (Hello) in println statement.
val name = “James”
println(s “Hello, $name”) //output: Hello, James
String interpolater can also process arbitrary expressions. The following code snippet for Processing a String (1 + 1) with arbitrary expression (${1 + 1}) using ‘s’ String interpolator. Any arbitrary expression can be embedded in ‘${}’.
println(s “1 + 1 = ${1 + 1}”) //output: 1 + 1 = 2
Try the following example program of implementing ‘s’ interpolator.
object Demo {
def main(args: Array[String]) {
val name = "James"
println(s"Hello, $name")
println(s"1 + 1 = ${1 + 1}")
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
Hello, James
1 + 1 = 2
The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc.
Let us take an example of append floating point value (height = 1.9d) and String variable (name = “James”) with normal string. The following code snippet of implementing ‘f’ Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print (floating point value) 1.90.
val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") //James is 1.90 meters tall
It is type safe (i.e.) the variable reference and following format specifier should match otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities (format specifiers) available in Java. By default means, there is no % character after variable reference. It will assume as %s (String).
The ‘raw’ interpolator is similar to ‘s’ interpolator except that it performs no escaping of literals within a string. The following code snippets in a table will differ the usage of ‘s’ and ‘raw’ interpolators. In outputs of ‘s’ usage ‘\n’ effects as new line and in output of ‘raw’ usage the ‘\n’ will not effect. It will print the complete string with escape letters.
Program −
object Demo {
def main(args: Array[String]) {
println(s"Result = \n a \n b")
}
}
Program −
object Demo {
def main(args: Array[String]) {
println(raw"Result = \n a \n b")
}
}
Output −
Result =
a
b
Output −
Result = \n a \n b
Following is the list of methods defined by java.lang.String class and can be used directly in your Scala programs −
char charAt(int index)
Returns the character at the specified index.
int compareTo(Object o)
Compares this String to another Object.
int compareTo(String anotherString)
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
int hashCode()
Returns a hash code for this string.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
String intern()
Returns a canonical representation for the string object.
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
int length()
Returns the length of this string.
boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len)
Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int offset, int len)
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[] split(String regex)
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
char[] toCharArray()
Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
String toString()
This object (which is already a string!) is itself returned.
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(primitive data type x)
Returns the string representation of the passed data type argument.
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2355,
"s": 1998,
"text": "This chapter takes you through the Scala Strings. In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java.lang.String class."
},
{
"code": null,
"e": 2407,
"s": 2355,
"text": "The following code can be used to create a String −"
},
{
"code": null,
"e": 2482,
"s": 2407,
"text": "var greeting = \"Hello world!\";\n\nor\n\nvar greeting:String = \"Hello world!\";\n"
},
{
"code": null,
"e": 2688,
"s": 2482,
"text": "Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”. String keyword can also be given in alternate declaration as shown above."
},
{
"code": null,
"e": 2723,
"s": 2688,
"text": "Try the following example program."
},
{
"code": null,
"e": 2848,
"s": 2723,
"text": "object Demo {\n val greeting: String = \"Hello, world!\"\n\n def main(args: Array[String]) {\n println( greeting )\n }\n}"
},
{
"code": null,
"e": 2955,
"s": 2848,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 2989,
"s": 2955,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 3004,
"s": 2989,
"text": "Hello, world!\n"
},
{
"code": null,
"e": 3230,
"s": 3004,
"text": "As mentioned earlier, String class is immutable. String object once created cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then use String Builder Class available in Scala!."
},
{
"code": null,
"e": 3457,
"s": 3230,
"text": "Methods used to obtain information about an object are known as accessor methods. One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object."
},
{
"code": null,
"e": 3521,
"s": 3457,
"text": "Use the following code segment to find the length of a string −"
},
{
"code": null,
"e": 3711,
"s": 3521,
"text": "object Demo {\n def main(args: Array[String]) {\n var palindrome = \"Dot saw I was Tod\";\n var len = palindrome.length();\n \n println( \"String Length is : \" + len );\n }\n}"
},
{
"code": null,
"e": 3818,
"s": 3711,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 3852,
"s": 3818,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 3875,
"s": 3852,
"text": "String Length is : 17\n"
},
{
"code": null,
"e": 3942,
"s": 3875,
"text": "The String class includes a method for concatenating two strings −"
},
{
"code": null,
"e": 3968,
"s": 3942,
"text": "string1.concat(string2);\n"
},
{
"code": null,
"e": 4114,
"s": 3968,
"text": "This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in −"
},
{
"code": null,
"e": 4145,
"s": 4114,
"text": "\"My name is \".concat(\"Zara\");\n"
},
{
"code": null,
"e": 4213,
"s": 4145,
"text": "Strings are more commonly concatenated with the + operator, as in −"
},
{
"code": null,
"e": 4240,
"s": 4213,
"text": "\"Hello,\" + \" world\" + \"!\"\n"
},
{
"code": null,
"e": 4259,
"s": 4240,
"text": "Which results in −"
},
{
"code": null,
"e": 4276,
"s": 4259,
"text": "\"Hello, world!\"\n"
},
{
"code": null,
"e": 4327,
"s": 4276,
"text": "The following lines of code to find string length."
},
{
"code": null,
"e": 4487,
"s": 4327,
"text": "object Demo {\n def main(args: Array[String]) {\n var str1 = \"Dot saw I was \";\n var str2 = \"Tod\";\n \n println(\"Dot \" + str1 + str2);\n }\n}"
},
{
"code": null,
"e": 4594,
"s": 4487,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 4628,
"s": 4594,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 4651,
"s": 4628,
"text": "Dot Dot saw I was Tod\n"
},
{
"code": null,
"e": 4852,
"s": 4651,
"text": "You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object."
},
{
"code": null,
"e": 4924,
"s": 4852,
"text": "Try the following example program, which makes use of printf() method −"
},
{
"code": null,
"e": 5278,
"s": 4924,
"text": "object Demo {\n def main(args: Array[String]) {\n var floatVar = 12.456\n var intVar = 2000\n var stringVar = \"Hello, Scala!\"\n \n var fs = printf(\"The value of the float variable is \" + \"%f, while the value of the integer \" + \"variable is %d, and the string\" + \"is %s\", floatVar, intVar, stringVar);\n \n println(fs)\n }\n}"
},
{
"code": null,
"e": 5385,
"s": 5278,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 5419,
"s": 5385,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 5551,
"s": 5419,
"text": "The value of the float variable is 12.456000, \nwhile the value of the integer variable is 2000, \nand the string is Hello, Scala!()\n"
},
{
"code": null,
"e": 5797,
"s": 5551,
"text": "String Interpolation is the new way to create Strings in Scala programming language. This feature supports the versions of Scala-2.10 and later. String Interpolation: The mechanism to embed variable references directly in process string literal."
},
{
"code": null,
"e": 5879,
"s": 5797,
"text": "There are three types (interpolators) of implementations in String Interpolation."
},
{
"code": null,
"e": 6123,
"s": 5879,
"text": "The literal ‘s’ allows the usage of variable directly in processing a string, when you prepend ‘s’ to it. Any String variable with in a scope that can be used with in a String. The following are the different usages of ‘s’ String interpolator."
},
{
"code": null,
"e": 6287,
"s": 6123,
"text": "The following example code snippet for the implementation of ‘s’ interpolator in appending String variable ($name) to a normal String (Hello) in println statement."
},
{
"code": null,
"e": 6356,
"s": 6287,
"text": "val name = “James”\nprintln(s “Hello, $name”) //output: Hello, James\n"
},
{
"code": null,
"e": 6594,
"s": 6356,
"text": "String interpolater can also process arbitrary expressions. The following code snippet for Processing a String (1 + 1) with arbitrary expression (${1 + 1}) using ‘s’ String interpolator. Any arbitrary expression can be embedded in ‘${}’."
},
{
"code": null,
"e": 6645,
"s": 6594,
"text": "println(s “1 + 1 = ${1 + 1}”) //output: 1 + 1 = 2\n"
},
{
"code": null,
"e": 6713,
"s": 6645,
"text": "Try the following example program of implementing ‘s’ interpolator."
},
{
"code": null,
"e": 6867,
"s": 6713,
"text": "object Demo {\n def main(args: Array[String]) {\n val name = \"James\"\n \n println(s\"Hello, $name\")\n println(s\"1 + 1 = ${1 + 1}\")\n }\n}"
},
{
"code": null,
"e": 6974,
"s": 6867,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 7008,
"s": 6974,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 7032,
"s": 7008,
"text": "Hello, James\n1 + 1 = 2\n"
},
{
"code": null,
"e": 7267,
"s": 7032,
"text": "The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc."
},
{
"code": null,
"e": 7556,
"s": 7267,
"text": "Let us take an example of append floating point value (height = 1.9d) and String variable (name = “James”) with normal string. The following code snippet of implementing ‘f’ Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print (floating point value) 1.90."
},
{
"code": null,
"e": 7670,
"s": 7556,
"text": "val height = 1.9d\nval name = \"James\"\nprintln(f\"$name%s is $height%2.2f meters tall\") //James is 1.90 meters tall\n"
},
{
"code": null,
"e": 7993,
"s": 7670,
"text": "It is type safe (i.e.) the variable reference and following format specifier should match otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities (format specifiers) available in Java. By default means, there is no % character after variable reference. It will assume as %s (String)."
},
{
"code": null,
"e": 8364,
"s": 7993,
"text": "The ‘raw’ interpolator is similar to ‘s’ interpolator except that it performs no escaping of literals within a string. The following code snippets in a table will differ the usage of ‘s’ and ‘raw’ interpolators. In outputs of ‘s’ usage ‘\\n’ effects as new line and in output of ‘raw’ usage the ‘\\n’ will not effect. It will print the complete string with escape letters."
},
{
"code": null,
"e": 8374,
"s": 8364,
"text": "Program −"
},
{
"code": null,
"e": 8467,
"s": 8374,
"text": "object Demo {\n def main(args: Array[String]) {\n println(s\"Result = \\n a \\n b\")\n }\n}"
},
{
"code": null,
"e": 8477,
"s": 8467,
"text": "Program −"
},
{
"code": null,
"e": 8572,
"s": 8477,
"text": "object Demo {\n def main(args: Array[String]) {\n println(raw\"Result = \\n a \\n b\")\n }\n}"
},
{
"code": null,
"e": 8581,
"s": 8572,
"text": "Output −"
},
{
"code": null,
"e": 8595,
"s": 8581,
"text": "Result =\na\nb\n"
},
{
"code": null,
"e": 8604,
"s": 8595,
"text": "Output −"
},
{
"code": null,
"e": 8624,
"s": 8604,
"text": "Result = \\n a \\n b\n"
},
{
"code": null,
"e": 8741,
"s": 8624,
"text": "Following is the list of methods defined by java.lang.String class and can be used directly in your Scala programs −"
},
{
"code": null,
"e": 8764,
"s": 8741,
"text": "char charAt(int index)"
},
{
"code": null,
"e": 8810,
"s": 8764,
"text": "Returns the character at the specified index."
},
{
"code": null,
"e": 8834,
"s": 8810,
"text": "int compareTo(Object o)"
},
{
"code": null,
"e": 8874,
"s": 8834,
"text": "Compares this String to another Object."
},
{
"code": null,
"e": 8910,
"s": 8874,
"text": "int compareTo(String anotherString)"
},
{
"code": null,
"e": 8950,
"s": 8910,
"text": "Compares two strings lexicographically."
},
{
"code": null,
"e": 8986,
"s": 8950,
"text": "int compareToIgnoreCase(String str)"
},
{
"code": null,
"e": 9053,
"s": 8986,
"text": "Compares two strings lexicographically, ignoring case differences."
},
{
"code": null,
"e": 9079,
"s": 9053,
"text": "String concat(String str)"
},
{
"code": null,
"e": 9140,
"s": 9079,
"text": "Concatenates the specified string to the end of this string."
},
{
"code": null,
"e": 9179,
"s": 9140,
"text": "boolean contentEquals(StringBuffer sb)"
},
{
"code": null,
"e": 9293,
"s": 9179,
"text": "Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer."
},
{
"code": null,
"e": 9332,
"s": 9293,
"text": "static String copyValueOf(char[] data)"
},
{
"code": null,
"e": 9412,
"s": 9332,
"text": "Returns a String that represents the character sequence in the array specified."
},
{
"code": null,
"e": 9474,
"s": 9412,
"text": "static String copyValueOf(char[] data, int offset, int count)"
},
{
"code": null,
"e": 9554,
"s": 9474,
"text": "Returns a String that represents the character sequence in the array specified."
},
{
"code": null,
"e": 9586,
"s": 9554,
"text": "boolean endsWith(String suffix)"
},
{
"code": null,
"e": 9639,
"s": 9586,
"text": "Tests if this string ends with the specified suffix."
},
{
"code": null,
"e": 9671,
"s": 9639,
"text": "boolean equals(Object anObject)"
},
{
"code": null,
"e": 9717,
"s": 9671,
"text": "Compares this string to the specified object."
},
{
"code": null,
"e": 9764,
"s": 9717,
"text": "boolean equalsIgnoreCase(String anotherString)"
},
{
"code": null,
"e": 9834,
"s": 9764,
"text": "Compares this String to another String, ignoring case considerations."
},
{
"code": null,
"e": 9850,
"s": 9834,
"text": "byte getBytes()"
},
{
"code": null,
"e": 9975,
"s": 9850,
"text": "Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array."
},
{
"code": null,
"e": 10011,
"s": 9975,
"text": "byte[] getBytes(String charsetName)"
},
{
"code": null,
"e": 10123,
"s": 10011,
"text": "Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array."
},
{
"code": null,
"e": 10189,
"s": 10123,
"text": "void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)"
},
{
"code": null,
"e": 10262,
"s": 10189,
"text": "Copies characters from this string into the destination character array."
},
{
"code": null,
"e": 10277,
"s": 10262,
"text": "int hashCode()"
},
{
"code": null,
"e": 10314,
"s": 10277,
"text": "Returns a hash code for this string."
},
{
"code": null,
"e": 10334,
"s": 10314,
"text": "int indexOf(int ch)"
},
{
"code": null,
"e": 10423,
"s": 10334,
"text": "Returns the index within this string of the first occurrence of the specified character."
},
{
"code": null,
"e": 10458,
"s": 10423,
"text": "int indexOf(int ch, int fromIndex)"
},
{
"code": null,
"e": 10591,
"s": 10458,
"text": "Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index."
},
{
"code": null,
"e": 10615,
"s": 10591,
"text": "int indexOf(String str)"
},
{
"code": null,
"e": 10704,
"s": 10615,
"text": "Returns the index within this string of the first occurrence of the specified substring."
},
{
"code": null,
"e": 10743,
"s": 10704,
"text": "int indexOf(String str, int fromIndex)"
},
{
"code": null,
"e": 10865,
"s": 10743,
"text": "Returns the index within this string of the first occurrence of the specified substring, starting at the specified index."
},
{
"code": null,
"e": 10881,
"s": 10865,
"text": "String intern()"
},
{
"code": null,
"e": 10939,
"s": 10881,
"text": "Returns a canonical representation for the string object."
},
{
"code": null,
"e": 10963,
"s": 10939,
"text": "int lastIndexOf(int ch)"
},
{
"code": null,
"e": 11051,
"s": 10963,
"text": "Returns the index within this string of the last occurrence of the specified character."
},
{
"code": null,
"e": 11090,
"s": 11051,
"text": "int lastIndexOf(int ch, int fromIndex)"
},
{
"code": null,
"e": 11230,
"s": 11090,
"text": "Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index."
},
{
"code": null,
"e": 11258,
"s": 11230,
"text": "int lastIndexOf(String str)"
},
{
"code": null,
"e": 11351,
"s": 11258,
"text": "Returns the index within this string of the rightmost occurrence of the specified substring."
},
{
"code": null,
"e": 11394,
"s": 11351,
"text": "int lastIndexOf(String str, int fromIndex)"
},
{
"code": null,
"e": 11534,
"s": 11394,
"text": "Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index."
},
{
"code": null,
"e": 11547,
"s": 11534,
"text": "int length()"
},
{
"code": null,
"e": 11582,
"s": 11547,
"text": "Returns the length of this string."
},
{
"code": null,
"e": 11612,
"s": 11582,
"text": "boolean matches(String regex)"
},
{
"code": null,
"e": 11683,
"s": 11612,
"text": "Tells whether or not this string matches the given regular expression."
},
{
"code": null,
"e": 11773,
"s": 11683,
"text": "boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len)"
},
{
"code": null,
"e": 11812,
"s": 11773,
"text": "Tests if two string regions are equal."
},
{
"code": null,
"e": 11882,
"s": 11812,
"text": "boolean regionMatches(int toffset, String other, int offset, int len)"
},
{
"code": null,
"e": 11921,
"s": 11882,
"text": "Tests if two string regions are equal."
},
{
"code": null,
"e": 11964,
"s": 11921,
"text": "String replace(char oldChar, char newChar)"
},
{
"code": null,
"e": 12066,
"s": 11964,
"text": "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar."
},
{
"code": null,
"e": 12117,
"s": 12066,
"text": "String replaceAll(String regex, String replacement"
},
{
"code": null,
"e": 12226,
"s": 12117,
"text": "Replaces each substring of this string that matches the given regular expression with the given replacement."
},
{
"code": null,
"e": 12280,
"s": 12226,
"text": "String replaceFirst(String regex, String replacement)"
},
{
"code": null,
"e": 12394,
"s": 12280,
"text": "Replaces the first substring of this string that matches the given regular expression with the given replacement."
},
{
"code": null,
"e": 12423,
"s": 12394,
"text": "String[] split(String regex)"
},
{
"code": null,
"e": 12490,
"s": 12423,
"text": "Splits this string around matches of the given regular expression."
},
{
"code": null,
"e": 12530,
"s": 12490,
"text": "String[] split(String regex, int limit)"
},
{
"code": null,
"e": 12597,
"s": 12530,
"text": "Splits this string around matches of the given regular expression."
},
{
"code": null,
"e": 12631,
"s": 12597,
"text": "boolean startsWith(String prefix)"
},
{
"code": null,
"e": 12686,
"s": 12631,
"text": "Tests if this string starts with the specified prefix."
},
{
"code": null,
"e": 12733,
"s": 12686,
"text": "boolean startsWith(String prefix, int toffset)"
},
{
"code": null,
"e": 12816,
"s": 12733,
"text": "Tests if this string starts with the specified prefix beginning a specified index."
},
{
"code": null,
"e": 12871,
"s": 12816,
"text": "CharSequence subSequence(int beginIndex, int endIndex)"
},
{
"code": null,
"e": 12944,
"s": 12871,
"text": "Returns a new character sequence that is a subsequence of this sequence."
},
{
"code": null,
"e": 12977,
"s": 12944,
"text": "String substring(int beginIndex)"
},
{
"code": null,
"e": 13034,
"s": 12977,
"text": "Returns a new string that is a substring of this string."
},
{
"code": null,
"e": 13081,
"s": 13034,
"text": "String substring(int beginIndex, int endIndex)"
},
{
"code": null,
"e": 13138,
"s": 13081,
"text": "Returns a new string that is a substring of this string."
},
{
"code": null,
"e": 13159,
"s": 13138,
"text": "char[] toCharArray()"
},
{
"code": null,
"e": 13206,
"s": 13159,
"text": "Converts this string to a new character array."
},
{
"code": null,
"e": 13227,
"s": 13206,
"text": "String toLowerCase()"
},
{
"code": null,
"e": 13326,
"s": 13227,
"text": "Converts all of the characters in this String to lower case using the rules of the default locale."
},
{
"code": null,
"e": 13360,
"s": 13326,
"text": "String toLowerCase(Locale locale)"
},
{
"code": null,
"e": 13457,
"s": 13360,
"text": "Converts all of the characters in this String to lower case using the rules of the given Locale."
},
{
"code": null,
"e": 13475,
"s": 13457,
"text": "String toString()"
},
{
"code": null,
"e": 13536,
"s": 13475,
"text": "This object (which is already a string!) is itself returned."
},
{
"code": null,
"e": 13557,
"s": 13536,
"text": "String toUpperCase()"
},
{
"code": null,
"e": 13656,
"s": 13557,
"text": "Converts all of the characters in this String to upper case using the rules of the default locale."
},
{
"code": null,
"e": 13690,
"s": 13656,
"text": "String toUpperCase(Locale locale)"
},
{
"code": null,
"e": 13787,
"s": 13690,
"text": "Converts all of the characters in this String to upper case using the rules of the given Locale."
},
{
"code": null,
"e": 13801,
"s": 13787,
"text": "String trim()"
},
{
"code": null,
"e": 13877,
"s": 13801,
"text": "Returns a copy of the string, with leading and trailing whitespace omitted."
},
{
"code": null,
"e": 13922,
"s": 13877,
"text": "static String valueOf(primitive data type x)"
},
{
"code": null,
"e": 13990,
"s": 13922,
"text": "Returns the string representation of the passed data type argument."
},
{
"code": null,
"e": 14023,
"s": 13990,
"text": "\n 82 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 14042,
"s": 14023,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 14077,
"s": 14042,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14098,
"s": 14077,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 14133,
"s": 14098,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 14151,
"s": 14133,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 14186,
"s": 14151,
"text": "\n 76 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 14204,
"s": 14186,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 14239,
"s": 14204,
"text": "\n 69 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 14257,
"s": 14239,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 14292,
"s": 14257,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 14315,
"s": 14292,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 14322,
"s": 14315,
"text": " Print"
},
{
"code": null,
"e": 14333,
"s": 14322,
"text": " Add Notes"
}
] |
C# Program to Convert Character case | Let’s say your string is −
str = "AMIT";
To convert the above uppercase string in lowercase, use the ToLower() method −
Console.WriteLine("Converted to LowerCase : {0}", str.ToLower());
The following is the code in C# to convert character case.
Live Demo
using System;
using System.Collections.Generic;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
string str;
str = "AMIT";
Console.WriteLine("UpperCase : {0}", str);
// convert to lowercase
Console.WriteLine("Converted to LowerCase : {0}", str.ToLower());
Console.ReadLine();
}
}
}
UpperCase : AMIT
Converted to LowerCase : amit | [
{
"code": null,
"e": 1089,
"s": 1062,
"text": "Let’s say your string is −"
},
{
"code": null,
"e": 1103,
"s": 1089,
"text": "str = \"AMIT\";"
},
{
"code": null,
"e": 1182,
"s": 1103,
"text": "To convert the above uppercase string in lowercase, use the ToLower() method −"
},
{
"code": null,
"e": 1248,
"s": 1182,
"text": "Console.WriteLine(\"Converted to LowerCase : {0}\", str.ToLower());"
},
{
"code": null,
"e": 1307,
"s": 1248,
"text": "The following is the code in C# to convert character case."
},
{
"code": null,
"e": 1317,
"s": 1307,
"text": "Live Demo"
},
{
"code": null,
"e": 1714,
"s": 1317,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n string str;\n str = \"AMIT\";\n Console.WriteLine(\"UpperCase : {0}\", str);\n // convert to lowercase\n Console.WriteLine(\"Converted to LowerCase : {0}\", str.ToLower());\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1761,
"s": 1714,
"text": "UpperCase : AMIT\nConverted to LowerCase : amit"
}
] |
Functionally Complete Operations | 25 Nov, 2019
Prerequisite – Functional CompletenessA switching function is expressed by binary variables, the logic operation symbols, and constants 0 and 1. When every switching function can be expressed by means of operations in it, then only a set of operation is said to be functionally complete.
The set (AND, OR, NOT) is a functionally complete set.The set (AND, NOT) is said to be functionally complete.The set (OR, NOT) is also said to be functionally complete.
The set (AND, OR, NOT) is a functionally complete set.
The set (AND, NOT) is said to be functionally complete.
The set (OR, NOT) is also said to be functionally complete.
Here,The set (AND, NOT) is said to be functionally complete as (OR) can be derived using ‘AND’ and ‘NOT’ operations.Example:
(X + Y) = (X'.Y')'
X'= compliment of X.
Y'= compliment of Y.
The set (OR, NOT) is said to be functionally complete as (AND) can be derived using ‘OR’ and ‘NOT’ operations.Example:
(X.Y) = (X' + Y')'
Note:A function can be fully functionally complete, or partially functionally complete or, not at all functionally complete.
Example-1:If a function, f(X, Y, Z)= (X’ + YZ’) then check whether its functionally complete or not?Put Z = Y in the above function,Therefore, f(X, Y, Y)= (X' + YY')
= (X' + 0) since, Y.Y'=0
= X' (It is compliment i.e., NOT)Again, put X= X’ and Z= Y’ in the above function,Therefore,f(X', Y, Y')= (X')'+ Y(Y')'
= (X + Y.Y) since, (X')'= X and (Y')'= Y
= (X + Y) since, Y.Y= Y (It is OR operator)Thus, you are able to derive NOT and OR operators from the above function so this function is fully functionally complete.
f(X, Y, Y)= (X' + YY')
= (X' + 0) since, Y.Y'=0
= X' (It is compliment i.e., NOT)
Again, put X= X’ and Z= Y’ in the above function,Therefore,
f(X', Y, Y')= (X')'+ Y(Y')'
= (X + Y.Y) since, (X')'= X and (Y')'= Y
= (X + Y) since, Y.Y= Y (It is OR operator)
Thus, you are able to derive NOT and OR operators from the above function so this function is fully functionally complete.
Example-2:If a function, f(X, Y)= (X’Y) then check whether it is functionally complete or not?Put X= (X’),Therefore, f(X', Y)= (X')'.Y = X.Y (It is AND operator)Here, AND operator is derived now you need to derive NOT operator to make it functionally complete.If you put Y= 1,Then f(X, 1)= (X'), It is NOT operator.Thus, this function is partially functionally complete as you need (1) to derive NOT operator.Note: Whenever you take the help of constants (1 and 0) to make a function functionally complete then that function is called partially complete function.
f(X', Y)= (X')'.Y = X.Y (It is AND operator)
Here, AND operator is derived now you need to derive NOT operator to make it functionally complete.If you put Y= 1,
Then f(X, 1)= (X'), It is NOT operator.
Thus, this function is partially functionally complete as you need (1) to derive NOT operator.Note: Whenever you take the help of constants (1 and 0) to make a function functionally complete then that function is called partially complete function.
Example-3:If a function f(X, Y, Z)= (XY + YZ + ZX) then check whether this function is functionally complete or not?In order to make a function functionally complete, deriving NOT operator is necessary but here, there is no compliment in the function so, it is not possible to derive NOT operator.Thus, this function is not at all functionally complete.
Thus, this function is not at all functionally complete.
Digital Electronics & Logic Design
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 316,
"s": 28,
"text": "Prerequisite – Functional CompletenessA switching function is expressed by binary variables, the logic operation symbols, and constants 0 and 1. When every switching function can be expressed by means of operations in it, then only a set of operation is said to be functionally complete."
},
{
"code": null,
"e": 485,
"s": 316,
"text": "The set (AND, OR, NOT) is a functionally complete set.The set (AND, NOT) is said to be functionally complete.The set (OR, NOT) is also said to be functionally complete."
},
{
"code": null,
"e": 540,
"s": 485,
"text": "The set (AND, OR, NOT) is a functionally complete set."
},
{
"code": null,
"e": 596,
"s": 540,
"text": "The set (AND, NOT) is said to be functionally complete."
},
{
"code": null,
"e": 656,
"s": 596,
"text": "The set (OR, NOT) is also said to be functionally complete."
},
{
"code": null,
"e": 781,
"s": 656,
"text": "Here,The set (AND, NOT) is said to be functionally complete as (OR) can be derived using ‘AND’ and ‘NOT’ operations.Example:"
},
{
"code": null,
"e": 842,
"s": 781,
"text": "(X + Y) = (X'.Y')'\nX'= compliment of X.\nY'= compliment of Y."
},
{
"code": null,
"e": 961,
"s": 842,
"text": "The set (OR, NOT) is said to be functionally complete as (AND) can be derived using ‘OR’ and ‘NOT’ operations.Example:"
},
{
"code": null,
"e": 980,
"s": 961,
"text": "(X.Y) = (X' + Y')'"
},
{
"code": null,
"e": 1105,
"s": 980,
"text": "Note:A function can be fully functionally complete, or partially functionally complete or, not at all functionally complete."
},
{
"code": null,
"e": 1665,
"s": 1105,
"text": "Example-1:If a function, f(X, Y, Z)= (X’ + YZ’) then check whether its functionally complete or not?Put Z = Y in the above function,Therefore, f(X, Y, Y)= (X' + YY')\n = (X' + 0) since, Y.Y'=0\n = X' (It is compliment i.e., NOT)Again, put X= X’ and Z= Y’ in the above function,Therefore,f(X', Y, Y')= (X')'+ Y(Y')'\n = (X + Y.Y) since, (X')'= X and (Y')'= Y\n = (X + Y) since, Y.Y= Y (It is OR operator)Thus, you are able to derive NOT and OR operators from the above function so this function is fully functionally complete."
},
{
"code": null,
"e": 1768,
"s": 1665,
"text": " f(X, Y, Y)= (X' + YY')\n = (X' + 0) since, Y.Y'=0\n = X' (It is compliment i.e., NOT)"
},
{
"code": null,
"e": 1828,
"s": 1768,
"text": "Again, put X= X’ and Z= Y’ in the above function,Therefore,"
},
{
"code": null,
"e": 1963,
"s": 1828,
"text": "f(X', Y, Y')= (X')'+ Y(Y')'\n = (X + Y.Y) since, (X')'= X and (Y')'= Y\n = (X + Y) since, Y.Y= Y (It is OR operator)"
},
{
"code": null,
"e": 2086,
"s": 1963,
"text": "Thus, you are able to derive NOT and OR operators from the above function so this function is fully functionally complete."
},
{
"code": null,
"e": 2650,
"s": 2086,
"text": "Example-2:If a function, f(X, Y)= (X’Y) then check whether it is functionally complete or not?Put X= (X’),Therefore, f(X', Y)= (X')'.Y = X.Y (It is AND operator)Here, AND operator is derived now you need to derive NOT operator to make it functionally complete.If you put Y= 1,Then f(X, 1)= (X'), It is NOT operator.Thus, this function is partially functionally complete as you need (1) to derive NOT operator.Note: Whenever you take the help of constants (1 and 0) to make a function functionally complete then that function is called partially complete function."
},
{
"code": null,
"e": 2696,
"s": 2650,
"text": " f(X', Y)= (X')'.Y = X.Y (It is AND operator)"
},
{
"code": null,
"e": 2812,
"s": 2696,
"text": "Here, AND operator is derived now you need to derive NOT operator to make it functionally complete.If you put Y= 1,"
},
{
"code": null,
"e": 2852,
"s": 2812,
"text": "Then f(X, 1)= (X'), It is NOT operator."
},
{
"code": null,
"e": 3101,
"s": 2852,
"text": "Thus, this function is partially functionally complete as you need (1) to derive NOT operator.Note: Whenever you take the help of constants (1 and 0) to make a function functionally complete then that function is called partially complete function."
},
{
"code": null,
"e": 3455,
"s": 3101,
"text": "Example-3:If a function f(X, Y, Z)= (XY + YZ + ZX) then check whether this function is functionally complete or not?In order to make a function functionally complete, deriving NOT operator is necessary but here, there is no compliment in the function so, it is not possible to derive NOT operator.Thus, this function is not at all functionally complete."
},
{
"code": null,
"e": 3512,
"s": 3455,
"text": "Thus, this function is not at all functionally complete."
},
{
"code": null,
"e": 3547,
"s": 3512,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 3571,
"s": 3547,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 3579,
"s": 3571,
"text": "GATE CS"
}
] |
Python | Pandas Series.is_monotonic_increasing | 28 Jan, 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 series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.is_monotonic_increasing attribute return a boolean value. It returns True if the data in the given Series object is monotonically increasing else it return False.
Syntax:Series.is_monotonic_increasing
Parameter : None
Returns : boolean
Example #1: Use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)
Output :
Now we will use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# check if monotonically increasingsr.is_monotonic_increasing
Output :
As we can see in the output, the Series.is_monotonic_increasing attribute has returned False indicating the underlying in the given series object is not monotonically increasing. Example #2 : Use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)
Output :
Now we will use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not.
# check if monotonically increasingsr.is_monotonic_increasing
Output :
As we can see in the output, the Series.is_monotonic_increasing attribute has returned True indicating the underlying in the given series object is monotonically increasing.
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. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 499,
"s": 242,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 676,
"s": 499,
"text": "Pandas Series.is_monotonic_increasing attribute return a boolean value. It returns True if the data in the given Series object is monotonically increasing else it return False."
},
{
"code": null,
"e": 714,
"s": 676,
"text": "Syntax:Series.is_monotonic_increasing"
},
{
"code": null,
"e": 731,
"s": 714,
"text": "Parameter : None"
},
{
"code": null,
"e": 749,
"s": 731,
"text": "Returns : boolean"
},
{
"code": null,
"e": 901,
"s": 749,
"text": "Example #1: Use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)",
"e": 1141,
"s": 901,
"text": null
},
{
"code": null,
"e": 1150,
"s": 1141,
"text": "Output :"
},
{
"code": null,
"e": 1302,
"s": 1150,
"text": "Now we will use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not."
},
{
"code": "# check if monotonically increasingsr.is_monotonic_increasing",
"e": 1364,
"s": 1302,
"text": null
},
{
"code": null,
"e": 1373,
"s": 1364,
"text": "Output :"
},
{
"code": null,
"e": 1705,
"s": 1373,
"text": "As we can see in the output, the Series.is_monotonic_increasing attribute has returned False indicating the underlying in the given series object is not monotonically increasing. Example #2 : Use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)",
"e": 1944,
"s": 1705,
"text": null
},
{
"code": null,
"e": 1953,
"s": 1944,
"text": "Output :"
},
{
"code": null,
"e": 2105,
"s": 1953,
"text": "Now we will use Series.is_monotonic_increasing attribute to check if the underlying data in the given Series object is monotonically increasing or not."
},
{
"code": "# check if monotonically increasingsr.is_monotonic_increasing",
"e": 2167,
"s": 2105,
"text": null
},
{
"code": null,
"e": 2176,
"s": 2167,
"text": "Output :"
},
{
"code": null,
"e": 2350,
"s": 2176,
"text": "As we can see in the output, the Series.is_monotonic_increasing attribute has returned True indicating the underlying in the given series object is monotonically increasing."
},
{
"code": null,
"e": 2371,
"s": 2350,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2400,
"s": 2371,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2414,
"s": 2400,
"text": "Python-pandas"
},
{
"code": null,
"e": 2421,
"s": 2414,
"text": "Python"
}
] |
How to achieve <fieldset> like effect without using <fieldset> tag ? | 08 Jul, 2020
Forms are used to make a group for more understandable of all users and clients, as related data fields are easier to identify. It also makes it easier for users to concentrate on smaller and more clearly defined groups by understanding them one by one as an individual rather than try to grasp the entire form at once.
The grouping has to be created visually for users and in the code for easier data handling. By default, the <fieldset> and <legend> elements are used to group the related form data fields.
Example 1: The below example shows the usage of the default <fieldset> tag in HTML.
HTML
<!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <fieldset> <legend> Shipping Address: </legend> <div> <label for="shipping_name"> Name: </label> <br> <input type="text" name="shipping_name" id="shipping_name"> </div> <div> <label for="shipping_street"> Street: </label> <br> <input type="text" name="shipping_street" id="shipping_street"> </div> </fieldset> <fieldset> <legend> Billing Address: </legend> <div> <label for="billing_name"> Name: </label> <br> <input type="text" name="billing_name" id="billing_name"> </div> <div> <label for="billing_street"> Street: </label> <br> <input type="text" name="billing_street" id="billing_street"> </div> </fieldset></body> </html>
Output:
Alternative to the fieldset effect: The effect of the fieldset tag can be achieved using custom CSS, in case the user does not want to use the <fieldset> tag. It uses a clever use of border, margin, and various other CSS properties to achieve a similar effect.
Example 2: The below example demonstrates the alternative fieldset effect.
HTML
<!DOCTYPE html><html> <head> <style> /* Defining a custom border on all sides except the top side */ .custom-field { border: 4px solid; border-top: none; margin: 32px 2px; padding: 8px; } /* Defining the style of the heading/legend for custom fieldset */ .custom-field h1 { font: 16px normal; margin: -16px -8px 0; } /* Using float:left allows us to mimic the legend like fieldset. The float:right property can also be used to show the legend on right side */ .custom-field h1 span { float: left; } /* Creating the custom top border to make it look like fieldset defining small border before the legend. The width can be modified to change position of the legend */ .custom-field h1:before { border-top: 4px solid; content: ' '; float: left; margin: 8px 2px 0 -1px; width: 12px; } /* Defining a long border after the legend, using overflow hidden to actually hide the line behind the legend text. It can be removed for a different effect */ .custom-field h1:after { border-top: 4px solid; content: ' '; display: block; height: 24px; left: 2px; margin: 0 1px 0 0; overflow: hidden; position: relative; top: 8px; } </style></head> <body> <!-- Original fieldset tag for comparison --> <fieldset> <legend> Fieldset 1 Legend </legend> Original Fieldset </fieldset> <!-- Custom fieldset which is created using custom CSS above --> <div class="custom-field"> <h1> <span> Custom created Fieldset </span> </h1> <div> <label for="shipping_name"> Name: </label> <br> <input type="text" name="shipping_name" id="shipping_name"> </div> <div> <label for="shipping_street"> Street: </label> <br> <input type="text" name="shipping_street" id="shipping_street"> </div> </div></body> </html>
Output:
CSS-Misc
HTML-Misc
HTML-Tags
HTML5
How To
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Tutorial
How to filter object array based on attributes?
How to Align Text in HTML?
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2020"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "Forms are used to make a group for more understandable of all users and clients, as related data fields are easier to identify. It also makes it easier for users to concentrate on smaller and more clearly defined groups by understanding them one by one as an individual rather than try to grasp the entire form at once."
},
{
"code": null,
"e": 538,
"s": 348,
"text": "The grouping has to be created visually for users and in the code for easier data handling. By default, the <fieldset> and <legend> elements are used to group the related form data fields. "
},
{
"code": null,
"e": 622,
"s": 538,
"text": "Example 1: The below example shows the usage of the default <fieldset> tag in HTML."
},
{
"code": null,
"e": 627,
"s": 622,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome To GFG</h2> <fieldset> <legend> Shipping Address: </legend> <div> <label for=\"shipping_name\"> Name: </label> <br> <input type=\"text\" name=\"shipping_name\" id=\"shipping_name\"> </div> <div> <label for=\"shipping_street\"> Street: </label> <br> <input type=\"text\" name=\"shipping_street\" id=\"shipping_street\"> </div> </fieldset> <fieldset> <legend> Billing Address: </legend> <div> <label for=\"billing_name\"> Name: </label> <br> <input type=\"text\" name=\"billing_name\" id=\"billing_name\"> </div> <div> <label for=\"billing_street\"> Street: </label> <br> <input type=\"text\" name=\"billing_street\" id=\"billing_street\"> </div> </fieldset></body> </html>",
"e": 1749,
"s": 627,
"text": null
},
{
"code": null,
"e": 1757,
"s": 1749,
"text": "Output:"
},
{
"code": null,
"e": 2018,
"s": 1757,
"text": "Alternative to the fieldset effect: The effect of the fieldset tag can be achieved using custom CSS, in case the user does not want to use the <fieldset> tag. It uses a clever use of border, margin, and various other CSS properties to achieve a similar effect."
},
{
"code": null,
"e": 2093,
"s": 2018,
"text": "Example 2: The below example demonstrates the alternative fieldset effect."
},
{
"code": null,
"e": 2098,
"s": 2093,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> /* Defining a custom border on all sides except the top side */ .custom-field { border: 4px solid; border-top: none; margin: 32px 2px; padding: 8px; } /* Defining the style of the heading/legend for custom fieldset */ .custom-field h1 { font: 16px normal; margin: -16px -8px 0; } /* Using float:left allows us to mimic the legend like fieldset. The float:right property can also be used to show the legend on right side */ .custom-field h1 span { float: left; } /* Creating the custom top border to make it look like fieldset defining small border before the legend. The width can be modified to change position of the legend */ .custom-field h1:before { border-top: 4px solid; content: ' '; float: left; margin: 8px 2px 0 -1px; width: 12px; } /* Defining a long border after the legend, using overflow hidden to actually hide the line behind the legend text. It can be removed for a different effect */ .custom-field h1:after { border-top: 4px solid; content: ' '; display: block; height: 24px; left: 2px; margin: 0 1px 0 0; overflow: hidden; position: relative; top: 8px; } </style></head> <body> <!-- Original fieldset tag for comparison --> <fieldset> <legend> Fieldset 1 Legend </legend> Original Fieldset </fieldset> <!-- Custom fieldset which is created using custom CSS above --> <div class=\"custom-field\"> <h1> <span> Custom created Fieldset </span> </h1> <div> <label for=\"shipping_name\"> Name: </label> <br> <input type=\"text\" name=\"shipping_name\" id=\"shipping_name\"> </div> <div> <label for=\"shipping_street\"> Street: </label> <br> <input type=\"text\" name=\"shipping_street\" id=\"shipping_street\"> </div> </div></body> </html>",
"e": 4599,
"s": 2098,
"text": null
},
{
"code": null,
"e": 4607,
"s": 4599,
"text": "Output:"
},
{
"code": null,
"e": 4616,
"s": 4607,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4626,
"s": 4616,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4636,
"s": 4626,
"text": "HTML-Tags"
},
{
"code": null,
"e": 4642,
"s": 4636,
"text": "HTML5"
},
{
"code": null,
"e": 4649,
"s": 4642,
"text": "How To"
},
{
"code": null,
"e": 4654,
"s": 4649,
"text": "HTML"
},
{
"code": null,
"e": 4671,
"s": 4654,
"text": "Web Technologies"
},
{
"code": null,
"e": 4676,
"s": 4671,
"text": "HTML"
},
{
"code": null,
"e": 4774,
"s": 4676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4788,
"s": 4774,
"text": "Java Tutorial"
},
{
"code": null,
"e": 4836,
"s": 4788,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 4863,
"s": 4836,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 4897,
"s": 4863,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 4946,
"s": 4897,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 4994,
"s": 4946,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 5056,
"s": 4994,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5106,
"s": 5056,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5130,
"s": 5106,
"text": "REST API (Introduction)"
}
] |
Python | sympy.sqrt() method | 04 Jul, 2019
With the help of sympy.sqrt() method, we can find the square root of any value in terms of values and also in terms of symbolically simplified mathematical expression.
Syntax: sqrt(val)
Parameters:val – It is the value on which square root operation is to be performed.
Returns: Returns square root in terms of values and symbolically simplified mathematical expression corresponding to the input expression.
Example #1:
# import sympy from sympy import * val = 256 print("Value : {}".format(val)) # Use sympy.sqrt() method sqrt_val = sqrt(val) print("Square root of value : {}".format(sqrt_val))
Output:
Value : 256
Square root of value : 16
Example #2:
# import sympy from sympy import * val = 8 print("Value : {}".format(val)) # Use sympy.sqrt() method sqrt_val = sqrt(val) print("Square root of value : {}".format(sqrt_val))
Output:
Value : 8
Square root of value : 2*sqrt(2)
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2019"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "With the help of sympy.sqrt() method, we can find the square root of any value in terms of values and also in terms of symbolically simplified mathematical expression."
},
{
"code": null,
"e": 214,
"s": 196,
"text": "Syntax: sqrt(val)"
},
{
"code": null,
"e": 298,
"s": 214,
"text": "Parameters:val – It is the value on which square root operation is to be performed."
},
{
"code": null,
"e": 437,
"s": 298,
"text": "Returns: Returns square root in terms of values and symbolically simplified mathematical expression corresponding to the input expression."
},
{
"code": null,
"e": 449,
"s": 437,
"text": "Example #1:"
},
{
"code": "# import sympy from sympy import * val = 256 print(\"Value : {}\".format(val)) # Use sympy.sqrt() method sqrt_val = sqrt(val) print(\"Square root of value : {}\".format(sqrt_val)) ",
"e": 645,
"s": 449,
"text": null
},
{
"code": null,
"e": 653,
"s": 645,
"text": "Output:"
},
{
"code": null,
"e": 692,
"s": 653,
"text": "Value : 256\nSquare root of value : 16\n"
},
{
"code": null,
"e": 704,
"s": 692,
"text": "Example #2:"
},
{
"code": "# import sympy from sympy import * val = 8 print(\"Value : {}\".format(val)) # Use sympy.sqrt() method sqrt_val = sqrt(val) print(\"Square root of value : {}\".format(sqrt_val)) ",
"e": 898,
"s": 704,
"text": null
},
{
"code": null,
"e": 906,
"s": 898,
"text": "Output:"
},
{
"code": null,
"e": 950,
"s": 906,
"text": "Value : 8\nSquare root of value : 2*sqrt(2)\n"
},
{
"code": null,
"e": 956,
"s": 950,
"text": "SymPy"
},
{
"code": null,
"e": 963,
"s": 956,
"text": "Python"
}
] |
How to post data using file_get_contents in PHP ? | 11 Jun, 2020
The file_get_contents() function in PHP is used to read the contents of a file and make HTTP requests using GET and get HTTP responses using POST methods. The HTTP POST request can be made using the $context parameter of the file_get_contents() function, which posts the specified data to the URL specified using the $path parameter. The following syntax is used to POST requests to the required path:
Syntax:
string file_get_contents( $path, $include_path,
$context, $offset, $max_length )
Parameters:
$path: A required parameter that specifies the URL to post data.
$include_path: It is an optional parameter that specifies if we wish to search for files in the included path while reading.
$context: It specifies the data in the form of a JSON stream to be posted to the URL.
$start: It is an optional parameter that is used to specify the starting point in the file for reading.
$max_length: It is an optional parameter that is used to specify the number of bytes to be read.
Therefore, a content stream can be created and then, injected into the respective path. The data can contain information in the form of key-value pairs. The context stream is created by the stream_context_create($options) function with the parameters supplied in the $options argument. The parameters contain the ‘method’ consisting of either GET or POST and ‘content’ parameter containing the data that has to appear on the URL.
The code snippet indicates a sample program to post data to the URL using the file_get_contents() method. We create a folder by the name Demo which contains two files “index.php” and “demo1.php” and run it using the MAMP server.
The following code is included in ‘index.php’.
<?php // Contains the url to post data// this is my local server url// demo is the folder name and// demo1.php is other file$url_path = 'http://localhost:8888/Demo/demo1.php'; // Data is an array of key value pairs// to be reflected on the site$data = array('Name' => 'John', 'Age' => '24'); // Method specified whether to GET or// POST data with the content specified// by $data variable. 'http' is used// even in case of 'https' $options = array( 'http' => array( 'method' => 'POST', 'content' => http_build_query($data))); // Create a context stream with// the specified options$stream = stream_context_create($options); // The data is stored in the // result variable$result = file_get_contents( $url_path, false, $stream); echo $result;?>
To view the items in the content, the following code is written in ‘demo1.php’:
<?phpecho $_POST['Name'];?>
The code prints the following output on the specified URL:
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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?
How to call PHP function on the click of a Button ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 430,
"s": 28,
"text": "The file_get_contents() function in PHP is used to read the contents of a file and make HTTP requests using GET and get HTTP responses using POST methods. The HTTP POST request can be made using the $context parameter of the file_get_contents() function, which posts the specified data to the URL specified using the $path parameter. The following syntax is used to POST requests to the required path:"
},
{
"code": null,
"e": 438,
"s": 430,
"text": "Syntax:"
},
{
"code": null,
"e": 542,
"s": 438,
"text": "string file_get_contents( $path, $include_path, \n $context, $offset, $max_length )"
},
{
"code": null,
"e": 554,
"s": 542,
"text": "Parameters:"
},
{
"code": null,
"e": 619,
"s": 554,
"text": "$path: A required parameter that specifies the URL to post data."
},
{
"code": null,
"e": 744,
"s": 619,
"text": "$include_path: It is an optional parameter that specifies if we wish to search for files in the included path while reading."
},
{
"code": null,
"e": 830,
"s": 744,
"text": "$context: It specifies the data in the form of a JSON stream to be posted to the URL."
},
{
"code": null,
"e": 934,
"s": 830,
"text": "$start: It is an optional parameter that is used to specify the starting point in the file for reading."
},
{
"code": null,
"e": 1031,
"s": 934,
"text": "$max_length: It is an optional parameter that is used to specify the number of bytes to be read."
},
{
"code": null,
"e": 1461,
"s": 1031,
"text": "Therefore, a content stream can be created and then, injected into the respective path. The data can contain information in the form of key-value pairs. The context stream is created by the stream_context_create($options) function with the parameters supplied in the $options argument. The parameters contain the ‘method’ consisting of either GET or POST and ‘content’ parameter containing the data that has to appear on the URL."
},
{
"code": null,
"e": 1690,
"s": 1461,
"text": "The code snippet indicates a sample program to post data to the URL using the file_get_contents() method. We create a folder by the name Demo which contains two files “index.php” and “demo1.php” and run it using the MAMP server."
},
{
"code": null,
"e": 1737,
"s": 1690,
"text": "The following code is included in ‘index.php’."
},
{
"code": "<?php // Contains the url to post data// this is my local server url// demo is the folder name and// demo1.php is other file$url_path = 'http://localhost:8888/Demo/demo1.php'; // Data is an array of key value pairs// to be reflected on the site$data = array('Name' => 'John', 'Age' => '24'); // Method specified whether to GET or// POST data with the content specified// by $data variable. 'http' is used// even in case of 'https' $options = array( 'http' => array( 'method' => 'POST', 'content' => http_build_query($data))); // Create a context stream with// the specified options$stream = stream_context_create($options); // The data is stored in the // result variable$result = file_get_contents( $url_path, false, $stream); echo $result;?>",
"e": 2504,
"s": 1737,
"text": null
},
{
"code": null,
"e": 2584,
"s": 2504,
"text": "To view the items in the content, the following code is written in ‘demo1.php’:"
},
{
"code": "<?phpecho $_POST['Name'];?> ",
"e": 2613,
"s": 2584,
"text": null
},
{
"code": null,
"e": 2672,
"s": 2613,
"text": "The code prints the following output on the specified URL:"
},
{
"code": null,
"e": 2681,
"s": 2672,
"text": "PHP-Misc"
},
{
"code": null,
"e": 2688,
"s": 2681,
"text": "Picked"
},
{
"code": null,
"e": 2692,
"s": 2688,
"text": "PHP"
},
{
"code": null,
"e": 2705,
"s": 2692,
"text": "PHP Programs"
},
{
"code": null,
"e": 2722,
"s": 2705,
"text": "Web Technologies"
},
{
"code": null,
"e": 2749,
"s": 2722,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2753,
"s": 2749,
"text": "PHP"
},
{
"code": null,
"e": 2851,
"s": 2753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2901,
"s": 2851,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2941,
"s": 2901,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3002,
"s": 2941,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3052,
"s": 3002,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 3097,
"s": 3052,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3147,
"s": 3097,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3187,
"s": 3147,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3248,
"s": 3187,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3298,
"s": 3248,
"text": "How to check whether an array is empty using PHP?"
}
] |
Introductory guide to Information Retrieval using KNN and KDTree | 23 May, 2022
It can be defined as a software program which is used to find material(usual documents) of an unstructured nature(usually text) that satisfies an information need from within large collections(usually stored on computers). It helps users find their required information but does not explicitly return the answers to their questions. It gives information about the existence and location of the documents that might contain the required information.
Information Retrieval can be used in many scenarios, some of these are:
Web Search
E-mail Search
Searching your laptop
Legal information retrieval etc.
To learn more about information retrieval you can refer to this article.
Here we are going to discuss two algorithms which are used in Information Retrieval:
K-Nearest Neighbors(KNN)K-Dimensional Tree(KDTree)
K-Nearest Neighbors(KNN)
K-Dimensional Tree(KDTree)
It is a supervised machine learning classification algorithm. Classification gives information regarding what group something belongs to, for example, type of tumor, the favourite sport of a person etc. The K in KNN stands for the number of the nearest neighbors that the classifier will use to make its prediction.
We have training data with which we can predict the query data. For the query record which needs to be classified, the KNN algorithm computes the distance between the query record and all of the training data records. Then it looks at the K closest data records in the training data.
How to choose K value?
While choosing K value, keep following these things in mind:
If K=1, the classes are divided into regions and the query record belongs to a class according to the region it lies in.
Choose odd values of K for a 2 class problem.
K must not be a multiple of the number of classes.K not equal to ‘ni’, where n is the number of classes and i = 1, 2, 3....
Distance Metrics: The different distance metrics which can be used are:
Euclidean Distance
Manhattan Distance
Hamming Distance
Minkowski Distance
Chebyshev Distance
Let’s take an example to understand in detail how KNN algorithm works. Given below is a small dataset to predict which Pizza outlet a person prefers out of Pizza Hut & Dominos.
The outlet is chosen on the basis of Age of the person and how much Cheese Content does the person like(on the scale of 10).
This data can be visualized graphically as:
Note: If we have discrete data we first have to convert it into numeric data. Ex: Gender is given as Male and Female we can convert it to numeric as 0 and 1.
Since we have 2 classes — Pizza Hut and Dominos, we’ll take K=3.
To calculate the distance we are using the Euclidean Distance –
Prediction: On the basis of the above data we need to find out the result for the query:
Now find the distance of the record Harry to all the other records.
Given below is the calculation for the distance from Harry to Riya:
Similarly, the Distances from all the records are:
From the table we can see that the K(3) closest distances are of Mark, Rachel and Varun and Pizza Outlet they prefer are Pizza Hut, Pizza Hut and Dominos respectively. Hence, we can make the prediction that Harry prefers Pizza Hut.
Advantages of using KNN Algorithm:
No training phase
It can learn complex models easily
It is robust to noisy training data
Disadvantages of using KNN Algorithm:
Determining the value of parameter K can be difficult as different K values can give different results.
It is hard to apply on High Dimensional data
Computation cost is high as for each query it has to go through all the records which take O(N) time, where N is the number of records. If we maintain a priority queue to return the closest K records then the time complexity will be O(log(K)*N).
Due to the high computational cost, we use an algorithm which is time efficient and similar in approach – KDTree Algorithm.
KDTree is a space partitioning data structure for organizing points in K-Dimensional space. It is an improvement over KNN. It is useful for representing data efficiently. In KDTree the data points are organized and partitioned on the basis of some specific conditions.
How the algorithm works:
To understand this let’s take the sample data of Pizza Outlet which we considered in the previous example. Basically we make some axis-aligned cuts and create different regions, keeping the track of points that lie into these regions. Each region is represented by a node in the tree.
Split the regions at the mean value of the observations.
For the first cut, we’ll find the mean of all the X-coordinates (Cheese Content in this case).
Now on both the regions, we’ll calculate the means of Y-coordinates to make the cuts and so on, repeating the steps until the number of points in each region is less than a given number. You can choose any number less than the number of records in the dataset otherwise we’ll have only 1 region. The complete tree structure for this will be:
Here there are less than 3 points in each region.
Now if a new query point comes, and we need to find out in which region will the point be, we can traverse the tree. In this case, the query point(chosen randomly) lies in the 4th region.
We can find it’s the nearest neighbour in this region.
But this might not be the actual the nearest neighbour for this query in the entire dataset. Hence we traverse back to node 2 and then check the remaining subtree for this node.
We get the tightest box for node 5 which contains all the points in this region. After that, we check if the distance of this box is closer to the query point than the current nearest neighbour or not.
In this case, the distance of the box is smaller. Hence, there is a point in region point which is closer to the query point than the current the nearest neighbour. We find that point, and then we again traverse back the tree to node 3 and check the same.
Now the distance is greater than the distance from the new nearest neighbour. Hence, we stop here, and we do not need to search for this sub-tree. We can prune this part of the tree.
Note: A branch of the tree is eliminated only when K points have been found and the branch cannot have points closer than any of the K current bests.
KDtree Implementation:
We will be performing Document Retrieval which is the most widely used use case for Information Retrieval. For this, we have made a sample dataset of articles available on the internet on famous celebrities. On entering the name you get the names of the celebrities similar to the given name. Here the K value is taken as 3. We will get three nearest neighbors of the document name entered.
You can get the dataset from here.
Code:
python3
#import the libraries requiredimport numpy as npimport pandas as pdimport nltkfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformerfrom sklearn.neighbors import KDTree #Reading the datasetperson = pd.read_csv('famous_people.csv') #Printing first five rows of the datasetprint(person.head())
Output:
Code:
python3
#Counting the frequency of occurrence of each wordcount_vector = CountVectorizer()train_counts = count_vector.fit_transform(person.Text) #Using tf-idf to reduce the weight of common wordstfidf_transform = TfidfTransformer()train_tfidf = tfidf_transform.fit_transform(train_counts)a = np.array(train_tfidf.toarray()) #obtaining the KDTreekdtree = KDTree(a ,leaf_size=3) #take the name of the personality as inputperson_name=input("Enter the name of the Person:- ") #Using KDTree to get K articles similar to the given nameperson['tfidf']=list(train_tfidf.toarray())distance, idx = kdtree.query(person['tfidf'][person['Name']== person_name].tolist(), k=3)for i, value in list(enumerate(idx[0])): print("Name : {}".format(person['Name'][value])) print("Distance : {}".format(distance[0][i])) print("URI : {}".format(person['URI'][value]))
Output:
We get MS Dhoni, Virat Kohli and Yuvraj Singh as the 3 nearest neighbors for MS Dhoni.
At each level of the tree, KDTree divides the range of the domain in half.Hence they are useful for performing range searches.
It is an improvement of KNN as discussed earlier.
The complexity lies in between O(log N) to O(N) where N is the number of nodes in the tree.
Degradation of performance when high dimensional data is used.The algorithm will need to visit many more branches.If the dimensionality of dataset is K then the number of nodes N>>(2^K).
If the query point if far from all the points in the dataset then we might have to traverse the whole tree to find the nearest neighbors.
For any queries do leave a comment below.
sweetyty
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Bagging vs Boosting in Machine Learning
Principal Component Analysis with Python
Types of Environments in AI
An introduction to Machine Learning | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 477,
"s": 28,
"text": "It can be defined as a software program which is used to find material(usual documents) of an unstructured nature(usually text) that satisfies an information need from within large collections(usually stored on computers). It helps users find their required information but does not explicitly return the answers to their questions. It gives information about the existence and location of the documents that might contain the required information."
},
{
"code": null,
"e": 549,
"s": 477,
"text": "Information Retrieval can be used in many scenarios, some of these are:"
},
{
"code": null,
"e": 560,
"s": 549,
"text": "Web Search"
},
{
"code": null,
"e": 574,
"s": 560,
"text": "E-mail Search"
},
{
"code": null,
"e": 596,
"s": 574,
"text": "Searching your laptop"
},
{
"code": null,
"e": 629,
"s": 596,
"text": "Legal information retrieval etc."
},
{
"code": null,
"e": 702,
"s": 629,
"text": "To learn more about information retrieval you can refer to this article."
},
{
"code": null,
"e": 787,
"s": 702,
"text": "Here we are going to discuss two algorithms which are used in Information Retrieval:"
},
{
"code": null,
"e": 838,
"s": 787,
"text": "K-Nearest Neighbors(KNN)K-Dimensional Tree(KDTree)"
},
{
"code": null,
"e": 863,
"s": 838,
"text": "K-Nearest Neighbors(KNN)"
},
{
"code": null,
"e": 890,
"s": 863,
"text": "K-Dimensional Tree(KDTree)"
},
{
"code": null,
"e": 1206,
"s": 890,
"text": "It is a supervised machine learning classification algorithm. Classification gives information regarding what group something belongs to, for example, type of tumor, the favourite sport of a person etc. The K in KNN stands for the number of the nearest neighbors that the classifier will use to make its prediction."
},
{
"code": null,
"e": 1490,
"s": 1206,
"text": "We have training data with which we can predict the query data. For the query record which needs to be classified, the KNN algorithm computes the distance between the query record and all of the training data records. Then it looks at the K closest data records in the training data."
},
{
"code": null,
"e": 1513,
"s": 1490,
"text": "How to choose K value?"
},
{
"code": null,
"e": 1574,
"s": 1513,
"text": "While choosing K value, keep following these things in mind:"
},
{
"code": null,
"e": 1695,
"s": 1574,
"text": "If K=1, the classes are divided into regions and the query record belongs to a class according to the region it lies in."
},
{
"code": null,
"e": 1741,
"s": 1695,
"text": "Choose odd values of K for a 2 class problem."
},
{
"code": null,
"e": 1865,
"s": 1741,
"text": "K must not be a multiple of the number of classes.K not equal to ‘ni’, where n is the number of classes and i = 1, 2, 3...."
},
{
"code": null,
"e": 1937,
"s": 1865,
"text": "Distance Metrics: The different distance metrics which can be used are:"
},
{
"code": null,
"e": 1956,
"s": 1937,
"text": "Euclidean Distance"
},
{
"code": null,
"e": 1975,
"s": 1956,
"text": "Manhattan Distance"
},
{
"code": null,
"e": 1992,
"s": 1975,
"text": "Hamming Distance"
},
{
"code": null,
"e": 2011,
"s": 1992,
"text": "Minkowski Distance"
},
{
"code": null,
"e": 2030,
"s": 2011,
"text": "Chebyshev Distance"
},
{
"code": null,
"e": 2207,
"s": 2030,
"text": "Let’s take an example to understand in detail how KNN algorithm works. Given below is a small dataset to predict which Pizza outlet a person prefers out of Pizza Hut & Dominos."
},
{
"code": null,
"e": 2332,
"s": 2207,
"text": "The outlet is chosen on the basis of Age of the person and how much Cheese Content does the person like(on the scale of 10)."
},
{
"code": null,
"e": 2377,
"s": 2332,
"text": "This data can be visualized graphically as: "
},
{
"code": null,
"e": 2535,
"s": 2377,
"text": "Note: If we have discrete data we first have to convert it into numeric data. Ex: Gender is given as Male and Female we can convert it to numeric as 0 and 1."
},
{
"code": null,
"e": 2600,
"s": 2535,
"text": "Since we have 2 classes — Pizza Hut and Dominos, we’ll take K=3."
},
{
"code": null,
"e": 2664,
"s": 2600,
"text": "To calculate the distance we are using the Euclidean Distance –"
},
{
"code": null,
"e": 2753,
"s": 2664,
"text": "Prediction: On the basis of the above data we need to find out the result for the query:"
},
{
"code": null,
"e": 2821,
"s": 2753,
"text": "Now find the distance of the record Harry to all the other records."
},
{
"code": null,
"e": 2898,
"s": 2821,
"text": " Given below is the calculation for the distance from Harry to Riya:"
},
{
"code": null,
"e": 2957,
"s": 2898,
"text": " Similarly, the Distances from all the records are:"
},
{
"code": null,
"e": 3189,
"s": 2957,
"text": "From the table we can see that the K(3) closest distances are of Mark, Rachel and Varun and Pizza Outlet they prefer are Pizza Hut, Pizza Hut and Dominos respectively. Hence, we can make the prediction that Harry prefers Pizza Hut."
},
{
"code": null,
"e": 3225,
"s": 3189,
"text": "Advantages of using KNN Algorithm: "
},
{
"code": null,
"e": 3243,
"s": 3225,
"text": "No training phase"
},
{
"code": null,
"e": 3278,
"s": 3243,
"text": "It can learn complex models easily"
},
{
"code": null,
"e": 3314,
"s": 3278,
"text": "It is robust to noisy training data"
},
{
"code": null,
"e": 3353,
"s": 3314,
"text": "Disadvantages of using KNN Algorithm: "
},
{
"code": null,
"e": 3457,
"s": 3353,
"text": "Determining the value of parameter K can be difficult as different K values can give different results."
},
{
"code": null,
"e": 3502,
"s": 3457,
"text": "It is hard to apply on High Dimensional data"
},
{
"code": null,
"e": 3748,
"s": 3502,
"text": "Computation cost is high as for each query it has to go through all the records which take O(N) time, where N is the number of records. If we maintain a priority queue to return the closest K records then the time complexity will be O(log(K)*N)."
},
{
"code": null,
"e": 3872,
"s": 3748,
"text": "Due to the high computational cost, we use an algorithm which is time efficient and similar in approach – KDTree Algorithm."
},
{
"code": null,
"e": 4141,
"s": 3872,
"text": "KDTree is a space partitioning data structure for organizing points in K-Dimensional space. It is an improvement over KNN. It is useful for representing data efficiently. In KDTree the data points are organized and partitioned on the basis of some specific conditions."
},
{
"code": null,
"e": 4166,
"s": 4141,
"text": "How the algorithm works:"
},
{
"code": null,
"e": 4451,
"s": 4166,
"text": "To understand this let’s take the sample data of Pizza Outlet which we considered in the previous example. Basically we make some axis-aligned cuts and create different regions, keeping the track of points that lie into these regions. Each region is represented by a node in the tree."
},
{
"code": null,
"e": 4508,
"s": 4451,
"text": "Split the regions at the mean value of the observations."
},
{
"code": null,
"e": 4603,
"s": 4508,
"text": "For the first cut, we’ll find the mean of all the X-coordinates (Cheese Content in this case)."
},
{
"code": null,
"e": 4945,
"s": 4603,
"text": "Now on both the regions, we’ll calculate the means of Y-coordinates to make the cuts and so on, repeating the steps until the number of points in each region is less than a given number. You can choose any number less than the number of records in the dataset otherwise we’ll have only 1 region. The complete tree structure for this will be:"
},
{
"code": null,
"e": 4995,
"s": 4945,
"text": "Here there are less than 3 points in each region."
},
{
"code": null,
"e": 5183,
"s": 4995,
"text": "Now if a new query point comes, and we need to find out in which region will the point be, we can traverse the tree. In this case, the query point(chosen randomly) lies in the 4th region."
},
{
"code": null,
"e": 5238,
"s": 5183,
"text": "We can find it’s the nearest neighbour in this region."
},
{
"code": null,
"e": 5416,
"s": 5238,
"text": "But this might not be the actual the nearest neighbour for this query in the entire dataset. Hence we traverse back to node 2 and then check the remaining subtree for this node."
},
{
"code": null,
"e": 5618,
"s": 5416,
"text": "We get the tightest box for node 5 which contains all the points in this region. After that, we check if the distance of this box is closer to the query point than the current nearest neighbour or not."
},
{
"code": null,
"e": 5874,
"s": 5618,
"text": "In this case, the distance of the box is smaller. Hence, there is a point in region point which is closer to the query point than the current the nearest neighbour. We find that point, and then we again traverse back the tree to node 3 and check the same."
},
{
"code": null,
"e": 6057,
"s": 5874,
"text": "Now the distance is greater than the distance from the new nearest neighbour. Hence, we stop here, and we do not need to search for this sub-tree. We can prune this part of the tree."
},
{
"code": null,
"e": 6207,
"s": 6057,
"text": "Note: A branch of the tree is eliminated only when K points have been found and the branch cannot have points closer than any of the K current bests."
},
{
"code": null,
"e": 6231,
"s": 6207,
"text": "KDtree Implementation: "
},
{
"code": null,
"e": 6622,
"s": 6231,
"text": "We will be performing Document Retrieval which is the most widely used use case for Information Retrieval. For this, we have made a sample dataset of articles available on the internet on famous celebrities. On entering the name you get the names of the celebrities similar to the given name. Here the K value is taken as 3. We will get three nearest neighbors of the document name entered."
},
{
"code": null,
"e": 6657,
"s": 6622,
"text": "You can get the dataset from here."
},
{
"code": null,
"e": 6664,
"s": 6657,
"text": "Code: "
},
{
"code": null,
"e": 6672,
"s": 6664,
"text": "python3"
},
{
"code": "#import the libraries requiredimport numpy as npimport pandas as pdimport nltkfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformerfrom sklearn.neighbors import KDTree #Reading the datasetperson = pd.read_csv('famous_people.csv') #Printing first five rows of the datasetprint(person.head())",
"e": 6987,
"s": 6672,
"text": null
},
{
"code": null,
"e": 6995,
"s": 6987,
"text": "Output:"
},
{
"code": null,
"e": 7003,
"s": 6995,
"text": " Code: "
},
{
"code": null,
"e": 7011,
"s": 7003,
"text": "python3"
},
{
"code": "#Counting the frequency of occurrence of each wordcount_vector = CountVectorizer()train_counts = count_vector.fit_transform(person.Text) #Using tf-idf to reduce the weight of common wordstfidf_transform = TfidfTransformer()train_tfidf = tfidf_transform.fit_transform(train_counts)a = np.array(train_tfidf.toarray()) #obtaining the KDTreekdtree = KDTree(a ,leaf_size=3) #take the name of the personality as inputperson_name=input(\"Enter the name of the Person:- \") #Using KDTree to get K articles similar to the given nameperson['tfidf']=list(train_tfidf.toarray())distance, idx = kdtree.query(person['tfidf'][person['Name']== person_name].tolist(), k=3)for i, value in list(enumerate(idx[0])): print(\"Name : {}\".format(person['Name'][value])) print(\"Distance : {}\".format(distance[0][i])) print(\"URI : {}\".format(person['URI'][value]))",
"e": 7856,
"s": 7011,
"text": null
},
{
"code": null,
"e": 7864,
"s": 7856,
"text": "Output:"
},
{
"code": null,
"e": 7951,
"s": 7864,
"text": "We get MS Dhoni, Virat Kohli and Yuvraj Singh as the 3 nearest neighbors for MS Dhoni."
},
{
"code": null,
"e": 8078,
"s": 7951,
"text": "At each level of the tree, KDTree divides the range of the domain in half.Hence they are useful for performing range searches."
},
{
"code": null,
"e": 8128,
"s": 8078,
"text": "It is an improvement of KNN as discussed earlier."
},
{
"code": null,
"e": 8220,
"s": 8128,
"text": "The complexity lies in between O(log N) to O(N) where N is the number of nodes in the tree."
},
{
"code": null,
"e": 8407,
"s": 8220,
"text": "Degradation of performance when high dimensional data is used.The algorithm will need to visit many more branches.If the dimensionality of dataset is K then the number of nodes N>>(2^K)."
},
{
"code": null,
"e": 8545,
"s": 8407,
"text": "If the query point if far from all the points in the dataset then we might have to traverse the whole tree to find the nearest neighbors."
},
{
"code": null,
"e": 8587,
"s": 8545,
"text": "For any queries do leave a comment below."
},
{
"code": null,
"e": 8596,
"s": 8587,
"text": "sweetyty"
},
{
"code": null,
"e": 8613,
"s": 8596,
"text": "Machine Learning"
},
{
"code": null,
"e": 8630,
"s": 8613,
"text": "Machine Learning"
},
{
"code": null,
"e": 8728,
"s": 8630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8769,
"s": 8728,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 8802,
"s": 8769,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 8838,
"s": 8802,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 8862,
"s": 8838,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 8913,
"s": 8862,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 8946,
"s": 8913,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 8986,
"s": 8946,
"text": "Bagging vs Boosting in Machine Learning"
},
{
"code": null,
"e": 9027,
"s": 8986,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 9055,
"s": 9027,
"text": "Types of Environments in AI"
}
] |
Replace node with depth in a binary tree | 02 May, 2022
Given a binary tree, replace each node with its depth value. For example, consider the following tree. Root is at depth 0, change its value to 0 and next level nodes are at depth 1 and so on.
3 0
/ \ / \
2 5 == >; 1 1
/ \ / \
1 4 2 2
The idea is to traverse tree starting from root. While traversing pass depth of node as parameter. We can track depth by passing it as 0 for root and one-plus-current-depth for children.Below is the implementation of the idea.
C++
Java
Python3
C#
Javascript
// CPP program to replace every key value// with its depth.#include<bits/stdc++.h>using namespace std; /* A tree node structure */struct Node{ int data; struct Node *left, *right;}; /* Utility function to create a new Binary Tree node */struct Node* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Helper function replaces the data with depth// Note : Default value of level is 0 for root.void replaceNode(struct Node *node, int level=0){ // Base Case if (node == NULL) return; // Replace data with current depth node->data = level; replaceNode(node->left, level+1); replaceNode(node->right, level+1);} // A utility function to print inorder// traversal of a Binary Treevoid printInorder(struct Node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data <<" "; printInorder(node->right);} /* Driver function to test above functions */int main(){ struct Node *root = new struct Node; /* Constructing tree given in the above figure */ root = newNode(3); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(1); root->left->right = newNode(4); cout << "Before Replacing Nodes\n"; printInorder(root); replaceNode(root); cout << endl; cout << "After Replacing Nodes\n"; printInorder(root); return 0;}
// Java program to replace every key value// with its depth.class GfG { /* A tree node structure */static class Node{ int data; Node left, right;} /* Utility function to create anew Binary Tree node */static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} // Helper function replaces the data with depth// Note : Default value of level is 0 for root.static void replaceNode(Node node, int level){ // Base Case if (node == null) return; // Replace data with current depth node.data = level; replaceNode(node.left, level+1); replaceNode(node.right, level+1);} // A utility function to print inorder// traversal of a Binary Treestatic void printInorder(Node node){ if (node == null) return; printInorder(node.left); System.out.print(node.data + " "); printInorder(node.right);} /* Driver function to test above functions */public static void main(String[] args){ Node root = new Node(); /* Constructing tree given in the above figure */ root = newNode(3); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(1); root.left.right = newNode(4); System.out.println("Before Replacing Nodes"); printInorder(root); replaceNode(root, 0); System.out.println(); System.out.println("After Replacing Nodes"); printInorder(root); }}
# Python3 program to replace every key# value with its depth. class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Helper function replaces the data with depth# Note : Default value of level is 0 for root.def replaceNode(node, level = 0): # Base Case if (node == None): return # Replace data with current depth node.data = level replaceNode(node.left, level + 1) replaceNode(node.right, level + 1) # A utility function to print inorder# traversal of a Binary Treedef printInorder(node): if (node == None): return printInorder(node.left) print(node.data, end = " ") printInorder(node.right) # Driver Codeif __name__ == '__main__': # Constructing tree given in # the above figure root = newNode(3) root.left = newNode(2) root.right = newNode(5) root.left.left = newNode(1) root.left.right = newNode(4) print("Before Replacing Nodes") printInorder(root) replaceNode(root) print() print("After Replacing Nodes") printInorder(root) # This code is contributed by PranchalK
// C# program to replace every key value// with its depth.using System; public class GfG{ /* A tree node structure */ public class Node { public int data; public Node left, right; } /* Utility function to create a new Binary Tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Helper function replaces the data with depth // Note : Default value of level is 0 for root. static void replaceNode(Node node, int level) { // Base Case if (node == null) return; // Replace data with current depth node.data = level; replaceNode(node.left, level + 1); replaceNode(node.right, level + 1); } // A utility function to print inorder // traversal of a Binary Tree static void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + " "); printInorder(node.right); } /* Driver code*/ public static void Main(String[] args) { Node root = new Node(); /* Constructing tree given in the above figure */ root = newNode(3); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(1); root.left.right = newNode(4); Console.WriteLine("Before Replacing Nodes"); printInorder(root); replaceNode(root, 0); Console.WriteLine(); Console.WriteLine("After Replacing Nodes"); printInorder(root); }} // This code is contributed Rajput-Ji
<script> // JavaScript program to replace every // key value with its depth. class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* Utility function to create a new Binary Tree node */ function newNode(data) { let temp = new Node(data); return temp; } // Helper function replaces the data with depth // Note : Default value of level is 0 for root. function replaceNode(node, level) { // Base Case if (node == null) return; // Replace data with current depth node.data = level; replaceNode(node.left, level+1); replaceNode(node.right, level+1); } // A utility function to print inorder // traversal of a Binary Tree function printInorder(node) { if (node == null) return; printInorder(node.left); document.write(node.data + " "); printInorder(node.right); } let root = new Node(); /* Constructing tree given in the above figure */ root = newNode(3); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(1); root.left.right = newNode(4); document.write("Before Replacing Nodes" + "</br>"); printInorder(root); replaceNode(root, 0); document.write("</br>"); document.write("</br>"); document.write("After Replacing Nodes" + "</br>"); printInorder(root); </script>
Output:
Before Replacing Nodes
1 2 4 3 5
After Replacing Nodes
2 1 2 0 1
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Replace node with depth in a binary tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReplace node with depth in a binary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=p5_P7Rx-98A" 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 Chhavi. 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.
prerna saini
PranchalKatiyar
Rajput-Ji
rameshtravel07
simmytarika5
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Decision Tree
Diagonal Traversal of Binary Tree | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 May, 2022"
},
{
"code": null,
"e": 246,
"s": 52,
"text": "Given a binary tree, replace each node with its depth value. For example, consider the following tree. Root is at depth 0, change its value to 0 and next level nodes are at depth 1 and so on. "
},
{
"code": null,
"e": 421,
"s": 246,
"text": " 3 0\n / \\ / \\\n 2 5 == >; 1 1\n / \\ / \\\n 1 4 2 2"
},
{
"code": null,
"e": 652,
"s": 423,
"text": "The idea is to traverse tree starting from root. While traversing pass depth of node as parameter. We can track depth by passing it as 0 for root and one-plus-current-depth for children.Below is the implementation of the idea. "
},
{
"code": null,
"e": 656,
"s": 652,
"text": "C++"
},
{
"code": null,
"e": 661,
"s": 656,
"text": "Java"
},
{
"code": null,
"e": 669,
"s": 661,
"text": "Python3"
},
{
"code": null,
"e": 672,
"s": 669,
"text": "C#"
},
{
"code": null,
"e": 683,
"s": 672,
"text": "Javascript"
},
{
"code": "// CPP program to replace every key value// with its depth.#include<bits/stdc++.h>using namespace std; /* A tree node structure */struct Node{ int data; struct Node *left, *right;}; /* Utility function to create a new Binary Tree node */struct Node* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Helper function replaces the data with depth// Note : Default value of level is 0 for root.void replaceNode(struct Node *node, int level=0){ // Base Case if (node == NULL) return; // Replace data with current depth node->data = level; replaceNode(node->left, level+1); replaceNode(node->right, level+1);} // A utility function to print inorder// traversal of a Binary Treevoid printInorder(struct Node* node){ if (node == NULL) return; printInorder(node->left); cout << node->data <<\" \"; printInorder(node->right);} /* Driver function to test above functions */int main(){ struct Node *root = new struct Node; /* Constructing tree given in the above figure */ root = newNode(3); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(1); root->left->right = newNode(4); cout << \"Before Replacing Nodes\\n\"; printInorder(root); replaceNode(root); cout << endl; cout << \"After Replacing Nodes\\n\"; printInorder(root); return 0;}",
"e": 2135,
"s": 683,
"text": null
},
{
"code": "// Java program to replace every key value// with its depth.class GfG { /* A tree node structure */static class Node{ int data; Node left, right;} /* Utility function to create anew Binary Tree node */static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} // Helper function replaces the data with depth// Note : Default value of level is 0 for root.static void replaceNode(Node node, int level){ // Base Case if (node == null) return; // Replace data with current depth node.data = level; replaceNode(node.left, level+1); replaceNode(node.right, level+1);} // A utility function to print inorder// traversal of a Binary Treestatic void printInorder(Node node){ if (node == null) return; printInorder(node.left); System.out.print(node.data + \" \"); printInorder(node.right);} /* Driver function to test above functions */public static void main(String[] args){ Node root = new Node(); /* Constructing tree given in the above figure */ root = newNode(3); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(1); root.left.right = newNode(4); System.out.println(\"Before Replacing Nodes\"); printInorder(root); replaceNode(root, 0); System.out.println(); System.out.println(\"After Replacing Nodes\"); printInorder(root); }}",
"e": 3575,
"s": 2135,
"text": null
},
{
"code": "# Python3 program to replace every key# value with its depth. class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Helper function replaces the data with depth# Note : Default value of level is 0 for root.def replaceNode(node, level = 0): # Base Case if (node == None): return # Replace data with current depth node.data = level replaceNode(node.left, level + 1) replaceNode(node.right, level + 1) # A utility function to print inorder# traversal of a Binary Treedef printInorder(node): if (node == None): return printInorder(node.left) print(node.data, end = \" \") printInorder(node.right) # Driver Codeif __name__ == '__main__': # Constructing tree given in # the above figure root = newNode(3) root.left = newNode(2) root.right = newNode(5) root.left.left = newNode(1) root.left.right = newNode(4) print(\"Before Replacing Nodes\") printInorder(root) replaceNode(root) print() print(\"After Replacing Nodes\") printInorder(root) # This code is contributed by PranchalK",
"e": 4701,
"s": 3575,
"text": null
},
{
"code": "// C# program to replace every key value// with its depth.using System; public class GfG{ /* A tree node structure */ public class Node { public int data; public Node left, right; } /* Utility function to create a new Binary Tree node */ static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } // Helper function replaces the data with depth // Note : Default value of level is 0 for root. static void replaceNode(Node node, int level) { // Base Case if (node == null) return; // Replace data with current depth node.data = level; replaceNode(node.left, level + 1); replaceNode(node.right, level + 1); } // A utility function to print inorder // traversal of a Binary Tree static void printInorder(Node node) { if (node == null) return; printInorder(node.left); Console.Write(node.data + \" \"); printInorder(node.right); } /* Driver code*/ public static void Main(String[] args) { Node root = new Node(); /* Constructing tree given in the above figure */ root = newNode(3); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(1); root.left.right = newNode(4); Console.WriteLine(\"Before Replacing Nodes\"); printInorder(root); replaceNode(root, 0); Console.WriteLine(); Console.WriteLine(\"After Replacing Nodes\"); printInorder(root); }} // This code is contributed Rajput-Ji",
"e": 6391,
"s": 4701,
"text": null
},
{
"code": "<script> // JavaScript program to replace every // key value with its depth. class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } /* Utility function to create a new Binary Tree node */ function newNode(data) { let temp = new Node(data); return temp; } // Helper function replaces the data with depth // Note : Default value of level is 0 for root. function replaceNode(node, level) { // Base Case if (node == null) return; // Replace data with current depth node.data = level; replaceNode(node.left, level+1); replaceNode(node.right, level+1); } // A utility function to print inorder // traversal of a Binary Tree function printInorder(node) { if (node == null) return; printInorder(node.left); document.write(node.data + \" \"); printInorder(node.right); } let root = new Node(); /* Constructing tree given in the above figure */ root = newNode(3); root.left = newNode(2); root.right = newNode(5); root.left.left = newNode(1); root.left.right = newNode(4); document.write(\"Before Replacing Nodes\" + \"</br>\"); printInorder(root); replaceNode(root, 0); document.write(\"</br>\"); document.write(\"</br>\"); document.write(\"After Replacing Nodes\" + \"</br>\"); printInorder(root); </script>",
"e": 7911,
"s": 6391,
"text": null
},
{
"code": null,
"e": 7921,
"s": 7911,
"text": "Output: "
},
{
"code": null,
"e": 7989,
"s": 7921,
"text": "Before Replacing Nodes\n1 2 4 3 5 \n\nAfter Replacing Nodes\n2 1 2 0 1 "
},
{
"code": null,
"e": 8000,
"s": 7991,
"text": "Chapters"
},
{
"code": null,
"e": 8027,
"s": 8000,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 8077,
"s": 8027,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 8100,
"s": 8077,
"text": "captions off, selected"
},
{
"code": null,
"e": 8108,
"s": 8100,
"text": "English"
},
{
"code": null,
"e": 8126,
"s": 8108,
"text": "default, selected"
},
{
"code": null,
"e": 8150,
"s": 8126,
"text": "This is a modal window."
},
{
"code": null,
"e": 8219,
"s": 8150,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 8241,
"s": 8219,
"text": "End of dialog window."
},
{
"code": null,
"e": 9139,
"s": 8241,
"text": "Replace node with depth in a binary tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReplace node with depth in a binary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=p5_P7Rx-98A\" 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": 9554,
"s": 9139,
"text": "This article is contributed by Chhavi. 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": 9569,
"s": 9556,
"text": "prerna saini"
},
{
"code": null,
"e": 9585,
"s": 9569,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 9595,
"s": 9585,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9610,
"s": 9595,
"text": "rameshtravel07"
},
{
"code": null,
"e": 9623,
"s": 9610,
"text": "simmytarika5"
},
{
"code": null,
"e": 9628,
"s": 9623,
"text": "Tree"
},
{
"code": null,
"e": 9633,
"s": 9628,
"text": "Tree"
},
{
"code": null,
"e": 9731,
"s": 9633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9763,
"s": 9731,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9799,
"s": 9763,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 9840,
"s": 9799,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 9904,
"s": 9840,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9947,
"s": 9904,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 9980,
"s": 9947,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 10006,
"s": 9980,
"text": "Diameter of a Binary Tree"
},
{
"code": null,
"e": 10054,
"s": 10006,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 10068,
"s": 10054,
"text": "Decision Tree"
}
] |
Queue.Dequeue Method in C# | 04 Feb, 2019
The Dequeue() method is used to returns the object at the beginning of the Queue. This method is similar to the Peek() Method. The only difference between Dequeue and Peek method is that Peek() method will not modify the Queue but Dequeue will modify. This method is an O(1) operation and comes under System.Collections namespace.
Syntax:
public virtual object Dequeue ();
Return value: It returns the object which is removed from the beginning of the Queue.
Exception: The method throws InvalidOperationException on calling empty queue, therefore always check that the total count of a queue is greater than zero before calling the Dequeue() method.
Below programs illustrate the use of the above-discussed method:
// C# Program to illustrate the use // of Queue.Dequeue Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { Queue queue = new Queue(); queue.Enqueue(3); queue.Enqueue(2); queue.Enqueue(1); queue.Enqueue("Four"); Console.WriteLine("Number of elements in the Queue: {0}", queue.Count); // Retrieveing top element of queue Console.WriteLine("Top element of queue is:"); Console.WriteLine(queue.Dequeue()); // printing the no of queue element // after dequeue operation Console.WriteLine("Number of elements in the Queue: {0}", queue.Count); }}
Number of elements in the Queue: 4
Top element of queue is:
3
Number of elements in the Queue: 3
// C# Program to illustrate the use // of Queue.Dequeue Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { Queue queue = new Queue(); // Adding elements in Queue queue.Enqueue(2); queue.Enqueue("Four"); Console.WriteLine("Number of elements in the Queue: {0}", queue.Count); // Retrieveing top element of queue Console.WriteLine("Top element of queue is:"); Console.WriteLine(queue.Dequeue()); // printing the no. of queue element // after dequeue operation Console.WriteLine("Number of elements in the Queue: {0}", queue.Count); }}
Number of elements in the Queue: 2
Top element of queue is:
2
Number of elements in the Queue: 1
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.dequeue?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.
Difference between Abstract Class and Interface in C#
C# Dictionary with examples
C# | How to check whether a List contains a specified element
C# | Multiple inheritance using interfaces
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Feb, 2019"
},
{
"code": null,
"e": 384,
"s": 53,
"text": "The Dequeue() method is used to returns the object at the beginning of the Queue. This method is similar to the Peek() Method. The only difference between Dequeue and Peek method is that Peek() method will not modify the Queue but Dequeue will modify. This method is an O(1) operation and comes under System.Collections namespace."
},
{
"code": null,
"e": 392,
"s": 384,
"text": "Syntax:"
},
{
"code": null,
"e": 427,
"s": 392,
"text": "public virtual object Dequeue ();\n"
},
{
"code": null,
"e": 513,
"s": 427,
"text": "Return value: It returns the object which is removed from the beginning of the Queue."
},
{
"code": null,
"e": 705,
"s": 513,
"text": "Exception: The method throws InvalidOperationException on calling empty queue, therefore always check that the total count of a queue is greater than zero before calling the Dequeue() method."
},
{
"code": null,
"e": 770,
"s": 705,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": "// C# Program to illustrate the use // of Queue.Dequeue Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { Queue queue = new Queue(); queue.Enqueue(3); queue.Enqueue(2); queue.Enqueue(1); queue.Enqueue(\"Four\"); Console.WriteLine(\"Number of elements in the Queue: {0}\", queue.Count); // Retrieveing top element of queue Console.WriteLine(\"Top element of queue is:\"); Console.WriteLine(queue.Dequeue()); // printing the no of queue element // after dequeue operation Console.WriteLine(\"Number of elements in the Queue: {0}\", queue.Count); }}",
"e": 1567,
"s": 770,
"text": null
},
{
"code": null,
"e": 1665,
"s": 1567,
"text": "Number of elements in the Queue: 4\nTop element of queue is:\n3\nNumber of elements in the Queue: 3\n"
},
{
"code": "// C# Program to illustrate the use // of Queue.Dequeue Methodusing System;using System.Collections; class GFG { // Main Method public static void Main() { Queue queue = new Queue(); // Adding elements in Queue queue.Enqueue(2); queue.Enqueue(\"Four\"); Console.WriteLine(\"Number of elements in the Queue: {0}\", queue.Count); // Retrieveing top element of queue Console.WriteLine(\"Top element of queue is:\"); Console.WriteLine(queue.Dequeue()); // printing the no. of queue element // after dequeue operation Console.WriteLine(\"Number of elements in the Queue: {0}\", queue.Count); }}",
"e": 2449,
"s": 1665,
"text": null
},
{
"code": null,
"e": 2547,
"s": 2449,
"text": "Number of elements in the Queue: 2\nTop element of queue is:\n2\nNumber of elements in the Queue: 1\n"
},
{
"code": null,
"e": 2558,
"s": 2547,
"text": "Reference:"
},
{
"code": null,
"e": 2659,
"s": 2558,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.dequeue?view=netframework-4.7.2"
},
{
"code": null,
"e": 2688,
"s": 2659,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 2713,
"s": 2688,
"text": "CSharp-Collections-Queue"
},
{
"code": null,
"e": 2727,
"s": 2713,
"text": "CSharp-method"
},
{
"code": null,
"e": 2730,
"s": 2727,
"text": "C#"
},
{
"code": null,
"e": 2828,
"s": 2730,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2882,
"s": 2828,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 2910,
"s": 2882,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 2972,
"s": 2910,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 3015,
"s": 2972,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3038,
"s": 3015,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 3066,
"s": 3038,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 3108,
"s": 3066,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 3139,
"s": 3108,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 3188,
"s": 3139,
"text": "Differences Between .NET Core and .NET Framework"
}
] |
Python – Group Sublists by another List | 22 Jun, 2020
Sometimes, while working with lists, we can have a problem in which we need to group all the sublists, separated by elements present in different list. This type of custom grouping is uncommon utility but having solution to these can always be handy. Lets discuss certain way in which this task can be performed.
Method #1 : Using loop + generator(yield)This is brute force way in which this task can be performed. In this, we iterate the list and make groups dynamically using yield. We keep track of elements occurred and restart list when we find element in second list.
# Python3 code to demonstrate # Group Sublists by another List# using loop + generator(yield) # helper functiondef grp_ele(test_list1, test_list2): temp = [] for i in test_list1: if i in test_list2: if temp: yield temp temp = [] yield i else: temp.append(i) if temp: yield temp # Initializing liststest_list1 = [8, 5, 9, 11, 3, 7]test_list2 = [9, 11] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Group Sublists by another List# using loop + generator(yield)res = list(grp_ele(test_list1, test_list2)) # printing result print ("The Grouped list is : " + str(res))
The original list 1 is : [8, 5, 9, 11, 3, 7]
The original list 2 is : [9, 11]
The Grouped list is : [[8, 5], 9, 11, [3, 7]]
nidhi_biet
Python list-programs
Python-list-of-lists
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "Sometimes, while working with lists, we can have a problem in which we need to group all the sublists, separated by elements present in different list. This type of custom grouping is uncommon utility but having solution to these can always be handy. Lets discuss certain way in which this task can be performed."
},
{
"code": null,
"e": 602,
"s": 341,
"text": "Method #1 : Using loop + generator(yield)This is brute force way in which this task can be performed. In this, we iterate the list and make groups dynamically using yield. We keep track of elements occurred and restart list when we find element in second list."
},
{
"code": "# Python3 code to demonstrate # Group Sublists by another List# using loop + generator(yield) # helper functiondef grp_ele(test_list1, test_list2): temp = [] for i in test_list1: if i in test_list2: if temp: yield temp temp = [] yield i else: temp.append(i) if temp: yield temp # Initializing liststest_list1 = [8, 5, 9, 11, 3, 7]test_list2 = [9, 11] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Group Sublists by another List# using loop + generator(yield)res = list(grp_ele(test_list1, test_list2)) # printing result print (\"The Grouped list is : \" + str(res))",
"e": 1358,
"s": 602,
"text": null
},
{
"code": null,
"e": 1483,
"s": 1358,
"text": "The original list 1 is : [8, 5, 9, 11, 3, 7]\nThe original list 2 is : [9, 11]\nThe Grouped list is : [[8, 5], 9, 11, [3, 7]]\n"
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1517,
"s": 1496,
"text": "Python list-programs"
},
{
"code": null,
"e": 1538,
"s": 1517,
"text": "Python-list-of-lists"
},
{
"code": null,
"e": 1545,
"s": 1538,
"text": "Python"
},
{
"code": null,
"e": 1561,
"s": 1545,
"text": "Python Programs"
},
{
"code": null,
"e": 1659,
"s": 1561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1677,
"s": 1659,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1719,
"s": 1677,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1741,
"s": 1719,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1776,
"s": 1741,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1802,
"s": 1776,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1845,
"s": 1802,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1867,
"s": 1845,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1906,
"s": 1867,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1944,
"s": 1906,
"text": "Python | Convert a list to dictionary"
}
] |
Subdomain in Flask | Python | 17 Apr, 2019
Prerequisite: Introduction to Flask
In this article, we will learn how to setup subdomains in Flask. But first, let’s go through the basic like what is DNS and subdomains.
Domain Name System (DNS):The Domain Name System (DNS) is a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or a private network. Most prominently, it translates more readily memorized domain names to the numerical IP addresses needed for locating and identifying computer services and devices with the underlying network protocols.DNS is basically using words (Domain Names) in place of numbers (IP addresses) to locate something. For example, 127.0.0.1 is used to point the local computer address, localhost.
Subdomain:A subdomain is a domain that is part of a larger domain. Basically, it’s a sort of child domain which means it is a part of some parent domain. For example, practice.geeksforgeeks.org and contribute.geeksforgeeks.org are subdomains of the geeksforgeeks.org domain, which in turn is a subdomain of the org top-level domain (TLD).These are different from the path defined after TLD as in geeksforgeeks.org/basic/.
Further, we will discuss how to set endpoints in your web application using Python’s micro-framework, Flask.
Adding alternate domain name for local IP –Prior to the coding part, we got to setup hosts file in order to provide alternate names to local IP so that we are able to test our app locally. Edit this file with root privileges.
Linux: /etc/hosts
Windows: C:\Windows\System32\Drivers\etc\hosts
Add these lines to set up alternate domain names.
127.0.0.1 vibhu.gfg
127.0.0.1 practice.vibhu.gfg
In this example, we’re considering vibhu.gfg as our domain name, with gfg being the TLD. practice would be a subdomain we’re targeting to set in our web app.
Setting up the Server –In the app’s configuration SERVER_NAME is set to the domain name, along with the port number we intend to run our app on. The default port, flask uses is 5000, so we take it as it is.
from flask import Flask app = Flask(__name__) @app.route('/')def home(): return "Welcome to GeeksForGeeks !" if __name__ == "__main__": website_url = 'vibhu.gfg:5000' app.config['SERVER_NAME'] = website_url app.run()
Output:Run the app and notice the link on which the app is running.Test the link on your browser.
Adding Several Endpoints –
basic: An endpoint with extension to the path on the main domain.practice: An endpoint serving on the practice subdomain.courses: An endpoint with extension on to the path on the practice subdomain.
basic: An endpoint with extension to the path on the main domain.
practice: An endpoint serving on the practice subdomain.
courses: An endpoint with extension on to the path on the practice subdomain.
Subdomains in Flask are set using the subdomain parameter in the app.route decorator.
from flask import Flask app = Flask(__name__) @app.route('/')def home(): return "Welcome to GeeksForGeeks !" @app.route('/basic/')def basic(): return "Basic Category Articles " \ "listed on this page." @app.route('/', subdomain ='practice')def practice(): return "Coding Practice Page" @app.route('/courses/', subdomain ='practice')def courses(): return "Courses listed " \ "under practice subdomain." if __name__ == "__main__": website_url = 'vibhu.gfg:5000' app.config['SERVER_NAME'] = website_url app.run()
Output:
Python
Web Technologies
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
Python String | replace()
How to Install PIP on Windows ?
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": 54,
"s": 26,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 90,
"s": 54,
"text": "Prerequisite: Introduction to Flask"
},
{
"code": null,
"e": 226,
"s": 90,
"text": "In this article, we will learn how to setup subdomains in Flask. But first, let’s go through the basic like what is DNS and subdomains."
},
{
"code": null,
"e": 803,
"s": 226,
"text": "Domain Name System (DNS):The Domain Name System (DNS) is a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or a private network. Most prominently, it translates more readily memorized domain names to the numerical IP addresses needed for locating and identifying computer services and devices with the underlying network protocols.DNS is basically using words (Domain Names) in place of numbers (IP addresses) to locate something. For example, 127.0.0.1 is used to point the local computer address, localhost."
},
{
"code": null,
"e": 1225,
"s": 803,
"text": "Subdomain:A subdomain is a domain that is part of a larger domain. Basically, it’s a sort of child domain which means it is a part of some parent domain. For example, practice.geeksforgeeks.org and contribute.geeksforgeeks.org are subdomains of the geeksforgeeks.org domain, which in turn is a subdomain of the org top-level domain (TLD).These are different from the path defined after TLD as in geeksforgeeks.org/basic/."
},
{
"code": null,
"e": 1334,
"s": 1225,
"text": "Further, we will discuss how to set endpoints in your web application using Python’s micro-framework, Flask."
},
{
"code": null,
"e": 1560,
"s": 1334,
"text": "Adding alternate domain name for local IP –Prior to the coding part, we got to setup hosts file in order to provide alternate names to local IP so that we are able to test our app locally. Edit this file with root privileges."
},
{
"code": null,
"e": 1626,
"s": 1560,
"text": "Linux: /etc/hosts \nWindows: C:\\Windows\\System32\\Drivers\\etc\\hosts"
},
{
"code": null,
"e": 1676,
"s": 1626,
"text": "Add these lines to set up alternate domain names."
},
{
"code": null,
"e": 1737,
"s": 1676,
"text": "127.0.0.1 vibhu.gfg\n127.0.0.1 practice.vibhu.gfg"
},
{
"code": null,
"e": 1895,
"s": 1737,
"text": "In this example, we’re considering vibhu.gfg as our domain name, with gfg being the TLD. practice would be a subdomain we’re targeting to set in our web app."
},
{
"code": null,
"e": 2102,
"s": 1895,
"text": "Setting up the Server –In the app’s configuration SERVER_NAME is set to the domain name, along with the port number we intend to run our app on. The default port, flask uses is 5000, so we take it as it is."
},
{
"code": "from flask import Flask app = Flask(__name__) @app.route('/')def home(): return \"Welcome to GeeksForGeeks !\" if __name__ == \"__main__\": website_url = 'vibhu.gfg:5000' app.config['SERVER_NAME'] = website_url app.run()",
"e": 2338,
"s": 2102,
"text": null
},
{
"code": null,
"e": 2436,
"s": 2338,
"text": "Output:Run the app and notice the link on which the app is running.Test the link on your browser."
},
{
"code": null,
"e": 2463,
"s": 2436,
"text": "Adding Several Endpoints –"
},
{
"code": null,
"e": 2662,
"s": 2463,
"text": "basic: An endpoint with extension to the path on the main domain.practice: An endpoint serving on the practice subdomain.courses: An endpoint with extension on to the path on the practice subdomain."
},
{
"code": null,
"e": 2728,
"s": 2662,
"text": "basic: An endpoint with extension to the path on the main domain."
},
{
"code": null,
"e": 2785,
"s": 2728,
"text": "practice: An endpoint serving on the practice subdomain."
},
{
"code": null,
"e": 2863,
"s": 2785,
"text": "courses: An endpoint with extension on to the path on the practice subdomain."
},
{
"code": null,
"e": 2949,
"s": 2863,
"text": "Subdomains in Flask are set using the subdomain parameter in the app.route decorator."
},
{
"code": "from flask import Flask app = Flask(__name__) @app.route('/')def home(): return \"Welcome to GeeksForGeeks !\" @app.route('/basic/')def basic(): return \"Basic Category Articles \" \\ \"listed on this page.\" @app.route('/', subdomain ='practice')def practice(): return \"Coding Practice Page\" @app.route('/courses/', subdomain ='practice')def courses(): return \"Courses listed \" \\ \"under practice subdomain.\" if __name__ == \"__main__\": website_url = 'vibhu.gfg:5000' app.config['SERVER_NAME'] = website_url app.run()",
"e": 3516,
"s": 2949,
"text": null
},
{
"code": null,
"e": 3524,
"s": 3516,
"text": "Output:"
},
{
"code": null,
"e": 3531,
"s": 3524,
"text": "Python"
},
{
"code": null,
"e": 3548,
"s": 3531,
"text": "Web Technologies"
},
{
"code": null,
"e": 3646,
"s": 3548,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3664,
"s": 3646,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3706,
"s": 3664,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3728,
"s": 3706,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3754,
"s": 3728,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3786,
"s": 3754,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3819,
"s": 3786,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3881,
"s": 3819,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3942,
"s": 3881,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3992,
"s": 3942,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
NumberFormat getCurrencyInstance() method in Java with Examples | 12 Apr, 2022
The getCurrencyInstance() method is a built-in method of the java.text.NumberFormat returns a currency format for the current default FORMAT locale.Syntax:public static final NumberFormat getCurrencyInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for currency formattingBelow is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar
Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar
Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance()The getCurrencyInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a currency format for any specifies locale.Syntax:public static NumberFormat getCurrencyInstance?(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for currency formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getCurrencyInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar
Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)
The getCurrencyInstance() method is a built-in method of the java.text.NumberFormat returns a currency format for the current default FORMAT locale.Syntax:public static final NumberFormat getCurrencyInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for currency formattingBelow is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar
Program 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar
Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance()
Syntax:
public static final NumberFormat getCurrencyInstance()
Parameters: The function does not accepts any parameter.
Return Value: The function returns the NumberFormat instance for currency formatting
Below is the implementation of the above function:
Program 1:
// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}
Canadian Dollar
Program 2:
// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}
US Dollar
Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance()
The getCurrencyInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a currency format for any specifies locale.Syntax:public static NumberFormat getCurrencyInstance?(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for currency formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getCurrencyInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar
Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)
Syntax:
public static NumberFormat getCurrencyInstance?(Locale inLocale)
Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.
Return Value: The function returns the NumberFormat instance for currency formatting.
Below is the implementation of the above function:
Program 1:
// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getCurrencyInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}
Canadian Dollar
Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)
Java-Functions
Java-NumberFormat
Java-text package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 3026,
"s": 53,
"text": "The getCurrencyInstance() method is a built-in method of the java.text.NumberFormat returns a currency format for the current default FORMAT locale.Syntax:public static final NumberFormat getCurrencyInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for currency formattingBelow is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance()The getCurrencyInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a currency format for any specifies locale.Syntax:public static NumberFormat getCurrencyInstance?(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for currency formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getCurrencyInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)"
},
{
"code": null,
"e": 4808,
"s": 3026,
"text": "The getCurrencyInstance() method is a built-in method of the java.text.NumberFormat returns a currency format for the current default FORMAT locale.Syntax:public static final NumberFormat getCurrencyInstance()Parameters: The function does not accepts any parameter.Return Value: The function returns the NumberFormat instance for currency formattingBelow is the implementation of the above function:Program 1:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nProgram 2:// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:US Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance()"
},
{
"code": null,
"e": 4816,
"s": 4808,
"text": "Syntax:"
},
{
"code": null,
"e": 4871,
"s": 4816,
"text": "public static final NumberFormat getCurrencyInstance()"
},
{
"code": null,
"e": 4928,
"s": 4871,
"text": "Parameters: The function does not accepts any parameter."
},
{
"code": null,
"e": 5013,
"s": 4928,
"text": "Return Value: The function returns the NumberFormat instance for currency formatting"
},
{
"code": null,
"e": 5064,
"s": 5013,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 5075,
"s": 5064,
"text": "Program 1:"
},
{
"code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}",
"e": 5754,
"s": 5075,
"text": null
},
{
"code": null,
"e": 5771,
"s": 5754,
"text": "Canadian Dollar\n"
},
{
"code": null,
"e": 5782,
"s": 5771,
"text": "Program 2:"
},
{
"code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}",
"e": 6324,
"s": 5782,
"text": null
},
{
"code": null,
"e": 6335,
"s": 6324,
"text": "US Dollar\n"
},
{
"code": null,
"e": 6439,
"s": 6335,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance()"
},
{
"code": null,
"e": 7631,
"s": 6439,
"text": "The getCurrencyInstance(Locale inLocale) method is a built-in method of the java.text.NumberFormat returns a currency format for any specifies locale.Syntax:public static NumberFormat getCurrencyInstance?(Locale inLocale)Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies.Return Value: The function returns the NumberFormat instance for currency formatting.Below is the implementation of the above function:Program 1:// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getCurrencyInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}Output:Canadian Dollar\nReference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)"
},
{
"code": null,
"e": 7639,
"s": 7631,
"text": "Syntax:"
},
{
"code": null,
"e": 7704,
"s": 7639,
"text": "public static NumberFormat getCurrencyInstance?(Locale inLocale)"
},
{
"code": null,
"e": 7825,
"s": 7704,
"text": "Parameters: The function accepts a single mandatory parameter inLocale which describes the locale which is to specifies."
},
{
"code": null,
"e": 7911,
"s": 7825,
"text": "Return Value: The function returns the NumberFormat instance for currency formatting."
},
{
"code": null,
"e": 7962,
"s": 7911,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 7973,
"s": 7962,
"text": "Program 1:"
},
{
"code": "// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getCurrencyInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}",
"e": 8537,
"s": 7973,
"text": null
},
{
"code": null,
"e": 8554,
"s": 8537,
"text": "Canadian Dollar\n"
},
{
"code": null,
"e": 8674,
"s": 8554,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)"
},
{
"code": null,
"e": 8689,
"s": 8674,
"text": "Java-Functions"
},
{
"code": null,
"e": 8707,
"s": 8689,
"text": "Java-NumberFormat"
},
{
"code": null,
"e": 8725,
"s": 8707,
"text": "Java-text package"
},
{
"code": null,
"e": 8730,
"s": 8725,
"text": "Java"
},
{
"code": null,
"e": 8735,
"s": 8730,
"text": "Java"
}
] |
How to print a blank line in C#? | To display a line in C#, use the Console.WriteLine().
Under that set a blank line −
Console.WriteLine(" ");
The following is the code that displays a blank line −
Live Demo
using System;
namespace Program {
public class Demo {
public static void Main(String[] args) {
Console.WriteLine(" ");
Console.WriteLine("Displayed a blank line above!\n");
Console.ReadLine();
}
}
}
Displayed a blank line above! | [
{
"code": null,
"e": 1241,
"s": 1187,
"text": "To display a line in C#, use the Console.WriteLine()."
},
{
"code": null,
"e": 1271,
"s": 1241,
"text": "Under that set a blank line −"
},
{
"code": null,
"e": 1295,
"s": 1271,
"text": "Console.WriteLine(\" \");"
},
{
"code": null,
"e": 1350,
"s": 1295,
"text": "The following is the code that displays a blank line −"
},
{
"code": null,
"e": 1361,
"s": 1350,
"text": " Live Demo"
},
{
"code": null,
"e": 1607,
"s": 1361,
"text": "using System;\nnamespace Program {\n public class Demo {\n public static void Main(String[] args) {\n\n Console.WriteLine(\" \");\n Console.WriteLine(\"Displayed a blank line above!\\n\");\n Console.ReadLine();\n\n }\n }\n}"
},
{
"code": null,
"e": 1637,
"s": 1607,
"text": "Displayed a blank line above!"
}
] |
Implementing Forward Iterator in BST | 31 Jan, 2022
Given a Binary search tree, the task is to implement forward iterator on it with the following functions.
curr(): returns the pointer to current element.next(): iterates to the next smallest element in the Binary Search Tree.isEnd(): returns true if there no node left to traverse else false.
curr(): returns the pointer to current element.
next(): iterates to the next smallest element in the Binary Search Tree.
isEnd(): returns true if there no node left to traverse else false.
Iterator traverses the BST in sorted order(increasing). We will implement the iterator using a stack data structure.Initialisation:
We will create a stack named “q” to store the nodes of BST.
Create a variable “curr” and initialise it with pointer to root.
While “curr” is not NULL Push “curr” in the stack ‘q’.Set curr = curr -> left
Push “curr” in the stack ‘q’.
Set curr = curr -> left
curr()
Returns the value at the top of the stack ‘q’. Note: It might throw segmentation fault if the stack is empty.
Time Complexity: O(1)
next()
Declare pointer variable “curr” which points to node.
Set curr = q.top()->right.
Pop top most element of stack.
While “curr” is not NULL Push “curr” in the stack ‘q’.Set curr = curr -> left.
Push “curr” in the stack ‘q’.
Set curr = curr -> left.
Time Complexity: O(1) on average of all calls. Can be O(h) for a single call in the worst case.
isEnd()
Returns true if stack “q” is empty else return false.
Time Complexity: O(1) Worst Case space complexity for this implementation of iterators is O(h). It should be noticed that iterator points to the top-most element of the stack.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Iterator for BSTclass bstit {private: // Stack to store the nodes // of BST stack<node*> q; public: // Constructor for the class bstit(node* root) { // Initializing stack node* curr = root; while (curr != NULL) q.push(curr), curr = curr->left; } // Function to return // current element iterator // is pointing to node* curr() { return q.top(); } // Function to iterate to next // element of BST void next() { node* curr = q.top()->right; q.pop(); while (curr != NULL) q.push(curr), curr = curr->left; } // Function to check if // stack is empty bool isEnd() { return !(q.size()); }}; // Function to iterator to every element// using iteratorvoid iterate(bstit it){ while (!it.isEnd()) cout << it.curr()->data << " ", it.next();} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); // Iterator to BST bstit it(root); // Function to test iterator iterate(it); return 0;}
// Java implementation of the approachimport java.util.*; // Node of the binary treeclass TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }} // Iterator for BSTclass BSTIterator{ // Stack to store the nodes// of BSTStack<TreeNode> s; // Constructor for the classpublic BSTIterator(TreeNode root){ // Initializing stack s = new Stack<>(); TreeNode curr = root; while (curr != null) { s.push(curr); curr = curr.left; }} // Function to return// current element iterator// is pointing toTreeNode curr(){ return s.peek();} // Function to iterate to next// element of BSTpublic void next(){ TreeNode temp = s.peek().right; s.pop(); while (temp != null) { s.push(temp); temp = temp.left; }} // Function to check if// stack is emptypublic boolean isEnd(){ return !s.isEmpty();} // Function to iterator to every element// using iteratorvoid iterate(){ while (isEnd()) { System.out.print(curr().val + " "); next(); }}} class BinaryTree{ TreeNode root; // Driver codepublic static void main(String args[]){ // Let us construct a tree shown in // the above figure BinaryTree tree = new BinaryTree(); tree.root = new TreeNode(5); tree.root.left = new TreeNode(3); tree.root.right = new TreeNode(7); tree.root.left.left = new TreeNode(2); tree.root.left.right = new TreeNode(4); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(8); // Iterator to BST BSTIterator it = new BSTIterator(tree.root); // Function to test iterator it.iterate();}} // This code is contributed by nobody_cares
# Python 3 implementation of the approach# Node of the binary treeclass node: def __init__(self,data): self.data = data self.left = None self.right = None # Iterator for BSTclass bstit: # Stack to store the nodes # of BST __stack = [] # Constructor for the class def __init__(self, root): # Initializing stack curr = root while (curr is not None): self.__stack.append(curr) curr = curr.left # Function to return # current element iterator # is pointing to def curr(self): return self.__stack[-1] # Function to iterate to next # element of BST def next(self): curr = self.__stack[-1].right self.__stack.pop() while (curr is not None): self.__stack.append(curr) curr = curr.left # Function to check if # stack is empty def isEnd(self): return not len(self.__stack) # Function to iterator to every element# using iteratordef iterate(it): while (not it.isEnd()): print(it.curr().data,end=" ") it.next() # Driver codeif __name__ == '__main__': root = node(5) root.left = node(3) root.right = node(7) root.left.left = node(2) root.left.right = node(4) root.right.left = node(6) root.right.right = node(8) # Iterator to BST it = bstit(root) # Function to test iterator iterate(it) print()# This code is added by Amartya Ghosh
// C# implementation of the approachusing System;using System.Collections.Generic; // Node of the binary treepublic class TreeNode{ public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; }} // Iterator for BSTpublic class BSTIterator{ // Stack to store the nodes // of BST Stack<TreeNode> s; // Constructor for the class public BSTIterator(TreeNode root) { // Initializing stack s = new Stack<TreeNode>(); TreeNode curr = root; while (curr != null) { s.Push(curr); curr = curr.left; } } // Function to return // current element iterator // is pointing to TreeNode curr() { return s.Peek(); } // Function to iterate to next // element of BST public void next() { TreeNode temp = s.Peek().right; s.Pop(); while (temp != null) { s.Push(temp); temp = temp.left; } } // Function to check if // stack is empty public bool isEnd() { return s.Count!=0; } // Function to iterator to every element // using iterator public void iterate() { while (isEnd()) { Console.Write(curr().val + " "); next(); } }} public class BinaryTree{ TreeNode root; // Driver code public static void Main(String []args) { // Let us construct a tree shown in // the above figure BinaryTree tree = new BinaryTree(); tree.root = new TreeNode(5); tree.root.left = new TreeNode(3); tree.root.right = new TreeNode(7); tree.root.left.left = new TreeNode(2); tree.root.left.right = new TreeNode(4); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(8); // Iterator to BST BSTIterator it = new BSTIterator(tree.root); // Function to test iterator it.iterate(); }} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Stack to store the nodes// of BSTlet q = []; // Constructor for the classfunction bstit(root){ // Initializing stack let curr = root; while (curr != null) { q.push(curr); curr = curr.left; }} // Function to return// current element iterator// is pointing tofunction curr(){ return q[q.length - 1];} // Function to iterate to previous// element of BSTfunction next(){ let curr = q[q.length - 1].right; q.pop(); while (curr != null) { q.push(curr); curr = curr.left; }} // Function to check if// stack is emptyfunction isEnd(){ return (q.length == 0);} // Function to test the iteratorfunction iterate(){ while (!isEnd()) { document.write(curr().data + " "); next(); }} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); // Iterator to BSTbstit(root); // Function call to test the iteratoriterate(); // This code is contributed by Rajput-Ji </script>
2 3 4 5 6 7 8
nobody_cares
arorakashish0911
amartyaghoshgfg
Rajput-Ji
Binary Search Tree
C++
Data Structures
Stack
Data Structures
Stack
Binary Search Tree
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find postorder traversal of BST from preorder traversal
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Sorted Array to Balanced BST
Optimal Binary Search Tree | DP-24
Lowest Common Ancestor in a Binary Search Tree.
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Jan, 2022"
},
{
"code": null,
"e": 161,
"s": 54,
"text": "Given a Binary search tree, the task is to implement forward iterator on it with the following functions. "
},
{
"code": null,
"e": 348,
"s": 161,
"text": "curr(): returns the pointer to current element.next(): iterates to the next smallest element in the Binary Search Tree.isEnd(): returns true if there no node left to traverse else false."
},
{
"code": null,
"e": 396,
"s": 348,
"text": "curr(): returns the pointer to current element."
},
{
"code": null,
"e": 469,
"s": 396,
"text": "next(): iterates to the next smallest element in the Binary Search Tree."
},
{
"code": null,
"e": 537,
"s": 469,
"text": "isEnd(): returns true if there no node left to traverse else false."
},
{
"code": null,
"e": 670,
"s": 537,
"text": "Iterator traverses the BST in sorted order(increasing). We will implement the iterator using a stack data structure.Initialisation: "
},
{
"code": null,
"e": 730,
"s": 670,
"text": "We will create a stack named “q” to store the nodes of BST."
},
{
"code": null,
"e": 795,
"s": 730,
"text": "Create a variable “curr” and initialise it with pointer to root."
},
{
"code": null,
"e": 873,
"s": 795,
"text": "While “curr” is not NULL Push “curr” in the stack ‘q’.Set curr = curr -> left"
},
{
"code": null,
"e": 903,
"s": 873,
"text": "Push “curr” in the stack ‘q’."
},
{
"code": null,
"e": 927,
"s": 903,
"text": "Set curr = curr -> left"
},
{
"code": null,
"e": 935,
"s": 927,
"text": "curr() "
},
{
"code": null,
"e": 1047,
"s": 935,
"text": "Returns the value at the top of the stack ‘q’. Note: It might throw segmentation fault if the stack is empty. "
},
{
"code": null,
"e": 1069,
"s": 1047,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 1077,
"s": 1069,
"text": "next() "
},
{
"code": null,
"e": 1131,
"s": 1077,
"text": "Declare pointer variable “curr” which points to node."
},
{
"code": null,
"e": 1158,
"s": 1131,
"text": "Set curr = q.top()->right."
},
{
"code": null,
"e": 1189,
"s": 1158,
"text": "Pop top most element of stack."
},
{
"code": null,
"e": 1268,
"s": 1189,
"text": "While “curr” is not NULL Push “curr” in the stack ‘q’.Set curr = curr -> left."
},
{
"code": null,
"e": 1298,
"s": 1268,
"text": "Push “curr” in the stack ‘q’."
},
{
"code": null,
"e": 1323,
"s": 1298,
"text": "Set curr = curr -> left."
},
{
"code": null,
"e": 1419,
"s": 1323,
"text": "Time Complexity: O(1) on average of all calls. Can be O(h) for a single call in the worst case."
},
{
"code": null,
"e": 1428,
"s": 1419,
"text": "isEnd() "
},
{
"code": null,
"e": 1484,
"s": 1428,
"text": "Returns true if stack “q” is empty else return false. "
},
{
"code": null,
"e": 1660,
"s": 1484,
"text": "Time Complexity: O(1) Worst Case space complexity for this implementation of iterators is O(h). It should be noticed that iterator points to the top-most element of the stack."
},
{
"code": null,
"e": 1711,
"s": 1660,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1715,
"s": 1711,
"text": "C++"
},
{
"code": null,
"e": 1720,
"s": 1715,
"text": "Java"
},
{
"code": null,
"e": 1728,
"s": 1720,
"text": "Python3"
},
{
"code": null,
"e": 1731,
"s": 1728,
"text": "C#"
},
{
"code": null,
"e": 1742,
"s": 1731,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Iterator for BSTclass bstit {private: // Stack to store the nodes // of BST stack<node*> q; public: // Constructor for the class bstit(node* root) { // Initializing stack node* curr = root; while (curr != NULL) q.push(curr), curr = curr->left; } // Function to return // current element iterator // is pointing to node* curr() { return q.top(); } // Function to iterate to next // element of BST void next() { node* curr = q.top()->right; q.pop(); while (curr != NULL) q.push(curr), curr = curr->left; } // Function to check if // stack is empty bool isEnd() { return !(q.size()); }}; // Function to iterator to every element// using iteratorvoid iterate(bstit it){ while (!it.isEnd()) cout << it.curr()->data << \" \", it.next();} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); // Iterator to BST bstit it(root); // Function to test iterator iterate(it); return 0;}",
"e": 3262,
"s": 1742,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; // Node of the binary treeclass TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }} // Iterator for BSTclass BSTIterator{ // Stack to store the nodes// of BSTStack<TreeNode> s; // Constructor for the classpublic BSTIterator(TreeNode root){ // Initializing stack s = new Stack<>(); TreeNode curr = root; while (curr != null) { s.push(curr); curr = curr.left; }} // Function to return// current element iterator// is pointing toTreeNode curr(){ return s.peek();} // Function to iterate to next// element of BSTpublic void next(){ TreeNode temp = s.peek().right; s.pop(); while (temp != null) { s.push(temp); temp = temp.left; }} // Function to check if// stack is emptypublic boolean isEnd(){ return !s.isEmpty();} // Function to iterator to every element// using iteratorvoid iterate(){ while (isEnd()) { System.out.print(curr().val + \" \"); next(); }}} class BinaryTree{ TreeNode root; // Driver codepublic static void main(String args[]){ // Let us construct a tree shown in // the above figure BinaryTree tree = new BinaryTree(); tree.root = new TreeNode(5); tree.root.left = new TreeNode(3); tree.root.right = new TreeNode(7); tree.root.left.left = new TreeNode(2); tree.root.left.right = new TreeNode(4); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(8); // Iterator to BST BSTIterator it = new BSTIterator(tree.root); // Function to test iterator it.iterate();}} // This code is contributed by nobody_cares",
"e": 4973,
"s": 3262,
"text": null
},
{
"code": "# Python 3 implementation of the approach# Node of the binary treeclass node: def __init__(self,data): self.data = data self.left = None self.right = None # Iterator for BSTclass bstit: # Stack to store the nodes # of BST __stack = [] # Constructor for the class def __init__(self, root): # Initializing stack curr = root while (curr is not None): self.__stack.append(curr) curr = curr.left # Function to return # current element iterator # is pointing to def curr(self): return self.__stack[-1] # Function to iterate to next # element of BST def next(self): curr = self.__stack[-1].right self.__stack.pop() while (curr is not None): self.__stack.append(curr) curr = curr.left # Function to check if # stack is empty def isEnd(self): return not len(self.__stack) # Function to iterator to every element# using iteratordef iterate(it): while (not it.isEnd()): print(it.curr().data,end=\" \") it.next() # Driver codeif __name__ == '__main__': root = node(5) root.left = node(3) root.right = node(7) root.left.left = node(2) root.left.right = node(4) root.right.left = node(6) root.right.right = node(8) # Iterator to BST it = bstit(root) # Function to test iterator iterate(it) print()# This code is added by Amartya Ghosh",
"e": 6424,
"s": 4973,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; // Node of the binary treepublic class TreeNode{ public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; }} // Iterator for BSTpublic class BSTIterator{ // Stack to store the nodes // of BST Stack<TreeNode> s; // Constructor for the class public BSTIterator(TreeNode root) { // Initializing stack s = new Stack<TreeNode>(); TreeNode curr = root; while (curr != null) { s.Push(curr); curr = curr.left; } } // Function to return // current element iterator // is pointing to TreeNode curr() { return s.Peek(); } // Function to iterate to next // element of BST public void next() { TreeNode temp = s.Peek().right; s.Pop(); while (temp != null) { s.Push(temp); temp = temp.left; } } // Function to check if // stack is empty public bool isEnd() { return s.Count!=0; } // Function to iterator to every element // using iterator public void iterate() { while (isEnd()) { Console.Write(curr().val + \" \"); next(); } }} public class BinaryTree{ TreeNode root; // Driver code public static void Main(String []args) { // Let us construct a tree shown in // the above figure BinaryTree tree = new BinaryTree(); tree.root = new TreeNode(5); tree.root.left = new TreeNode(3); tree.root.right = new TreeNode(7); tree.root.left.left = new TreeNode(2); tree.root.left.right = new TreeNode(4); tree.root.right.left = new TreeNode(6); tree.root.right.right = new TreeNode(8); // Iterator to BST BSTIterator it = new BSTIterator(tree.root); // Function to test iterator it.iterate(); }} // This code is contributed by Rajput-Ji",
"e": 8231,
"s": 6424,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Stack to store the nodes// of BSTlet q = []; // Constructor for the classfunction bstit(root){ // Initializing stack let curr = root; while (curr != null) { q.push(curr); curr = curr.left; }} // Function to return// current element iterator// is pointing tofunction curr(){ return q[q.length - 1];} // Function to iterate to previous// element of BSTfunction next(){ let curr = q[q.length - 1].right; q.pop(); while (curr != null) { q.push(curr); curr = curr.left; }} // Function to check if// stack is emptyfunction isEnd(){ return (q.length == 0);} // Function to test the iteratorfunction iterate(){ while (!isEnd()) { document.write(curr().data + \" \"); next(); }} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); // Iterator to BSTbstit(root); // Function call to test the iteratoriterate(); // This code is contributed by Rajput-Ji </script>",
"e": 9541,
"s": 8231,
"text": null
},
{
"code": null,
"e": 9555,
"s": 9541,
"text": "2 3 4 5 6 7 8"
},
{
"code": null,
"e": 9570,
"s": 9557,
"text": "nobody_cares"
},
{
"code": null,
"e": 9587,
"s": 9570,
"text": "arorakashish0911"
},
{
"code": null,
"e": 9603,
"s": 9587,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 9613,
"s": 9603,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9632,
"s": 9613,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 9636,
"s": 9632,
"text": "C++"
},
{
"code": null,
"e": 9652,
"s": 9636,
"text": "Data Structures"
},
{
"code": null,
"e": 9658,
"s": 9652,
"text": "Stack"
},
{
"code": null,
"e": 9674,
"s": 9658,
"text": "Data Structures"
},
{
"code": null,
"e": 9680,
"s": 9674,
"text": "Stack"
},
{
"code": null,
"e": 9699,
"s": 9680,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 9703,
"s": 9699,
"text": "CPP"
},
{
"code": null,
"e": 9801,
"s": 9703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9857,
"s": 9801,
"text": "Find postorder traversal of BST from preorder traversal"
},
{
"code": null,
"e": 9927,
"s": 9857,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 9956,
"s": 9927,
"text": "Sorted Array to Balanced BST"
},
{
"code": null,
"e": 9991,
"s": 9956,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 10039,
"s": 9991,
"text": "Lowest Common Ancestor in a Binary Search Tree."
},
{
"code": null,
"e": 10057,
"s": 10039,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 10100,
"s": 10057,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 10146,
"s": 10100,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 10169,
"s": 10146,
"text": "std::sort() in C++ STL"
}
] |
C++ Program to Check Whether Graph is DAG | A directed acyclic graph (DAG) is a graph that is directed and without cycles connecting the other edges. The edges of this graph go one way. This is a C++ program to check whether the graph is DAG.
Begin
Function checkDAG(int n):
intialize count = 0
intialize size = n - 1
for i = 0 to n-1
if (count == size)
return 1
done
if (arr[i].ptr == NULL)
increment count
for j = 0 to n-1
while (arr[j].ptr != NULL)
if ((arr[j].ptr)->d == (arr[i].ptr)->d)
(arr[j].ptr)->d = -1
done
arr[i].ptr = (arr[i].ptr)->next
done
done
done
done
return 0
End
Live Demo
#include<iostream>
using namespace std;
int c = 0;
struct ad_list { //A structure of type adj_list
int d;
ad_list *next;
}
*np = NULL, *np1 = NULL, *p = NULL, *q = NULL;
struct Gr { //A structure of type Gr
int v;
ad_list *ptr;
}
arr[6];
void addRevEdge(int s, int d) { //add reverse edges in the graph
np1 = new ad_list;
np1->d = s;
np1->next = NULL;
if (arr[d].ptr == NULL) {
arr[d].ptr = np1;
q = arr[d].ptr;
q->next = NULL;
} else {
q = arr[d].ptr;
while (q->next != NULL) {
q = q->next;
}
q->next = np1;
}
}
void addEdge(int s, int d) { // add edges in the graph
np = new ad_list;
np->d = d;
np->next = NULL;
if (arr[s].ptr == NULL) {
arr[s].ptr = np;
p = arr[s].ptr;
p->next = NULL;
} else {
p = arr[s].ptr;
while (p->next != NULL) {
p = p->next;
}
p->next = np;
}
}
void print_g(int n) {
for (int i = 0; i < n; i++) {
cout << "Adjacency List of " << arr[i].v << ": ";
while (arr[i].ptr != NULL) {
cout << (arr[i].ptr)->d<< " ";
arr[i].ptr = (arr[i].ptr)->next;
}
cout << endl;
}
}
int checkDAG(int n) {
int count = 0;
int size = n - 1;
for (int i = 0; i < n; i++) {
if (count == size) {
return 1;
}
if (arr[i].ptr == NULL) {
count++;
for (int j = 0; j < n; j++) {
while (arr[j].ptr != NULL) {
if ((arr[j].ptr)->d == (arr[i].ptr)->d) {
(arr[j].ptr)->d = -1;
}
arr[i].ptr = (arr[i].ptr)->next;
}
}
}
}
return 0;
}
int main() {
int v = 4;
cout << "Number of vertices: " << v << endl;
for (int i = 0; i < v; i++) {
arr[i].v = i;
arr[i].ptr = NULL;
}
addEdge(1, 0);
addEdge(3, 1);
addEdge(2, 1);
addEdge(0, 3);
addEdge(4, 1);
print_g(v);
cout << "The given graph is 'Directed Acyclic Graph' :";
if (checkDAG(v) == 1)
cout << " yes";
else
cout << " no";
}
Number of vertices: 4
Adjacency List of 0: 3
Adjacency List of 1: 0
Adjacency List of 2: 1
Adjacency List of 3: 1
The given graph is 'Directed Acyclic Graph' : yes | [
{
"code": null,
"e": 1261,
"s": 1062,
"text": "A directed acyclic graph (DAG) is a graph that is directed and without cycles connecting the other edges. The edges of this graph go one way. This is a C++ program to check whether the graph is DAG."
},
{
"code": null,
"e": 1760,
"s": 1261,
"text": "Begin\nFunction checkDAG(int n):\n intialize count = 0\n intialize size = n - 1\n for i = 0 to n-1\n if (count == size)\n return 1\n done\n if (arr[i].ptr == NULL)\n increment count\n for j = 0 to n-1\n while (arr[j].ptr != NULL)\n if ((arr[j].ptr)->d == (arr[i].ptr)->d)\n (arr[j].ptr)->d = -1\n done\n arr[i].ptr = (arr[i].ptr)->next\n done\n done\n done\n done\n return 0\nEnd"
},
{
"code": null,
"e": 1771,
"s": 1760,
"text": " Live Demo"
},
{
"code": null,
"e": 3851,
"s": 1771,
"text": "#include<iostream>\nusing namespace std;\nint c = 0;\nstruct ad_list { //A structure of type adj_list\n int d;\n ad_list *next;\n}\n*np = NULL, *np1 = NULL, *p = NULL, *q = NULL;\nstruct Gr { //A structure of type Gr\n int v;\n ad_list *ptr;\n}\narr[6];\nvoid addRevEdge(int s, int d) { //add reverse edges in the graph\n np1 = new ad_list;\n np1->d = s;\n np1->next = NULL;\n if (arr[d].ptr == NULL) {\n arr[d].ptr = np1;\n q = arr[d].ptr;\n q->next = NULL;\n } else {\n q = arr[d].ptr;\n while (q->next != NULL) {\n q = q->next;\n }\n q->next = np1;\n }\n}\nvoid addEdge(int s, int d) { // add edges in the graph\n np = new ad_list;\n np->d = d;\n np->next = NULL;\n if (arr[s].ptr == NULL) {\n arr[s].ptr = np;\n p = arr[s].ptr;\n p->next = NULL;\n } else {\n p = arr[s].ptr;\n while (p->next != NULL) {\n p = p->next;\n }\n p->next = np;\n }\n}\nvoid print_g(int n) {\n for (int i = 0; i < n; i++) {\n cout << \"Adjacency List of \" << arr[i].v << \": \";\n while (arr[i].ptr != NULL) {\n cout << (arr[i].ptr)->d<< \" \";\n arr[i].ptr = (arr[i].ptr)->next;\n }\n cout << endl;\n }\n}\nint checkDAG(int n) {\n int count = 0;\n int size = n - 1;\n for (int i = 0; i < n; i++) {\n if (count == size) {\n return 1;\n }\n if (arr[i].ptr == NULL) {\n count++;\n for (int j = 0; j < n; j++) {\n while (arr[j].ptr != NULL) {\n if ((arr[j].ptr)->d == (arr[i].ptr)->d) {\n (arr[j].ptr)->d = -1;\n }\n arr[i].ptr = (arr[i].ptr)->next;\n }\n }\n }\n }\n return 0;\n}\nint main() {\n int v = 4;\n cout << \"Number of vertices: \" << v << endl;\n for (int i = 0; i < v; i++) {\n arr[i].v = i;\n arr[i].ptr = NULL;\n }\n addEdge(1, 0);\n addEdge(3, 1);\n addEdge(2, 1);\n addEdge(0, 3);\n addEdge(4, 1);\n print_g(v);\n cout << \"The given graph is 'Directed Acyclic Graph' :\";\n if (checkDAG(v) == 1)\n cout << \" yes\";\n else\n cout << \" no\";\n}"
},
{
"code": null,
"e": 4015,
"s": 3851,
"text": "Number of vertices: 4\nAdjacency List of 0: 3\nAdjacency List of 1: 0\nAdjacency List of 2: 1\nAdjacency List of 3: 1\nThe given graph is 'Directed Acyclic Graph' : yes"
}
] |
Pythonic Big Data Using Julia?. Can Python handle large heaps of data... | by Emmett Boudreau | Towards Data Science | So recently, I have been experimenting with the idea of using Julia as a back-end for Python. While this is certainly a great concept in theory, some things do appear to have been lost in translation. This is a discussion that I have been having with several Julia and Python scientists, as the road to using Julia from Python is one that is at the moment traveled on very little. I also touched on this concept in another article, which you can read here:
towardsdatascience.com
In this article, I discussed the potential that Julia could have to replace C as a Python back-end. While to some extent, I do think that this is a weird idea — as Julia is not too difficult and is quite similar to Python in syntax, there would also be a significant advantage to this. The reason why I think using a compatibility layer from Python with Julia could be useful is that Python has far more mature web-frameworks that are far easier to deploy, and Python has far more high-level APIs that have been created for it. Being able to combine these powerful tools with the speed of Julia to handle more data and larger algorithms would be a dream come true.
As part of the tech-stack for Python and Julia symbiosis, we will need a package called TopLoader. TopLoader is a Pythonic interface for managing Julia virtual environments and packages. You can add TopLoader with Pip like so:
sudo pip3 install TopLoader
You can find TopLoader on Github here:
github.com
To set up TopLoader, you’ll first need to enter the Python REPL and import TopLoader. This will install and update PyCall, and set up the Julia executable to be ran from Python. Of course, you will also need Julia to be properly installed for this to work. There is a known issue with the Apt package manager’s installation of Julia where TopLoader will not be able to find Julia.
To resolve this,
DON’T INSTALL JULIA THROUGH APT!
Here is some Julian advice straight from the mouth of Julia Computing: Install the Julia binaries straight from Julia Computing, or http://julialang.org . Using a package manager version of Julia will create the following issues:
You will likely have an outdated version of Julia. For example, I am on Fedora and Dnf only has Julia up to version 1.2, whereas the current version is 1.4. Without the latest version of Julia, you will lose access to new features, such as parallel computing with @spawn, meaning you won’t be able to run a thread on anything but a multi-line for loop.
Your Julia executable could potentially end up in the wrong place. Your package manager places files on your system in a particular way, and having an executable link to /opt is certainly more optimal than having to predict where each package manager is going to put your Julia binaries, and then having to export them in Bash via ~/.bashrc or by running the command prior to starting Julia each time.
When you finally do get to a point where you can import TopLoader, make sure it is done specifically through the REPL. The setup involved with interpreting across Julia and Python cannot take place anywhere else.
(Notebook)
lathe.ai
Lathe uses Julia’s syntactical expressions to emulate classes in a typical duck-typed language like Python and C++. This is great because it means that models get an initialization prior to being ran through a prediction method. This means that we can fit a model like so:
model = LogisticRegression(trainX, trainy)
And this expression will go ahead and calculate any values that are needed for the LogisticRegression model to predict. Then we can call the predict method, which is a child of our new model object, to get our ŷ.
ŷ = model.predict(testX)
To demonstrate using Lathe from Python, we will first have to create an environment with TopLoader, and then add Lathe to it:
This environment already exists, and already has Lathe in it. However, we will need to instead install the Unstable branch of Lathe so that we can modify and test it. While we can do this from Python, I would also like to demonstrate how we could do this from the Julia REPL, which in my opinion is a lot easier and makes a lot more sense. All we need to do is enter the Julia REPL in our current directory:
And then enter the Pkg REPL with ] and activate our environment with the activate command:
Now we can add or remove any packages we desire.
Now if we reload our environment in TopLoader and use the List() function, we get the new updated version of Lathe.
We can import Lathe into Python using the Using() method from our environment:
Whenever we create a model type, everything works exactly as expected.
And just as well, so does the predict() method:
In order to determine if we are actually getting a performance gain from using Julia as apposed to Python, we’ll need a baseline. To do this, I carried over the same Linear Regression function translated into Python. This is a rather basic machine-learning model, so fortunately Python will be able to complete a lot of our tests on its own.
def dot(x,y): lst = [] for i,w in zip(x,y): lst.append(i * w) return(lst)def sq(x): x = [c ** 2 for c in x] return(x)class LinearRegression: def __init__(self,x,y): # a = ((∑y)(∑x^2)-(∑x)(∑xy)) / (n(∑x^2) - (∑x)^2) # b = (x(∑xy) - (∑x)(∑y)) / n(∑x^2) - (∑x)^2 if len(x) != len(y): pass # Get our Summations: Σx = sum(x) Σy = sum(y) # dot x and y xy = dot(x,y) # ∑dot x and y Σxy = sum(xy) # dotsquare x x2 = sq(x) # ∑ dotsquare x Σx2 = sum(x2) # n = sample size n = len(x) # Calculate a self.a = (((Σy) * (Σx2)) - ((Σx * (Σxy)))) / ((n * (Σx2))-(Σx**2)) # Calculate b self.b = ((n*(Σxy)) - (Σx * Σy)) / ((n * (Σx2)) - (Σx ** 2)) # The part that is super struct: def predict(self,xt): xt = [self.a + (self.b * i) for i in xt] return(xt)
I also imported Pandas and read in two CSV files I have on my machine that I use for speed tests. The data-set has 10,000,000 observations in it, which might still be apt to perform, but will almost certainly give Python a great workout. To time these calculations, I will be using the IPython magic command timeit.
%timeit LinearRegression(df["X"],df["Y"]).predict(testdf["X"])
Our result came out to 8.78 seconds.
Compare this with Julia’s speed on this exact calculation, where the result came out to 0.362333 seconds
But what about using TopLoader from Python? Could we expect performance similar to Julia, Python, or somewhere in between? The performance could also take a significant hit due to the translation layer in a worst-case-scenario. Unfortunately, that seems to be precisely what happened with TopLoader coming in with a solid 1 minute and 10 seconds.
Awful!
I’m going to have to accept the null hypothesis on this one.
The short answer is no, I was correct in my estimation that the layers of compatibility caused too much slowdown. However, I think that this observation could insight the reality that with a better system, Julia from Python could be fantastic. The problem with TopLoader is that it needs to translate Pythonic data into Julian data, and then translate that data back into Julian data. Perhaps if there was a way to run a Julia instance in the background that could receive large heaps of data from Python more efficiently, there might be a way to get this working.
With the need for a better system clearly illustrated, perhaps I will start a new project to achieve just that. In the meantime, however, Julia is certainly of no assistance to Python in terms of handling data, and using compatibility layers seems to be slower than using Python itself. While the future of this concept might be bold, and could even mean faster Python packages with less effort, the future certainly isn’t now.
Regardless of TopLoader’s failings in this aspect, I still think it is a pretty cool package. Bridging Julia virtual environments with Python is certainly a cool idea, and I can only hope that eventually a way can be determined to bring the full capabilities of this concept into fruition. | [
{
"code": null,
"e": 629,
"s": 172,
"text": "So recently, I have been experimenting with the idea of using Julia as a back-end for Python. While this is certainly a great concept in theory, some things do appear to have been lost in translation. This is a discussion that I have been having with several Julia and Python scientists, as the road to using Julia from Python is one that is at the moment traveled on very little. I also touched on this concept in another article, which you can read here:"
},
{
"code": null,
"e": 652,
"s": 629,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1317,
"s": 652,
"text": "In this article, I discussed the potential that Julia could have to replace C as a Python back-end. While to some extent, I do think that this is a weird idea — as Julia is not too difficult and is quite similar to Python in syntax, there would also be a significant advantage to this. The reason why I think using a compatibility layer from Python with Julia could be useful is that Python has far more mature web-frameworks that are far easier to deploy, and Python has far more high-level APIs that have been created for it. Being able to combine these powerful tools with the speed of Julia to handle more data and larger algorithms would be a dream come true."
},
{
"code": null,
"e": 1544,
"s": 1317,
"text": "As part of the tech-stack for Python and Julia symbiosis, we will need a package called TopLoader. TopLoader is a Pythonic interface for managing Julia virtual environments and packages. You can add TopLoader with Pip like so:"
},
{
"code": null,
"e": 1572,
"s": 1544,
"text": "sudo pip3 install TopLoader"
},
{
"code": null,
"e": 1611,
"s": 1572,
"text": "You can find TopLoader on Github here:"
},
{
"code": null,
"e": 1622,
"s": 1611,
"text": "github.com"
},
{
"code": null,
"e": 2003,
"s": 1622,
"text": "To set up TopLoader, you’ll first need to enter the Python REPL and import TopLoader. This will install and update PyCall, and set up the Julia executable to be ran from Python. Of course, you will also need Julia to be properly installed for this to work. There is a known issue with the Apt package manager’s installation of Julia where TopLoader will not be able to find Julia."
},
{
"code": null,
"e": 2020,
"s": 2003,
"text": "To resolve this,"
},
{
"code": null,
"e": 2053,
"s": 2020,
"text": "DON’T INSTALL JULIA THROUGH APT!"
},
{
"code": null,
"e": 2283,
"s": 2053,
"text": "Here is some Julian advice straight from the mouth of Julia Computing: Install the Julia binaries straight from Julia Computing, or http://julialang.org . Using a package manager version of Julia will create the following issues:"
},
{
"code": null,
"e": 2636,
"s": 2283,
"text": "You will likely have an outdated version of Julia. For example, I am on Fedora and Dnf only has Julia up to version 1.2, whereas the current version is 1.4. Without the latest version of Julia, you will lose access to new features, such as parallel computing with @spawn, meaning you won’t be able to run a thread on anything but a multi-line for loop."
},
{
"code": null,
"e": 3038,
"s": 2636,
"text": "Your Julia executable could potentially end up in the wrong place. Your package manager places files on your system in a particular way, and having an executable link to /opt is certainly more optimal than having to predict where each package manager is going to put your Julia binaries, and then having to export them in Bash via ~/.bashrc or by running the command prior to starting Julia each time."
},
{
"code": null,
"e": 3251,
"s": 3038,
"text": "When you finally do get to a point where you can import TopLoader, make sure it is done specifically through the REPL. The setup involved with interpreting across Julia and Python cannot take place anywhere else."
},
{
"code": null,
"e": 3262,
"s": 3251,
"text": "(Notebook)"
},
{
"code": null,
"e": 3271,
"s": 3262,
"text": "lathe.ai"
},
{
"code": null,
"e": 3544,
"s": 3271,
"text": "Lathe uses Julia’s syntactical expressions to emulate classes in a typical duck-typed language like Python and C++. This is great because it means that models get an initialization prior to being ran through a prediction method. This means that we can fit a model like so:"
},
{
"code": null,
"e": 3587,
"s": 3544,
"text": "model = LogisticRegression(trainX, trainy)"
},
{
"code": null,
"e": 3801,
"s": 3587,
"text": "And this expression will go ahead and calculate any values that are needed for the LogisticRegression model to predict. Then we can call the predict method, which is a child of our new model object, to get our ŷ."
},
{
"code": null,
"e": 3827,
"s": 3801,
"text": "ŷ = model.predict(testX)"
},
{
"code": null,
"e": 3953,
"s": 3827,
"text": "To demonstrate using Lathe from Python, we will first have to create an environment with TopLoader, and then add Lathe to it:"
},
{
"code": null,
"e": 4361,
"s": 3953,
"text": "This environment already exists, and already has Lathe in it. However, we will need to instead install the Unstable branch of Lathe so that we can modify and test it. While we can do this from Python, I would also like to demonstrate how we could do this from the Julia REPL, which in my opinion is a lot easier and makes a lot more sense. All we need to do is enter the Julia REPL in our current directory:"
},
{
"code": null,
"e": 4452,
"s": 4361,
"text": "And then enter the Pkg REPL with ] and activate our environment with the activate command:"
},
{
"code": null,
"e": 4501,
"s": 4452,
"text": "Now we can add or remove any packages we desire."
},
{
"code": null,
"e": 4617,
"s": 4501,
"text": "Now if we reload our environment in TopLoader and use the List() function, we get the new updated version of Lathe."
},
{
"code": null,
"e": 4696,
"s": 4617,
"text": "We can import Lathe into Python using the Using() method from our environment:"
},
{
"code": null,
"e": 4767,
"s": 4696,
"text": "Whenever we create a model type, everything works exactly as expected."
},
{
"code": null,
"e": 4815,
"s": 4767,
"text": "And just as well, so does the predict() method:"
},
{
"code": null,
"e": 5157,
"s": 4815,
"text": "In order to determine if we are actually getting a performance gain from using Julia as apposed to Python, we’ll need a baseline. To do this, I carried over the same Linear Regression function translated into Python. This is a rather basic machine-learning model, so fortunately Python will be able to complete a lot of our tests on its own."
},
{
"code": null,
"e": 6093,
"s": 5157,
"text": "def dot(x,y): lst = [] for i,w in zip(x,y): lst.append(i * w) return(lst)def sq(x): x = [c ** 2 for c in x] return(x)class LinearRegression: def __init__(self,x,y): # a = ((∑y)(∑x^2)-(∑x)(∑xy)) / (n(∑x^2) - (∑x)^2) # b = (x(∑xy) - (∑x)(∑y)) / n(∑x^2) - (∑x)^2 if len(x) != len(y): pass # Get our Summations: Σx = sum(x) Σy = sum(y) # dot x and y xy = dot(x,y) # ∑dot x and y Σxy = sum(xy) # dotsquare x x2 = sq(x) # ∑ dotsquare x Σx2 = sum(x2) # n = sample size n = len(x) # Calculate a self.a = (((Σy) * (Σx2)) - ((Σx * (Σxy)))) / ((n * (Σx2))-(Σx**2)) # Calculate b self.b = ((n*(Σxy)) - (Σx * Σy)) / ((n * (Σx2)) - (Σx ** 2)) # The part that is super struct: def predict(self,xt): xt = [self.a + (self.b * i) for i in xt] return(xt)"
},
{
"code": null,
"e": 6409,
"s": 6093,
"text": "I also imported Pandas and read in two CSV files I have on my machine that I use for speed tests. The data-set has 10,000,000 observations in it, which might still be apt to perform, but will almost certainly give Python a great workout. To time these calculations, I will be using the IPython magic command timeit."
},
{
"code": null,
"e": 6472,
"s": 6409,
"text": "%timeit LinearRegression(df[\"X\"],df[\"Y\"]).predict(testdf[\"X\"])"
},
{
"code": null,
"e": 6509,
"s": 6472,
"text": "Our result came out to 8.78 seconds."
},
{
"code": null,
"e": 6614,
"s": 6509,
"text": "Compare this with Julia’s speed on this exact calculation, where the result came out to 0.362333 seconds"
},
{
"code": null,
"e": 6961,
"s": 6614,
"text": "But what about using TopLoader from Python? Could we expect performance similar to Julia, Python, or somewhere in between? The performance could also take a significant hit due to the translation layer in a worst-case-scenario. Unfortunately, that seems to be precisely what happened with TopLoader coming in with a solid 1 minute and 10 seconds."
},
{
"code": null,
"e": 6968,
"s": 6961,
"text": "Awful!"
},
{
"code": null,
"e": 7029,
"s": 6968,
"text": "I’m going to have to accept the null hypothesis on this one."
},
{
"code": null,
"e": 7594,
"s": 7029,
"text": "The short answer is no, I was correct in my estimation that the layers of compatibility caused too much slowdown. However, I think that this observation could insight the reality that with a better system, Julia from Python could be fantastic. The problem with TopLoader is that it needs to translate Pythonic data into Julian data, and then translate that data back into Julian data. Perhaps if there was a way to run a Julia instance in the background that could receive large heaps of data from Python more efficiently, there might be a way to get this working."
},
{
"code": null,
"e": 8022,
"s": 7594,
"text": "With the need for a better system clearly illustrated, perhaps I will start a new project to achieve just that. In the meantime, however, Julia is certainly of no assistance to Python in terms of handling data, and using compatibility layers seems to be slower than using Python itself. While the future of this concept might be bold, and could even mean faster Python packages with less effort, the future certainly isn’t now."
}
] |
JSON with Ruby | This chapter covers how to encode and decode JSON objects using Ruby programming language. Let's start with preparing the environment to start our programming with Ruby for JSON.
Before you start with encoding and decoding JSON using Ruby, you need to install any of the JSON modules available for Ruby. You may need to install Ruby gem, but if you are running latest version of Ruby then you must have gem already installed on your machine, otherwise let's follow the following single step assuming you already have gem installed −
$gem install json
The following example shows that the first 2 keys hold string values and the last 3 keys hold arrays of strings. Let's keep the following content in a file called input.json.
{
"President": "Alan Isaac",
"CEO": "David Richardson",
"India": [
"Sachin Tendulkar",
"Virender Sehwag",
"Gautam Gambhir"
],
"Srilanka": [
"Lasith Malinga",
"Angelo Mathews",
"Kumar Sangakkara"
],
"England": [
"Alastair Cook",
"Jonathan Trott",
"Kevin Pietersen"
]
}
Given below is a Ruby program that will be used to parse the above mentioned JSON document −
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
json = File.read('input.json')
obj = JSON.parse(json)
pp obj
On executing, it will produce the following result −
{
"President"=>"Alan Isaac",
"CEO"=>"David Richardson",
"India"=>
["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"],
"Srilanka"=>
["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"],
"England"=>
["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]
}
20 Lectures
1 hours
Laurence Svekis
16 Lectures
1 hours
Laurence Svekis
10 Lectures
1 hours
Laurence Svekis
23 Lectures
2.5 hours
Laurence Svekis
9 Lectures
48 mins
Nilay Mehta
18 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1959,
"s": 1780,
"text": "This chapter covers how to encode and decode JSON objects using Ruby programming language. Let's start with preparing the environment to start our programming with Ruby for JSON."
},
{
"code": null,
"e": 2313,
"s": 1959,
"text": "Before you start with encoding and decoding JSON using Ruby, you need to install any of the JSON modules available for Ruby. You may need to install Ruby gem, but if you are running latest version of Ruby then you must have gem already installed on your machine, otherwise let's follow the following single step assuming you already have gem installed −"
},
{
"code": null,
"e": 2332,
"s": 2313,
"text": "$gem install json\n"
},
{
"code": null,
"e": 2507,
"s": 2332,
"text": "The following example shows that the first 2 keys hold string values and the last 3 keys hold arrays of strings. Let's keep the following content in a file called input.json."
},
{
"code": null,
"e": 2860,
"s": 2507,
"text": "{\n \"President\": \"Alan Isaac\",\n \"CEO\": \"David Richardson\",\n \n \"India\": [\n \"Sachin Tendulkar\",\n \"Virender Sehwag\",\n \"Gautam Gambhir\"\n ],\n\n \"Srilanka\": [\n \"Lasith Malinga\",\n \"Angelo Mathews\",\n \"Kumar Sangakkara\"\n ],\n\n \"England\": [\n \"Alastair Cook\",\n \"Jonathan Trott\",\n \"Kevin Pietersen\"\n ]\n\t\n}"
},
{
"code": null,
"e": 2953,
"s": 2860,
"text": "Given below is a Ruby program that will be used to parse the above mentioned JSON document −"
},
{
"code": null,
"e": 3079,
"s": 2953,
"text": "#!/usr/bin/ruby\nrequire 'rubygems'\nrequire 'json'\nrequire 'pp'\n\njson = File.read('input.json')\nobj = JSON.parse(json)\n\npp obj"
},
{
"code": null,
"e": 3132,
"s": 3079,
"text": "On executing, it will produce the following result −"
},
{
"code": null,
"e": 3426,
"s": 3132,
"text": "{\n \"President\"=>\"Alan Isaac\",\n \"CEO\"=>\"David Richardson\",\n\n \"India\"=>\n [\"Sachin Tendulkar\", \"Virender Sehwag\", \"Gautam Gambhir\"],\n\n \"Srilanka\"=>\n [\"Lasith Malinga \", \"Angelo Mathews\", \"Kumar Sangakkara\"],\n\n \"England\"=>\n [\"Alastair Cook\", \"Jonathan Trott\", \"Kevin Pietersen\"]\n}\n"
},
{
"code": null,
"e": 3459,
"s": 3426,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3476,
"s": 3459,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 3509,
"s": 3476,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3526,
"s": 3509,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 3559,
"s": 3526,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3576,
"s": 3559,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 3611,
"s": 3576,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3628,
"s": 3611,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 3659,
"s": 3628,
"text": "\n 9 Lectures \n 48 mins\n"
},
{
"code": null,
"e": 3672,
"s": 3659,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 3707,
"s": 3672,
"text": "\n 18 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3730,
"s": 3707,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3737,
"s": 3730,
"text": " Print"
},
{
"code": null,
"e": 3748,
"s": 3737,
"text": " Add Notes"
}
] |
D3.js zoom.scaleTo() Function - GeeksforGeeks | 31 Aug, 2020
The zoom.scaleTo() function in D3.js is used to scale the current zoon transform of the selected elements to k.
Syntax:
zoom.scaleTo(selection, k[, p])
Parameters: This function accept two parameter as mentioned above and described below
selection: This parameter can be selection or transition.
k: This parameter is a scale factor, specified either as numbers or as functions
Return Value: This function returns the zoom behavior.
Below programs illustrate the zoom.scaleTo() function in D3.js
Example 1:
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> circle { opacity: 0.7; } g.zoom-controls { cursor: pointer; pointer-events: all; } g.zoom-controls rect { fill: white; stroke: #596877; stroke-width: 1; } g.zoom-controls line { stroke: #596877; stroke-width: 2; } </style> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleTo() Function</h3> <svg> <g class="zoom-controls" transform="translate(10, 10)"> <g id="zoom-in" transform="translate(0, 0)"> <rect width="30" height="30"></rect> <line x1="5" y1="15" x2="25" y2="15"></line> <line x1="15" y1="5" x2="15" y2="25"></line> </g> <g id="zoom-out" transform="translate(30, 0)"> <rect width="30" height="30"></rect> <line x1="5" y1="15" x2="25" y2="15"></line> </g> </g> </svg> <script> var radius = 10; var svg = d3.select('svg'); var dimension = document.body.getBoundingClientRect(); var data = d3.range(0, 25).map(function() { return { x: getRandom(radius, dimension.width - radius), y: getRandom(radius, dimension.height - radius) } }); var zoom = d3.zoom() .on('zoom', function() { canvas.attr('transform', d3.event.transform); }) var canvas = svg .attr('width', dimension.width) .attr('height', dimension.height) .call(zoom) .insert('g', ':first-child'); canvas.selectAll('circle') .data(data) .enter() .append('circle') .attr('r', radius) .attr('cx', function(d) { return d.x; }).attr('cy', function(d) { return d.y; }).style('fill', function() { return d3.schemeCategory10[getRandom(0, 9)] }); d3.select('#zoom-in').on('click', function() { // Smooth zooming zoom.scaleTo(svg.transition().duration(750), 1.3); }); d3.select('#zoom-out').on('click', function() { // Ordinal zooming zoom.scaleTo(svg, 1 / 1.3); }); function getRandom(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } </script> </center></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.js"> </script> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleTo() Function</h3> <svg height="100px" width="100px"></svg> <script> const zoom_action = () => g.attr("transform", d3.event.transform) // Create the zoom handler const zoom = d3 .zoom() .on("zoom", zoom_action) // Get SVG element and apply zoom behaviour var svg = d3 .select("svg") .call(zoom) // Create Group that will be zoomed var g = svg.append("g") // Create circle g.append("circle") .attr("cx",0) .attr("cy",0) .attr("r", 5) .style("fill","green") // Use of zoom.scaleTo Function zoom.scaleTo(svg, 5) zoom.translateBy(svg, 50, 50) </script> </center></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 25412,
"s": 25300,
"text": "The zoom.scaleTo() function in D3.js is used to scale the current zoon transform of the selected elements to k."
},
{
"code": null,
"e": 25420,
"s": 25412,
"text": "Syntax:"
},
{
"code": null,
"e": 25452,
"s": 25420,
"text": "zoom.scaleTo(selection, k[, p])"
},
{
"code": null,
"e": 25538,
"s": 25452,
"text": "Parameters: This function accept two parameter as mentioned above and described below"
},
{
"code": null,
"e": 25596,
"s": 25538,
"text": "selection: This parameter can be selection or transition."
},
{
"code": null,
"e": 25677,
"s": 25596,
"text": "k: This parameter is a scale factor, specified either as numbers or as functions"
},
{
"code": null,
"e": 25732,
"s": 25677,
"text": "Return Value: This function returns the zoom behavior."
},
{
"code": null,
"e": 25795,
"s": 25732,
"text": "Below programs illustrate the zoom.scaleTo() function in D3.js"
},
{
"code": null,
"e": 25806,
"s": 25795,
"text": "Example 1:"
},
{
"code": null,
"e": 25811,
"s": 25806,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> circle { opacity: 0.7; } g.zoom-controls { cursor: pointer; pointer-events: all; } g.zoom-controls rect { fill: white; stroke: #596877; stroke-width: 1; } g.zoom-controls line { stroke: #596877; stroke-width: 2; } </style> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleTo() Function</h3> <svg> <g class=\"zoom-controls\" transform=\"translate(10, 10)\"> <g id=\"zoom-in\" transform=\"translate(0, 0)\"> <rect width=\"30\" height=\"30\"></rect> <line x1=\"5\" y1=\"15\" x2=\"25\" y2=\"15\"></line> <line x1=\"15\" y1=\"5\" x2=\"15\" y2=\"25\"></line> </g> <g id=\"zoom-out\" transform=\"translate(30, 0)\"> <rect width=\"30\" height=\"30\"></rect> <line x1=\"5\" y1=\"15\" x2=\"25\" y2=\"15\"></line> </g> </g> </svg> <script> var radius = 10; var svg = d3.select('svg'); var dimension = document.body.getBoundingClientRect(); var data = d3.range(0, 25).map(function() { return { x: getRandom(radius, dimension.width - radius), y: getRandom(radius, dimension.height - radius) } }); var zoom = d3.zoom() .on('zoom', function() { canvas.attr('transform', d3.event.transform); }) var canvas = svg .attr('width', dimension.width) .attr('height', dimension.height) .call(zoom) .insert('g', ':first-child'); canvas.selectAll('circle') .data(data) .enter() .append('circle') .attr('r', radius) .attr('cx', function(d) { return d.x; }).attr('cy', function(d) { return d.y; }).style('fill', function() { return d3.schemeCategory10[getRandom(0, 9)] }); d3.select('#zoom-in').on('click', function() { // Smooth zooming zoom.scaleTo(svg.transition().duration(750), 1.3); }); d3.select('#zoom-out').on('click', function() { // Ordinal zooming zoom.scaleTo(svg, 1 / 1.3); }); function getRandom(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } </script> </center></body> </html> ",
"e": 28840,
"s": 25811,
"text": null
},
{
"code": null,
"e": 28848,
"s": 28840,
"text": "Output:"
},
{
"code": null,
"e": 28859,
"s": 28848,
"text": "Example 2:"
},
{
"code": null,
"e": 28864,
"s": 28859,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v5.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | zoom.scaleTo() Function</h3> <svg height=\"100px\" width=\"100px\"></svg> <script> const zoom_action = () => g.attr(\"transform\", d3.event.transform) // Create the zoom handler const zoom = d3 .zoom() .on(\"zoom\", zoom_action) // Get SVG element and apply zoom behaviour var svg = d3 .select(\"svg\") .call(zoom) // Create Group that will be zoomed var g = svg.append(\"g\") // Create circle g.append(\"circle\") .attr(\"cx\",0) .attr(\"cy\",0) .attr(\"r\", 5) .style(\"fill\",\"green\") // Use of zoom.scaleTo Function zoom.scaleTo(svg, 5) zoom.translateBy(svg, 50, 50) </script> </center></body> </html> ",
"e": 29966,
"s": 28864,
"text": null
},
{
"code": null,
"e": 29974,
"s": 29966,
"text": "Output:"
},
{
"code": null,
"e": 29980,
"s": 29974,
"text": "D3.js"
},
{
"code": null,
"e": 29991,
"s": 29980,
"text": "JavaScript"
},
{
"code": null,
"e": 30008,
"s": 29991,
"text": "Web Technologies"
},
{
"code": null,
"e": 30106,
"s": 30008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30167,
"s": 30106,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30207,
"s": 30167,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30248,
"s": 30207,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30302,
"s": 30248,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30350,
"s": 30302,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 30392,
"s": 30350,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30454,
"s": 30392,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30497,
"s": 30454,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30530,
"s": 30497,
"text": "Installation of Node.js on Linux"
}
] |
How to convert the Integer variable to the string variable in PowerShell? | To convert the integer variable to the string variable, you need to use the explicit conversion or the functional method. In the below example, we are assigning an integer value to the variable $X.
$x = 120
$x.GetType().Name
Now when you check the data type of that variable, it will be Int32.
To convert it into the string variable, first, we will use the explicit method by using a square bracket and data type to convert inside the brackets.
[string]$x = 130
$x.GetType().Name
The data type of $x is the String.
In the second method, you can use the PowerShell functional method ToString() to convert. For example,
$x = $x.ToString()
$x.GetType().Name
In the same way, you can convert string value to the integer value but in its defined range. For example,
$x = "123"
[int]$x = $x
$x.GetType().Name
Here, we are declaring “123” as the string variable and to convert it we will use [int] data type ahead of $x so it will be converted to an integer variable. But when you convert a character string into an integer, you will get an error.
For example,
$x = "abc"
[int]$x = $x
Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ [int]$x = $x
+ ~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId :RuntimeException | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "To convert the integer variable to the string variable, you need to use the explicit conversion or the functional method. In the below example, we are assigning an integer value to the variable $X."
},
{
"code": null,
"e": 1287,
"s": 1260,
"text": "$x = 120\n$x.GetType().Name"
},
{
"code": null,
"e": 1356,
"s": 1287,
"text": "Now when you check the data type of that variable, it will be Int32."
},
{
"code": null,
"e": 1507,
"s": 1356,
"text": "To convert it into the string variable, first, we will use the explicit method by using a square bracket and data type to convert inside the brackets."
},
{
"code": null,
"e": 1542,
"s": 1507,
"text": "[string]$x = 130\n$x.GetType().Name"
},
{
"code": null,
"e": 1577,
"s": 1542,
"text": "The data type of $x is the String."
},
{
"code": null,
"e": 1680,
"s": 1577,
"text": "In the second method, you can use the PowerShell functional method ToString() to convert. For example,"
},
{
"code": null,
"e": 1717,
"s": 1680,
"text": "$x = $x.ToString()\n$x.GetType().Name"
},
{
"code": null,
"e": 1823,
"s": 1717,
"text": "In the same way, you can convert string value to the integer value but in its defined range. For example,"
},
{
"code": null,
"e": 1865,
"s": 1823,
"text": "$x = \"123\"\n[int]$x = $x\n$x.GetType().Name"
},
{
"code": null,
"e": 2103,
"s": 1865,
"text": "Here, we are declaring “123” as the string variable and to convert it we will use [int] data type ahead of $x so it will be converted to an integer variable. But when you convert a character string into an integer, you will get an error."
},
{
"code": null,
"e": 2116,
"s": 2103,
"text": "For example,"
},
{
"code": null,
"e": 2140,
"s": 2116,
"text": "$x = \"abc\"\n[int]$x = $x"
},
{
"code": null,
"e": 2411,
"s": 2140,
"text": "Cannot convert value \"abc\" to type \"System.Int32\". Error: \"Input string was not in a correct format.\"\nAt line:1 char:1\n+ [int]$x = $x\n+ ~~~~~~~~~~~~\n+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId :RuntimeException"
}
] |
How to concatenate all values of a single column in MySQL? | You can use group_concat() along with concat() to concatenate all values of a single column. Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20)
);
Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John |
| 2 | Larry |
| 3 | Chris |
| 4 | Robert |
| 5 | David |
+----+-----------+
5 rows in set (0.00 sec)
Following is the query to concatenate all values of a single column in MySQL.
mysql> select group_concat(concat('"', FirstName, '"')) AS FirstName from DemoTable;
This will produce the following output −
+-----------------------------------------+
| FirstName |
+-----------------------------------------+
| "John","Larry","Chris","Robert","David" |
+-----------------------------------------+
1 row in set (0.05 sec) | [
{
"code": null,
"e": 1185,
"s": 1062,
"text": "You can use group_concat() along with concat() to concatenate all values of a single column. Let us first create a table −"
},
{
"code": null,
"e": 1332,
"s": 1185,
"text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20)\n );\nQuery OK, 0 rows affected (0.73 sec)"
},
{
"code": null,
"e": 1388,
"s": 1332,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1857,
"s": 1388,
"text": "mysql> insert into DemoTable(FirstName) values('John');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DemoTable(FirstName) values('Larry');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(FirstName) values('Chris');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(FirstName) values('Robert');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable(FirstName) values('David');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1917,
"s": 1857,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1948,
"s": 1917,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1989,
"s": 1948,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2185,
"s": 1989,
"text": "+----+-----------+\n| Id | FirstName |\n+----+-----------+\n| 1 | John |\n| 2 | Larry |\n| 3 | Chris |\n| 4 | Robert |\n| 5 | David |\n+----+-----------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2263,
"s": 2185,
"text": "Following is the query to concatenate all values of a single column in MySQL."
},
{
"code": null,
"e": 2348,
"s": 2263,
"text": "mysql> select group_concat(concat('\"', FirstName, '\"')) AS FirstName from DemoTable;"
},
{
"code": null,
"e": 2389,
"s": 2348,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2633,
"s": 2389,
"text": "+-----------------------------------------+\n| FirstName |\n+-----------------------------------------+\n| \"John\",\"Larry\",\"Chris\",\"Robert\",\"David\" |\n+-----------------------------------------+\n1 row in set (0.05 sec)"
}
] |
LeafletJS - Layers Group | Using layer group, you can add multiple layers to a map and manage them as a single layer.
Follow the steps given below to create a LayerGroup and add it to the map.
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create elements (layers) such as markers, polygons, circles, etc., that are needed, by instantiating the respective classes as shown below.
// Creating markers
var hydMarker = new L.Marker([17.385044, 78.486671]);
var vskpMarker = new L.Marker([17.686816, 83.218482]);
var vjwdMarker = new L.Marker([16.506174, 80.648015]);
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.686816, 83.218482]
];
// Creating a polygon
var polygon = L.polygon(latlngs, {color: 'red'});
Step 5 − Create the Layer Group using l.layerGroup(). Pass the above created markers, polygons, etc., as shown below.
// Creating layer group
var layerGroup = L.layerGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);
Step 6 − Add the layer group created in the previous step using the addTo() method.
// Adding layer group to map
layerGroup.addTo(map);
The following code creates a layer group which holds 3 markers and a polygon, and adds it to the map.
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Layer Group</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width: 900px; height: 580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 7
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
// Creating markers
var hydMarker = new L.Marker([17.385044, 78.486671]);
var vskpMarker = new L.Marker([17.686816, 83.218482]);
var vjwdMarker = new L.Marker([16.506174, 80.648015]);
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.686816, 83.218482]
];
// Creating a polygon
var polygon = L.polygon(latlngs, {color: 'red'});
// Creating layer group
var layerGroup = L.layerGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);
layerGroup.addTo(map); // Adding layer group to map
</script>
</body>
</html>
It generates the following output −
You can add a layer to the feature group using the addLayer() method. To this method, you need to pass the element that is to be added.
You can add a circle with the city Hyderabad at the center.
// Creating a circle
var circle = L.circle([16.506174, 80.648015], 50000, {color: 'red', fillColor:
'#f03', fillOpacity: 0} );
// Adding circle to the layer group
layerGroup.addLayer(circle);
It will produce the following output. −
You can remove a layer from the feature group using the removeLayer() method. To this method, you need to pass the element that is to be removed.
You can remove the marker on the city named Vijayawada as shown below.
// Removing layer from map
layerGroup.removeLayer(vjwdMarker);
It will produce the following output −
It is similar to LayerGroup but it allows mouse events and bind popups to it. You can also set style to the entire group using setStyle() method.
Follow the steps given below to create a Feature Group and add it to the map.
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create elements (layers) such as markers, polygons, and circles that are needed, by instantiating the respective classes as shown below.
// Creating markers
var hydMarker = new L.Marker([17.385044, 78.486671]);
var vskpMarker = new L.Marker([17.686816, 83.218482]);
var vjwdMarker = new L.Marker([16.506174, 80.648015]);
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.686816, 83.218482]
];
// Creating a polygon
var polygon = L.polygon(latlngs, {color: 'red'});>
Step 5 − Create Feature Group using l.featureGroup(). Pass the above-created markers, polygons, etc., as shown below.
// Creating feature group
var featureGroup = L.featureGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);
Step 6 − If you set style to the feature group, it will be applied to each element (layer) in the group. You can do so using the setStyle() method and to this method, you need to pass values to the options such as color and opacity etc.
Set the style to the feature group created in the above step.
// Setting style to the feature group
featureGroup.setStyle({color:'blue',opacity:.5});
Step 7 − Bind the popup using the bindPopup() method, as shown below.
// Binding popup to the feature group
featureGroup.bindPopup("Feature Group");
Step 8 − Add the feature group created in the previous step using the addTo() method.
// Adding layer group to map
featureGroup.addTo(map);
The following code creates a feature group which holds 3 markers and a polygon, and adds it to the map.
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Feature Group</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 7
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
// Creating markers
var hydMarker = new L.Marker([17.385044, 78.486671]);
var vskpMarker = new L.Marker([17.686816, 83.218482]);
var vjwdMarker = new L.Marker([16.506174, 80.648015]);
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.686816, 83.218482]
];
var polygon = L.polygon(latlngs, {color: 'red'}); // Creating a polygon
// Creating feature group
var featureGroup = L.featureGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);
featureGroup.setStyle({color:'blue',opacity:.5});
featureGroup.bindPopup("Feature Group");
featureGroup.addTo(map); // Adding layer group to map
</script>
</body>
</html>
It generates the following output −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1889,
"s": 1798,
"text": "Using layer group, you can add multiple layers to a map and manage them as a single layer."
},
{
"code": null,
"e": 1964,
"s": 1889,
"text": "Follow the steps given below to create a LayerGroup and add it to the map."
},
{
"code": null,
"e": 2067,
"s": 1964,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 2138,
"s": 2067,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 2225,
"s": 2138,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 2374,
"s": 2225,
"text": "Step 4 − Create elements (layers) such as markers, polygons, circles, etc., that are needed, by instantiating the respective classes as shown below."
},
{
"code": null,
"e": 2757,
"s": 2374,
"text": "// Creating markers\nvar hydMarker = new L.Marker([17.385044, 78.486671]);\nvar vskpMarker = new L.Marker([17.686816, 83.218482]);\nvar vjwdMarker = new L.Marker([16.506174, 80.648015]);\n\n// Creating latlng object\nvar latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.686816, 83.218482]\n];\n// Creating a polygon\nvar polygon = L.polygon(latlngs, {color: 'red'});\n"
},
{
"code": null,
"e": 2875,
"s": 2757,
"text": "Step 5 − Create the Layer Group using l.layerGroup(). Pass the above created markers, polygons, etc., as shown below."
},
{
"code": null,
"e": 2977,
"s": 2875,
"text": "// Creating layer group\nvar layerGroup = L.layerGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);\n"
},
{
"code": null,
"e": 3061,
"s": 2977,
"text": "Step 6 − Add the layer group created in the previous step using the addTo() method."
},
{
"code": null,
"e": 3114,
"s": 3061,
"text": "// Adding layer group to map\nlayerGroup.addTo(map);\n"
},
{
"code": null,
"e": 3216,
"s": 3114,
"text": "The following code creates a layer group which holds 3 markers and a polygon, and adds it to the map."
},
{
"code": null,
"e": 4722,
"s": 3216,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Leaflet Layer Group</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width: 900px; height: 580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [17.385044, 78.486671],\n zoom: 7\n }\n var map = new L.map('map', mapOptions); // Creating a map object\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n map.addLayer(layer); // Adding layer to the map\n \n // Creating markers\n var hydMarker = new L.Marker([17.385044, 78.486671]);\n var vskpMarker = new L.Marker([17.686816, 83.218482]);\n var vjwdMarker = new L.Marker([16.506174, 80.648015]);\n \n // Creating latlng object\n var latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.686816, 83.218482]\n ];\n // Creating a polygon\n var polygon = L.polygon(latlngs, {color: 'red'});\n \n // Creating layer group\n var layerGroup = L.layerGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);\n layerGroup.addTo(map); // Adding layer group to map\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 4758,
"s": 4722,
"text": "It generates the following output −"
},
{
"code": null,
"e": 4894,
"s": 4758,
"text": "You can add a layer to the feature group using the addLayer() method. To this method, you need to pass the element that is to be added."
},
{
"code": null,
"e": 4954,
"s": 4894,
"text": "You can add a circle with the city Hyderabad at the center."
},
{
"code": null,
"e": 5151,
"s": 4954,
"text": "// Creating a circle\nvar circle = L.circle([16.506174, 80.648015], 50000, {color: 'red', fillColor:\n '#f03', fillOpacity: 0} );\n\n// Adding circle to the layer group\nlayerGroup.addLayer(circle);\n"
},
{
"code": null,
"e": 5191,
"s": 5151,
"text": "It will produce the following output. −"
},
{
"code": null,
"e": 5337,
"s": 5191,
"text": "You can remove a layer from the feature group using the removeLayer() method. To this method, you need to pass the element that is to be removed."
},
{
"code": null,
"e": 5408,
"s": 5337,
"text": "You can remove the marker on the city named Vijayawada as shown below."
},
{
"code": null,
"e": 5472,
"s": 5408,
"text": "// Removing layer from map\nlayerGroup.removeLayer(vjwdMarker);\n"
},
{
"code": null,
"e": 5511,
"s": 5472,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 5657,
"s": 5511,
"text": "It is similar to LayerGroup but it allows mouse events and bind popups to it. You can also set style to the entire group using setStyle() method."
},
{
"code": null,
"e": 5735,
"s": 5657,
"text": "Follow the steps given below to create a Feature Group and add it to the map."
},
{
"code": null,
"e": 5838,
"s": 5735,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 5909,
"s": 5838,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 5996,
"s": 5909,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 6142,
"s": 5996,
"text": "Step 4 − Create elements (layers) such as markers, polygons, and circles that are needed, by instantiating the respective classes as shown below."
},
{
"code": null,
"e": 6526,
"s": 6142,
"text": "// Creating markers\nvar hydMarker = new L.Marker([17.385044, 78.486671]);\nvar vskpMarker = new L.Marker([17.686816, 83.218482]);\nvar vjwdMarker = new L.Marker([16.506174, 80.648015]);\n\n// Creating latlng object\nvar latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.686816, 83.218482]\n];\n// Creating a polygon\nvar polygon = L.polygon(latlngs, {color: 'red'});>\n"
},
{
"code": null,
"e": 6644,
"s": 6526,
"text": "Step 5 − Create Feature Group using l.featureGroup(). Pass the above-created markers, polygons, etc., as shown below."
},
{
"code": null,
"e": 6752,
"s": 6644,
"text": "// Creating feature group\nvar featureGroup = L.featureGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);\n"
},
{
"code": null,
"e": 6989,
"s": 6752,
"text": "Step 6 − If you set style to the feature group, it will be applied to each element (layer) in the group. You can do so using the setStyle() method and to this method, you need to pass values to the options such as color and opacity etc."
},
{
"code": null,
"e": 7051,
"s": 6989,
"text": "Set the style to the feature group created in the above step."
},
{
"code": null,
"e": 7140,
"s": 7051,
"text": "// Setting style to the feature group\nfeatureGroup.setStyle({color:'blue',opacity:.5});\n"
},
{
"code": null,
"e": 7210,
"s": 7140,
"text": "Step 7 − Bind the popup using the bindPopup() method, as shown below."
},
{
"code": null,
"e": 7290,
"s": 7210,
"text": "// Binding popup to the feature group\nfeatureGroup.bindPopup(\"Feature Group\");\n"
},
{
"code": null,
"e": 7376,
"s": 7290,
"text": "Step 8 − Add the feature group created in the previous step using the addTo() method."
},
{
"code": null,
"e": 7431,
"s": 7376,
"text": "// Adding layer group to map\nfeatureGroup.addTo(map);\n"
},
{
"code": null,
"e": 7535,
"s": 7431,
"text": "The following code creates a feature group which holds 3 markers and a polygon, and adds it to the map."
},
{
"code": null,
"e": 9151,
"s": 7535,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Leaflet Feature Group</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width:900px; height:580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [17.385044, 78.486671],\n zoom: 7\n }\n var map = new L.map('map', mapOptions); // Creating a map object\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n map.addLayer(layer); // Adding layer to the map\n \n // Creating markers\n var hydMarker = new L.Marker([17.385044, 78.486671]);\n var vskpMarker = new L.Marker([17.686816, 83.218482]);\n var vjwdMarker = new L.Marker([16.506174, 80.648015]);\n \n // Creating latlng object\n var latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.686816, 83.218482]\n ];\n var polygon = L.polygon(latlngs, {color: 'red'}); // Creating a polygon\n \n // Creating feature group\n var featureGroup = L.featureGroup([hydMarker, vskpMarker, vjwdMarker, polygon]);\n featureGroup.setStyle({color:'blue',opacity:.5});\n featureGroup.bindPopup(\"Feature Group\");\n featureGroup.addTo(map); // Adding layer group to map\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 9187,
"s": 9151,
"text": "It generates the following output −"
},
{
"code": null,
"e": 9194,
"s": 9187,
"text": " Print"
},
{
"code": null,
"e": 9205,
"s": 9194,
"text": " Add Notes"
}
] |
Angular 8 - Testing | Testing is a very important phase in the development life cycle of an application. It ensures an application quality. It needs careful planning and execution.
Unit testing is the easiest method to test an application. It is based on ensuring the correctness of a piece of code or a method of a class. But, it does not reflect the real environment and subsequently. It is the least option to find the bugs.
Generally, Angular 8 uses Jasmine and Karma configurations. To perform this, first you need to configure in your project, using the below command −
ng test
Now, you could see the following response −
Now, Chrome browser also opens and shows the test output in the “Jasmine HTML Reporter”. It looks similar to this,
Unit tests are small, simple and fast process whereas, E2E testing phase multiple components are involved and works together which cover flows in the application. To perform e2e test, type the below command −
ng e2e
You could see the below response −
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2547,
"s": 2388,
"text": "Testing is a very important phase in the development life cycle of an application. It ensures an application quality. It needs careful planning and execution."
},
{
"code": null,
"e": 2794,
"s": 2547,
"text": "Unit testing is the easiest method to test an application. It is based on ensuring the correctness of a piece of code or a method of a class. But, it does not reflect the real environment and subsequently. It is the least option to find the bugs."
},
{
"code": null,
"e": 2942,
"s": 2794,
"text": "Generally, Angular 8 uses Jasmine and Karma configurations. To perform this, first you need to configure in your project, using the below command −"
},
{
"code": null,
"e": 2950,
"s": 2942,
"text": "ng test"
},
{
"code": null,
"e": 2994,
"s": 2950,
"text": "Now, you could see the following response −"
},
{
"code": null,
"e": 3109,
"s": 2994,
"text": "Now, Chrome browser also opens and shows the test output in the “Jasmine HTML Reporter”. It looks similar to this,"
},
{
"code": null,
"e": 3318,
"s": 3109,
"text": "Unit tests are small, simple and fast process whereas, E2E testing phase multiple components are involved and works together which cover flows in the application. To perform e2e test, type the below command −"
},
{
"code": null,
"e": 3325,
"s": 3318,
"text": "ng e2e"
},
{
"code": null,
"e": 3360,
"s": 3325,
"text": "You could see the below response −"
},
{
"code": null,
"e": 3395,
"s": 3360,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3409,
"s": 3395,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3444,
"s": 3409,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3458,
"s": 3444,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3493,
"s": 3458,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3513,
"s": 3493,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 3548,
"s": 3513,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3565,
"s": 3548,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3598,
"s": 3565,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3610,
"s": 3598,
"text": " Senol Atac"
},
{
"code": null,
"e": 3645,
"s": 3610,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3657,
"s": 3645,
"text": " Senol Atac"
},
{
"code": null,
"e": 3664,
"s": 3657,
"text": " Print"
},
{
"code": null,
"e": 3675,
"s": 3664,
"text": " Add Notes"
}
] |
Querying Live running status and PNR of trains using Railway API in Python - GeeksforGeeks | 08 Jun, 2021
Railway API is organized around GET Requests. One can use this JSON based API to get information from Indian Railways regarding Live Train Status, PNR Status, Train Schedule, Station Details, and other things.
To use this API, one must need the API key, which can get from here
Note: User need to create an account on railwayapi.com to use the APIs.
Modules Needed :
requests
json
Below is the implementation :
Python3
# Python program to find live train# status using RAILWAY API # import required modulesimport requests , json # enter your api key hereapi_key = "Your_API_Key" # base_url variable to store urlbase_url = "https://api.railwayapi.com/v2/live/train/" # enter train_number heretrain_number = "12056" # enter current date in dd-mm-yyyy formatcurrent_date = "20-06-2018" # complete_url variable to# store complete url addresscomplete_url = base_url + train_number + "/date/" + current_date + "/apikey/" + api_key + "/" # get method of requests module# return response objectresponse_ob = requests.get(complete_url) # json method of response object convert# json format data into python format dataresult = response_ob.json() # Now result contains a list of nested dictionaries# Check the value of "response_code" key is equal# to "200" or not if equal that means record is# found otherwise record is not foundif result["response_code"] == 200 : # train name is extracting from # the result variable data train_name = result["train"]["name"] # store the value or data of # "route" key in variable y temp = result["route"] # source station name is extracting # from the y variable data source_station = temp[0]["station"]["name"] # destination station name is # extracting from the y variable data destination_station = temp[-1]["station"]["name"] # store the value of "position" # key in variable position position = result["position"] # print details print(" train name : " + str(train_name) + "\n source station : " + str(source_station) + "\n destination station : "+ str(destination_station) + "\n current status : " + str(position) ) else : print("Record not Found")
Output:
train name : NEWDELHI JAN SHATABDI EXP
source station : DEHRADUN
destination station : NEW DELHI
current status : Train has reached Destination and late by 15 minutes.
Python3
# Python program to find PNR# status using RAILWAY API # import required modulesimport requests, json # Enter API key hereapi_key = "Your_API_key" # base_url variable to store urlbase_url = "https://api.railwayapi.com/v2/pnr-status/pnr/" # Enter valid pnr_numberpnr_number = "6515483790" # Stores complete url addresscomplete_url = base_url + pnr_number + "/apikey/" + api_key + "/" # get method of requests module# return response objectresponse_ob = requests.get(complete_url) # json method of response object convert# json format data into python format dataresult = response_ob.json() # now result contains list# of nested dictionariesif result["response_code"] == 200: # train name is extracting # from the result variable data train_name = result["train"]["name"] # train number is extracting from # the result variable data train_number = result["train"]["number"] # from station name is extracting # from the result variable data from_station = result["from_station"]["name"] # to_station name is extracting from # the result variable data to_station = result["to_station"]["name"] # boarding point station name is # extracting from the result variable data boarding_point = result["boarding_point"]["name"] # reservation upto station name is # extracting from the result variable data reservation_upto = result["reservation_upto"]["name"] # store the value or data of "pnr" # key in pnr_num variable pnr_num = result["pnr"] # store the value or data of "doj" key # in variable date_of_journey variable date_of_journey = result["doj"] # store the value or data of # "total_passengers" key in variable total_passengers = result["total_passengers"] # store the value or data of "passengers" # key in variable passengers_list passengers_list = result["passengers"] # store the value or data of # "chart_prepared" key in variable chart_prepared = result["chart_prepared"] # print following values print(" train name : " + str(train_name) + "\n train number : " + str(train_number) + "\n from station : " + str(from_station) + "\n to station : " + str(to_station) + "\n boarding point : " + str(boarding_point) + "\n reservation upto : " + str(reservation_upto) + "\n pnr number : " + str(pnr_num) + "\n date of journey : " + str(date_of_journey) + "\n total no. of passengers: " + str(total_passengers) + "\n chart prepared : " + str(chart_prepared)) # looping through passenger list for passenger in passengers_list: # store the value or data # of "no" key in variable passenger_num = passenger["no"] # store the value or data of # "current_status" key in variable current_status = passenger["current_status"] # store the value or data of # "booking_status" key in variable booking_status = passenger["booking_status"] # print following values print(" passenger number : " + str(passenger_num) + "\n current status : " + str(current_status) + "\n booking_status : " + str(booking_status)) else: print("Record Not Found")
Output :
train name : DOON EXPRESS
train number : 13009
from station : LUCKNOW
to station : DEHRADUN
boarding point : LUCKNOW
reservation upto : DEHRADUN
pnr number : 6515483790
date of journey : 01-07-2018
total no. of passengers: 1
chart prepared : False
passenger number : 1
current status : RLWL/-/16/GN
booking_status : RLWL/-/23/GN
kumarv456
surinderdawra388
python-modules
Python-projects
python-utility
Python
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25671,
"s": 25643,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 25882,
"s": 25671,
"text": "Railway API is organized around GET Requests. One can use this JSON based API to get information from Indian Railways regarding Live Train Status, PNR Status, Train Schedule, Station Details, and other things. "
},
{
"code": null,
"e": 25951,
"s": 25882,
"text": "To use this API, one must need the API key, which can get from here "
},
{
"code": null,
"e": 26024,
"s": 25951,
"text": "Note: User need to create an account on railwayapi.com to use the APIs. "
},
{
"code": null,
"e": 26042,
"s": 26024,
"text": "Modules Needed : "
},
{
"code": null,
"e": 26056,
"s": 26042,
"text": "requests\njson"
},
{
"code": null,
"e": 26090,
"s": 26058,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 26098,
"s": 26090,
"text": "Python3"
},
{
"code": "# Python program to find live train# status using RAILWAY API # import required modulesimport requests , json # enter your api key hereapi_key = \"Your_API_Key\" # base_url variable to store urlbase_url = \"https://api.railwayapi.com/v2/live/train/\" # enter train_number heretrain_number = \"12056\" # enter current date in dd-mm-yyyy formatcurrent_date = \"20-06-2018\" # complete_url variable to# store complete url addresscomplete_url = base_url + train_number + \"/date/\" + current_date + \"/apikey/\" + api_key + \"/\" # get method of requests module# return response objectresponse_ob = requests.get(complete_url) # json method of response object convert# json format data into python format dataresult = response_ob.json() # Now result contains a list of nested dictionaries# Check the value of \"response_code\" key is equal# to \"200\" or not if equal that means record is# found otherwise record is not foundif result[\"response_code\"] == 200 : # train name is extracting from # the result variable data train_name = result[\"train\"][\"name\"] # store the value or data of # \"route\" key in variable y temp = result[\"route\"] # source station name is extracting # from the y variable data source_station = temp[0][\"station\"][\"name\"] # destination station name is # extracting from the y variable data destination_station = temp[-1][\"station\"][\"name\"] # store the value of \"position\" # key in variable position position = result[\"position\"] # print details print(\" train name : \" + str(train_name) + \"\\n source station : \" + str(source_station) + \"\\n destination station : \"+ str(destination_station) + \"\\n current status : \" + str(position) ) else : print(\"Record not Found\")",
"e": 27855,
"s": 26098,
"text": null
},
{
"code": null,
"e": 27865,
"s": 27855,
"text": "Output: "
},
{
"code": null,
"e": 28037,
"s": 27865,
"text": " train name : NEWDELHI JAN SHATABDI EXP\n source station : DEHRADUN\n destination station : NEW DELHI\n current status : Train has reached Destination and late by 15 minutes."
},
{
"code": null,
"e": 28051,
"s": 28043,
"text": "Python3"
},
{
"code": "# Python program to find PNR# status using RAILWAY API # import required modulesimport requests, json # Enter API key hereapi_key = \"Your_API_key\" # base_url variable to store urlbase_url = \"https://api.railwayapi.com/v2/pnr-status/pnr/\" # Enter valid pnr_numberpnr_number = \"6515483790\" # Stores complete url addresscomplete_url = base_url + pnr_number + \"/apikey/\" + api_key + \"/\" # get method of requests module# return response objectresponse_ob = requests.get(complete_url) # json method of response object convert# json format data into python format dataresult = response_ob.json() # now result contains list# of nested dictionariesif result[\"response_code\"] == 200: # train name is extracting # from the result variable data train_name = result[\"train\"][\"name\"] # train number is extracting from # the result variable data train_number = result[\"train\"][\"number\"] # from station name is extracting # from the result variable data from_station = result[\"from_station\"][\"name\"] # to_station name is extracting from # the result variable data to_station = result[\"to_station\"][\"name\"] # boarding point station name is # extracting from the result variable data boarding_point = result[\"boarding_point\"][\"name\"] # reservation upto station name is # extracting from the result variable data reservation_upto = result[\"reservation_upto\"][\"name\"] # store the value or data of \"pnr\" # key in pnr_num variable pnr_num = result[\"pnr\"] # store the value or data of \"doj\" key # in variable date_of_journey variable date_of_journey = result[\"doj\"] # store the value or data of # \"total_passengers\" key in variable total_passengers = result[\"total_passengers\"] # store the value or data of \"passengers\" # key in variable passengers_list passengers_list = result[\"passengers\"] # store the value or data of # \"chart_prepared\" key in variable chart_prepared = result[\"chart_prepared\"] # print following values print(\" train name : \" + str(train_name) + \"\\n train number : \" + str(train_number) + \"\\n from station : \" + str(from_station) + \"\\n to station : \" + str(to_station) + \"\\n boarding point : \" + str(boarding_point) + \"\\n reservation upto : \" + str(reservation_upto) + \"\\n pnr number : \" + str(pnr_num) + \"\\n date of journey : \" + str(date_of_journey) + \"\\n total no. of passengers: \" + str(total_passengers) + \"\\n chart prepared : \" + str(chart_prepared)) # looping through passenger list for passenger in passengers_list: # store the value or data # of \"no\" key in variable passenger_num = passenger[\"no\"] # store the value or data of # \"current_status\" key in variable current_status = passenger[\"current_status\"] # store the value or data of # \"booking_status\" key in variable booking_status = passenger[\"booking_status\"] # print following values print(\" passenger number : \" + str(passenger_num) + \"\\n current status : \" + str(current_status) + \"\\n booking_status : \" + str(booking_status)) else: print(\"Record Not Found\")",
"e": 31300,
"s": 28051,
"text": null
},
{
"code": null,
"e": 31311,
"s": 31300,
"text": "Output : "
},
{
"code": null,
"e": 31653,
"s": 31311,
"text": " train name : DOON EXPRESS\n train number : 13009\n from station : LUCKNOW\n to station : DEHRADUN\n boarding point : LUCKNOW\n reservation upto : DEHRADUN\n pnr number : 6515483790\n date of journey : 01-07-2018\n total no. of passengers: 1\n chart prepared : False\n passenger number : 1\n current status : RLWL/-/16/GN\n booking_status : RLWL/-/23/GN"
},
{
"code": null,
"e": 31665,
"s": 31655,
"text": "kumarv456"
},
{
"code": null,
"e": 31682,
"s": 31665,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31697,
"s": 31682,
"text": "python-modules"
},
{
"code": null,
"e": 31713,
"s": 31697,
"text": "Python-projects"
},
{
"code": null,
"e": 31728,
"s": 31713,
"text": "python-utility"
},
{
"code": null,
"e": 31735,
"s": 31728,
"text": "Python"
},
{
"code": null,
"e": 31833,
"s": 31735,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31865,
"s": 31833,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31907,
"s": 31865,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31949,
"s": 31907,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 32005,
"s": 31949,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 32032,
"s": 32005,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 32063,
"s": 32032,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 32099,
"s": 32063,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 32128,
"s": 32099,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 32150,
"s": 32128,
"text": "Defaultdict in Python"
}
] |
AngularJS | angular.element() Function - GeeksforGeeks | 12 Apr, 2019
The angular.element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular.element can be either used as an alias for jQuery function or it can be used as a function to wrap the element or string in Angular’s jqlite.
Syntax:
angular.element(element)
Where element refers to the HTML DOM element or the string to be wrapped into jQuery.
Example-1:
<!DOCTYPE html><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> <title> angular.element() </title></head> <body ng-app="app"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> angular.element() </h2> <div ng-controller="geek"> <div ng-mouseenter="style()" id="ide" ng-mouseleave="remove()"> {{name}} </div> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', '$document', function($scope, $document) { $scope.name = "GeeksforGeeks"; $scope.style = function() { angular.element( $document[0].querySelector('#ide')).css({ 'color': 'white', 'background-color': 'green', 'width': '200px' }); }; $scope.remove = function() { angular.element( $document[0].querySelector('#ide')).css({ 'color': 'black', 'background-color': 'white' }); }; } ]); </script> </body> </html>
Output:Before mouseenter:After mouseenter:
Example-2:
<!DOCTYPE html><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script> <title> angular.element() </title></head> <body ng-app="app" style="text-align:Center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> angular.element() </h2> <div ng-controller="geek"> <input type="text" id="text" ng-model="myVal" /> <button ng-click="getVal()"> Click me! </button> <br /> <br><b>You typed:</b> {{value}} </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', '$document', function($scope, $document) { $scope.myVal = ""; $scope.getVal = function() { $scope.value = angular.element( $document[0].querySelector( '#text')).val(); } }]); </script></body> </html>
Output:Before Input:After Input:
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
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
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ?
HTML Cheat Sheet - A Basic Guide to HTML | [
{
"code": null,
"e": 26301,
"s": 26273,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 26589,
"s": 26301,
"text": "The angular.element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular.element can be either used as an alias for jQuery function or it can be used as a function to wrap the element or string in Angular’s jqlite."
},
{
"code": null,
"e": 26597,
"s": 26589,
"text": "Syntax:"
},
{
"code": null,
"e": 26622,
"s": 26597,
"text": "angular.element(element)"
},
{
"code": null,
"e": 26708,
"s": 26622,
"text": "Where element refers to the HTML DOM element or the string to be wrapped into jQuery."
},
{
"code": null,
"e": 26719,
"s": 26708,
"text": "Example-1:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script> <title> angular.element() </title></head> <body ng-app=\"app\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2> angular.element() </h2> <div ng-controller=\"geek\"> <div ng-mouseenter=\"style()\" id=\"ide\" ng-mouseleave=\"remove()\"> {{name}} </div> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', '$document', function($scope, $document) { $scope.name = \"GeeksforGeeks\"; $scope.style = function() { angular.element( $document[0].querySelector('#ide')).css({ 'color': 'white', 'background-color': 'green', 'width': '200px' }); }; $scope.remove = function() { angular.element( $document[0].querySelector('#ide')).css({ 'color': 'black', 'background-color': 'white' }); }; } ]); </script> </body> </html>",
"e": 28027,
"s": 26719,
"text": null
},
{
"code": null,
"e": 28070,
"s": 28027,
"text": "Output:Before mouseenter:After mouseenter:"
},
{
"code": null,
"e": 28081,
"s": 28070,
"text": "Example-2:"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script> <title> angular.element() </title></head> <body ng-app=\"app\" style=\"text-align:Center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2> angular.element() </h2> <div ng-controller=\"geek\"> <input type=\"text\" id=\"text\" ng-model=\"myVal\" /> <button ng-click=\"getVal()\"> Click me! </button> <br /> <br><b>You typed:</b> {{value}} </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', '$document', function($scope, $document) { $scope.myVal = \"\"; $scope.getVal = function() { $scope.value = angular.element( $document[0].querySelector( '#text')).val(); } }]); </script></body> </html>",
"e": 29075,
"s": 28081,
"text": null
},
{
"code": null,
"e": 29108,
"s": 29075,
"text": "Output:Before Input:After Input:"
},
{
"code": null,
"e": 29125,
"s": 29108,
"text": "Web Technologies"
},
{
"code": null,
"e": 29223,
"s": 29125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29263,
"s": 29223,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29308,
"s": 29263,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29351,
"s": 29308,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29412,
"s": 29351,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29484,
"s": 29412,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29542,
"s": 29484,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29602,
"s": 29542,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29635,
"s": 29602,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 29696,
"s": 29635,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
ReactJS – forceUpdate() Method | In this article, we are going to see how to execute a function by forcibly re-rendering a component.
The component in the React lifecycle only re-renders if the props passed to it or its state changes but to forcibly render the component, use the build it forceUpdate method. This method overrides the shouldComponentUpdate method defined in the component but will consider the shouldComponentUpdate method defined in the children component.
component.forceUpdate(callback)
In this example, we will build a React application that gets forcibly re-rendered on a button click.
App.jsx
import React from 'react';
class App extends React.Component {
update = () => {
// calling the forceUpdate() method
this.forceUpdate();
};
render() {
console.log('Component is rendered');
return (
<>
<h2>TutorialsPoint</h2>
<button onClick={this.update}>Render</button>
</>
);
}
}
export default App;
This will produce the following result. | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this article, we are going to see how to execute a function by forcibly re-rendering a component."
},
{
"code": null,
"e": 1504,
"s": 1163,
"text": "The component in the React lifecycle only re-renders if the props passed to it or its state changes but to forcibly render the component, use the build it forceUpdate method. This method overrides the shouldComponentUpdate method defined in the component but will consider the shouldComponentUpdate method defined in the children component."
},
{
"code": null,
"e": 1536,
"s": 1504,
"text": "component.forceUpdate(callback)"
},
{
"code": null,
"e": 1637,
"s": 1536,
"text": "In this example, we will build a React application that gets forcibly re-rendered on a button click."
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "App.jsx"
},
{
"code": null,
"e": 2032,
"s": 1645,
"text": "import React from 'react';\n\nclass App extends React.Component {\n\n update = () => {\n // calling the forceUpdate() method\n this.forceUpdate();\n };\n render() {\n console.log('Component is rendered');\n return (\n <>\n <h2>TutorialsPoint</h2>\n <button onClick={this.update}>Render</button>\n </>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 2072,
"s": 2032,
"text": "This will produce the following result."
}
] |
Logging in Python | In this article, we will learn about logging in Python and various stages in protection and security.
First of all, we need to import the logging module, followed by using the logger to checj=k the current status and log messages. We are having 5 severity levels namely −
Warning
Info
Error
Critical
Debug
The logging module allows us to get started directly without setting up the configuration manually.
Import logging
logging.debug('a debug message')
logging.info('an info message')
logging.warning('a warning message')
logging.error('an error message')
logging.critical('a critical message')
WARNING:root: a warning message
ERROR:root: an error message
CRITICAL:root: a critical message
As we didn’t set the configurations, by default the logging and info messages aren’t logged. To make them noticeable we need to set the configuration manually.
Now let’s see how we can implement the basic configurations.
By the help of level parameter − we can set which level of log messages must be recorded.
Import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This gets logged')
DEBUG:root: This gets logged
By using this statement all statements above the debug level get recorded.
Now switching to file logging over console logging.
Import logging
logging.basicConfig(filename='app.log', filemode='w',
format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This gets logged to a file')
root - ERROR - This gets logged to a file
Here the file mode is said to write only so we have rights to rewrite the contents of the file. By default this configuration it opens in append mode only.
In this article, we learnt about logging in Python and various levels of logging available to us. | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "In this article, we will learn about logging in Python and various stages in protection and security."
},
{
"code": null,
"e": 1334,
"s": 1164,
"text": "First of all, we need to import the logging module, followed by using the logger to checj=k the current status and log messages. We are having 5 severity levels namely −"
},
{
"code": null,
"e": 1342,
"s": 1334,
"text": "Warning"
},
{
"code": null,
"e": 1347,
"s": 1342,
"text": "Info"
},
{
"code": null,
"e": 1353,
"s": 1347,
"text": "Error"
},
{
"code": null,
"e": 1362,
"s": 1353,
"text": "Critical"
},
{
"code": null,
"e": 1368,
"s": 1362,
"text": "Debug"
},
{
"code": null,
"e": 1468,
"s": 1368,
"text": "The logging module allows us to get started directly without setting up the configuration manually."
},
{
"code": null,
"e": 1658,
"s": 1468,
"text": "Import logging\nlogging.debug('a debug message')\nlogging.info('an info message')\nlogging.warning('a warning message')\nlogging.error('an error message')\nlogging.critical('a critical message')"
},
{
"code": null,
"e": 1753,
"s": 1658,
"text": "WARNING:root: a warning message\nERROR:root: an error message\nCRITICAL:root: a critical message"
},
{
"code": null,
"e": 1913,
"s": 1753,
"text": "As we didn’t set the configurations, by default the logging and info messages aren’t logged. To make them noticeable we need to set the configuration manually."
},
{
"code": null,
"e": 1974,
"s": 1913,
"text": "Now let’s see how we can implement the basic configurations."
},
{
"code": null,
"e": 2064,
"s": 1974,
"text": "By the help of level parameter − we can set which level of log messages must be recorded."
},
{
"code": null,
"e": 2154,
"s": 2064,
"text": "Import logging\nlogging.basicConfig(level=logging.DEBUG)\nlogging.debug('This gets logged')"
},
{
"code": null,
"e": 2183,
"s": 2154,
"text": "DEBUG:root: This gets logged"
},
{
"code": null,
"e": 2258,
"s": 2183,
"text": "By using this statement all statements above the debug level get recorded."
},
{
"code": null,
"e": 2310,
"s": 2258,
"text": "Now switching to file logging over console logging."
},
{
"code": null,
"e": 2474,
"s": 2310,
"text": "Import logging\nlogging.basicConfig(filename='app.log', filemode='w',\nformat='%(name)s - %(levelname)s - %(message)s')\nlogging.warning('This gets logged to a file')"
},
{
"code": null,
"e": 2516,
"s": 2474,
"text": "root - ERROR - This gets logged to a file"
},
{
"code": null,
"e": 2672,
"s": 2516,
"text": "Here the file mode is said to write only so we have rights to rewrite the contents of the file. By default this configuration it opens in append mode only."
},
{
"code": null,
"e": 2770,
"s": 2672,
"text": "In this article, we learnt about logging in Python and various levels of logging available to us."
}
] |
C Program to reverse a given number using Recursive function | "Recursive function" is something which calls itself again in the body of the function.
For example,
A function fact ( ), which computes the factorial of an integer ‘N’, which is the product of all whole numbers from 1 to N.
A function fact ( ), which computes the factorial of an integer ‘N’, which is the product of all whole numbers from 1 to N.
fact ( ) with an argument of 1 (or) 0, the function returns 1. otherwise, it returns n*fact (n-1), this happens until ‘n’ equals 1.
fact ( ) with an argument of 1 (or) 0, the function returns 1. otherwise, it returns n*fact (n-1), this happens until ‘n’ equals 1.
Fact (5) =5* fact (4)
=5*4*3* fact (3)
=5*4*3*2* fact (2)
=5*4*3*2*1 fact (1)
=5*4*3*2*1
= 120.
Following is the C program for use of recursive function to reverse a number −
#include<stdio.h>
main ( ){
int n,f;
int fact (int);
clrscr ( );
printf ("enter a number");
scanf ("%d", &n);
f= fact (n);
printf (factorial value = %d",f);
}
int fact (int n){
int f;
if ( ( n==1) || (n==0))
return 1;
else
f= n*fact (n-1);
return f;
}
The output is given below −
Enter a number 5
Factorial value = 120
Given below is another C Program to reverse a given number using Recursive function −
#include<stdio.h>
int sum=0,rem;
int main(){
int num,revNum;
printf("enter number:\n");
scanf("%d",&num);
revNum=revNumFunction(num);//calling function to reverse the given number
printf("the number after reverse :%d",revNum);
return 0;
}
revNumFunction(int num){
if(num){
rem=num%10;
sum=sum*10+rem;
revNum(num/10);
}
else
return sum;
}
The output is as follows −
enter number: 1357
the number after reverse is :7531 | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "\"Recursive function\" is something which calls itself again in the body of the function."
},
{
"code": null,
"e": 1163,
"s": 1150,
"text": "For example,"
},
{
"code": null,
"e": 1287,
"s": 1163,
"text": "A function fact ( ), which computes the factorial of an integer ‘N’, which is the product of all whole numbers from 1 to N."
},
{
"code": null,
"e": 1411,
"s": 1287,
"text": "A function fact ( ), which computes the factorial of an integer ‘N’, which is the product of all whole numbers from 1 to N."
},
{
"code": null,
"e": 1543,
"s": 1411,
"text": "fact ( ) with an argument of 1 (or) 0, the function returns 1. otherwise, it returns n*fact (n-1), this happens until ‘n’ equals 1."
},
{
"code": null,
"e": 1675,
"s": 1543,
"text": "fact ( ) with an argument of 1 (or) 0, the function returns 1. otherwise, it returns n*fact (n-1), this happens until ‘n’ equals 1."
},
{
"code": null,
"e": 1786,
"s": 1675,
"text": "Fact (5) =5* fact (4)\n =5*4*3* fact (3)\n =5*4*3*2* fact (2)\n =5*4*3*2*1 fact (1)\n =5*4*3*2*1\n = 120."
},
{
"code": null,
"e": 1865,
"s": 1786,
"text": "Following is the C program for use of recursive function to reverse a number −"
},
{
"code": null,
"e": 2162,
"s": 1865,
"text": "#include<stdio.h>\nmain ( ){\n int n,f;\n int fact (int);\n clrscr ( );\n printf (\"enter a number\");\n scanf (\"%d\", &n);\n f= fact (n);\n printf (factorial value = %d\",f);\n}\nint fact (int n){\n int f;\n if ( ( n==1) || (n==0))\n return 1;\n else\n f= n*fact (n-1);\n return f;\n}"
},
{
"code": null,
"e": 2190,
"s": 2162,
"text": "The output is given below −"
},
{
"code": null,
"e": 2229,
"s": 2190,
"text": "Enter a number 5\nFactorial value = 120"
},
{
"code": null,
"e": 2315,
"s": 2229,
"text": "Given below is another C Program to reverse a given number using Recursive function −"
},
{
"code": null,
"e": 2704,
"s": 2315,
"text": "#include<stdio.h>\nint sum=0,rem;\nint main(){\n int num,revNum;\n printf(\"enter number:\\n\");\n scanf(\"%d\",&num);\n revNum=revNumFunction(num);//calling function to reverse the given number\n printf(\"the number after reverse :%d\",revNum);\n return 0;\n}\nrevNumFunction(int num){\n if(num){\n rem=num%10;\n sum=sum*10+rem;\n revNum(num/10);\n }\n else\n return sum;\n}"
},
{
"code": null,
"e": 2731,
"s": 2704,
"text": "The output is as follows −"
},
{
"code": null,
"e": 2784,
"s": 2731,
"text": "enter number: 1357\nthe number after reverse is :7531"
}
] |
Tryit Editor v3.7 | Tryit: HTML text-align | [] |
Geographical plotting of maps with Plotly | by Jenny Dcruz | Towards Data Science | Geographical plotting is a method of displaying data on a global scale as well as for states of a country, often in a colorful manner. It plays a significant role in data analysis and visualization. It is commonly used while building dashboards to present widespread data.
In order to create interactive maps we use python’s plotly library. Plotly is used to make interactive graphs, as well as create other visualizations.
Click here to learn more about plotly.
Let’s split this tutorial into 2 parts. In the first part we’ll focus on geographically plotting data based on a country, which in our case will be the agricultural export of the USA. In the 2nd part we’ll use a random, global GDP dataset. Both these datasets can be found here.
Basic understanding of python programming. Specifically python’s matplotlib and plotly libraries.
Begin by importing the following modules:
import pandas as pdimport chart_studio.plotly as pyimport plotly.offline as poimport plotly.graph_objs as pgimport matplotlib.pyplot as plt%matplotlib inline
You need to initiate plotly’s notebook mode to display the plot inside the notebook. This will allow you to generate graphs offline and save them in a local machine.
This can be done as follows:
po.init_notebook_mode(connected = True)
We load our first dataset based on the USA’s agricultural export.
AE = pd.read_csv(‘AgriculturalExport.csv’)AE.head()
Here, the code of the state is vital as it helps us with the location when we plot a geographical graph.
While plotting data, you need to consider a few factors such as : What kind of output do you need? Which locations are to be displayed? What are the values required to be displayed in every location? Last but not least, what kind of color, styling or text is required? All these basic values are under our data variable that is a dictionary. You can use different map types. Here we’re using choropleth which is a basic graph that does not require any other libraries. Then we have the locations i.e. the location codes. Next, we require locationmode which tells the method we plan on specifying the location. In our example, we set the location mode as usa-states. Now we need values for the locations and then the text to be displayed while hovering over each of the mentioned locations.
data = dict(type = ‘choropleth’, locations = [‘AL’, ‘AK’, ‘AR’, ‘CA’], locationmode = ‘USA-states’, z = [1,2,30,40,50], text = [‘alabama’, ‘alaska’, ‘arizona’, ‘pugger’, ‘california’])
In the layout variable we just need scope which is represented with geo. Make sure USA is not written in capitals as that will lead to an error.
layout = dict(geo = {'scope':'usa'})
The x variable uses the plotly.graph_objs module that we imported earlier in order to plot the structure of the state. In our case, that’s the USA. We pass 2 parameters to x: data and layout. Data represents the data represented on particular scopes; Layout defines what kind of scope we are using there.
x = pg.Figure(data = [data] ,layout = layout)po.iplot(x)
Now we just need to change the layout and data according to the values available in our dataset. Instead of typing each state’s code, we write AE[‘code’] which calls the state codes from our dataset. Similarly, z will represent the total exports for every state as shown below. Coming to the text variable, our dataset includes a column called text that displays all the data with regards to the agricultural export for every state so instead of changing the text variable to just the state names we write AE[‘text’]. Thus displaying all the export information for every state.
data = dict(type = 'choropleth', locations = AE['code'], locationmode = 'USA-states', z = AE['total exports'], text = AE['text'])
As for layout, we’re now talking about more than just the scope so we can add showlakes and a title as follows:
layout = dict(title = 'USAs Agricultural Exports', geo = dict(scope = 'usa' , showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
You can use different color scales like Portland, Greens, etc and even add a color bar to your data as shown below:
data = dict(type = 'choropleth', locations = AE['code'], locationmode = 'USA-states', z = AE['total exports'], text = AE['text'], colorscale = 'Greens', colorbar = {'title' : 'colorbar'})layout = dict(title = 'USAs Agricultural Exports with the lakes', geo = dict(scope='usa' , showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
We’ve now reached the second part of our article where we’ll plot geographical charts on a global scale. For this we’ll use our global GDP dataset.
G_GDP = pd.read_csv('GlobalGDP.csv')G_GDP.head()
So again, let’s define the data and layout.
data = dict(type='choropleth', locations = G_GDP['CODE'], z = G_GDP['GDP (BILLIONS)'], text = G_GDP['COUNTRY'])
As we’re plotting a map on a global scale, layout will now consist of the projections attribute and not scope.
layout = dict(title = 'Global GDP - hammer projection', geo = dict( projection = {'type':'hammer'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
What’s fun with these plots is that you can zoom into, swipe through, and view the data plotted around the globe conveniently. This is because of our projection type: hammer. We can view the same data using other projection types as well such as natural earth, robinson, mercator, stereographic etc. The code and output for few of these projection types are given below.
layout = dict(title = 'Global GDP - robinson projection', geo = dict( projection = {'type':'robinson'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout) po.iplot(x)
layout = dict(title = 'Global GDP - natural earth projection', geo = dict( projection = {'type':'natural earth'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
layout = dict(title = 'Global GDP - mercator projection', geo = dict(projection = {'type':'mercator'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
layout = dict(title = 'Global GDP - stereographic projection', geo = dict(projection = {'type':'stereographic'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
layout = dict(title = 'Global GDP - orthographic projection', geo = dict( projection = {'type':'orthographic'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
You can remove the boundaries to your projections as follows:
layout = dict(title = 'Global GDP - robinson projection without borders', geo = dict(showframe = False, projection = {'type':'robinson'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)
To learn more about Plotly's map configurations and styling you can refer to its documentation.
The whole code to this article can be found here.
I hope this quick tutorial was helpful. Thank you for giving it a read!
You can reach out to me here. | [
{
"code": null,
"e": 445,
"s": 172,
"text": "Geographical plotting is a method of displaying data on a global scale as well as for states of a country, often in a colorful manner. It plays a significant role in data analysis and visualization. It is commonly used while building dashboards to present widespread data."
},
{
"code": null,
"e": 596,
"s": 445,
"text": "In order to create interactive maps we use python’s plotly library. Plotly is used to make interactive graphs, as well as create other visualizations."
},
{
"code": null,
"e": 635,
"s": 596,
"text": "Click here to learn more about plotly."
},
{
"code": null,
"e": 914,
"s": 635,
"text": "Let’s split this tutorial into 2 parts. In the first part we’ll focus on geographically plotting data based on a country, which in our case will be the agricultural export of the USA. In the 2nd part we’ll use a random, global GDP dataset. Both these datasets can be found here."
},
{
"code": null,
"e": 1012,
"s": 914,
"text": "Basic understanding of python programming. Specifically python’s matplotlib and plotly libraries."
},
{
"code": null,
"e": 1054,
"s": 1012,
"text": "Begin by importing the following modules:"
},
{
"code": null,
"e": 1212,
"s": 1054,
"text": "import pandas as pdimport chart_studio.plotly as pyimport plotly.offline as poimport plotly.graph_objs as pgimport matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 1378,
"s": 1212,
"text": "You need to initiate plotly’s notebook mode to display the plot inside the notebook. This will allow you to generate graphs offline and save them in a local machine."
},
{
"code": null,
"e": 1407,
"s": 1378,
"text": "This can be done as follows:"
},
{
"code": null,
"e": 1447,
"s": 1407,
"text": "po.init_notebook_mode(connected = True)"
},
{
"code": null,
"e": 1513,
"s": 1447,
"text": "We load our first dataset based on the USA’s agricultural export."
},
{
"code": null,
"e": 1565,
"s": 1513,
"text": "AE = pd.read_csv(‘AgriculturalExport.csv’)AE.head()"
},
{
"code": null,
"e": 1670,
"s": 1565,
"text": "Here, the code of the state is vital as it helps us with the location when we plot a geographical graph."
},
{
"code": null,
"e": 2460,
"s": 1670,
"text": "While plotting data, you need to consider a few factors such as : What kind of output do you need? Which locations are to be displayed? What are the values required to be displayed in every location? Last but not least, what kind of color, styling or text is required? All these basic values are under our data variable that is a dictionary. You can use different map types. Here we’re using choropleth which is a basic graph that does not require any other libraries. Then we have the locations i.e. the location codes. Next, we require locationmode which tells the method we plan on specifying the location. In our example, we set the location mode as usa-states. Now we need values for the locations and then the text to be displayed while hovering over each of the mentioned locations."
},
{
"code": null,
"e": 2649,
"s": 2460,
"text": "data = dict(type = ‘choropleth’, locations = [‘AL’, ‘AK’, ‘AR’, ‘CA’], locationmode = ‘USA-states’, z = [1,2,30,40,50], text = [‘alabama’, ‘alaska’, ‘arizona’, ‘pugger’, ‘california’])"
},
{
"code": null,
"e": 2794,
"s": 2649,
"text": "In the layout variable we just need scope which is represented with geo. Make sure USA is not written in capitals as that will lead to an error."
},
{
"code": null,
"e": 2831,
"s": 2794,
"text": "layout = dict(geo = {'scope':'usa'})"
},
{
"code": null,
"e": 3136,
"s": 2831,
"text": "The x variable uses the plotly.graph_objs module that we imported earlier in order to plot the structure of the state. In our case, that’s the USA. We pass 2 parameters to x: data and layout. Data represents the data represented on particular scopes; Layout defines what kind of scope we are using there."
},
{
"code": null,
"e": 3193,
"s": 3136,
"text": "x = pg.Figure(data = [data] ,layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 3771,
"s": 3193,
"text": "Now we just need to change the layout and data according to the values available in our dataset. Instead of typing each state’s code, we write AE[‘code’] which calls the state codes from our dataset. Similarly, z will represent the total exports for every state as shown below. Coming to the text variable, our dataset includes a column called text that displays all the data with regards to the agricultural export for every state so instead of changing the text variable to just the state names we write AE[‘text’]. Thus displaying all the export information for every state."
},
{
"code": null,
"e": 3949,
"s": 3771,
"text": "data = dict(type = 'choropleth', locations = AE['code'], locationmode = 'USA-states', z = AE['total exports'], text = AE['text'])"
},
{
"code": null,
"e": 4061,
"s": 3949,
"text": "As for layout, we’re now talking about more than just the scope so we can add showlakes and a title as follows:"
},
{
"code": null,
"e": 4322,
"s": 4061,
"text": "layout = dict(title = 'USAs Agricultural Exports', geo = dict(scope = 'usa' , showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 4438,
"s": 4322,
"text": "You can use different color scales like Portland, Greens, etc and even add a color bar to your data as shown below:"
},
{
"code": null,
"e": 4967,
"s": 4438,
"text": "data = dict(type = 'choropleth', locations = AE['code'], locationmode = 'USA-states', z = AE['total exports'], text = AE['text'], colorscale = 'Greens', colorbar = {'title' : 'colorbar'})layout = dict(title = 'USAs Agricultural Exports with the lakes', geo = dict(scope='usa' , showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 5115,
"s": 4967,
"text": "We’ve now reached the second part of our article where we’ll plot geographical charts on a global scale. For this we’ll use our global GDP dataset."
},
{
"code": null,
"e": 5164,
"s": 5115,
"text": "G_GDP = pd.read_csv('GlobalGDP.csv')G_GDP.head()"
},
{
"code": null,
"e": 5208,
"s": 5164,
"text": "So again, let’s define the data and layout."
},
{
"code": null,
"e": 5356,
"s": 5208,
"text": "data = dict(type='choropleth', locations = G_GDP['CODE'], z = G_GDP['GDP (BILLIONS)'], text = G_GDP['COUNTRY'])"
},
{
"code": null,
"e": 5467,
"s": 5356,
"text": "As we’re plotting a map on a global scale, layout will now consist of the projections attribute and not scope."
},
{
"code": null,
"e": 5748,
"s": 5467,
"text": "layout = dict(title = 'Global GDP - hammer projection', geo = dict( projection = {'type':'hammer'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 6119,
"s": 5748,
"text": "What’s fun with these plots is that you can zoom into, swipe through, and view the data plotted around the globe conveniently. This is because of our projection type: hammer. We can view the same data using other projection types as well such as natural earth, robinson, mercator, stereographic etc. The code and output for few of these projection types are given below."
},
{
"code": null,
"e": 6407,
"s": 6119,
"text": "layout = dict(title = 'Global GDP - robinson projection', geo = dict( projection = {'type':'robinson'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout) po.iplot(x)"
},
{
"code": null,
"e": 6704,
"s": 6407,
"text": "layout = dict(title = 'Global GDP - natural earth projection', geo = dict( projection = {'type':'natural earth'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 6986,
"s": 6704,
"text": "layout = dict(title = 'Global GDP - mercator projection', geo = dict(projection = {'type':'mercator'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 7278,
"s": 6986,
"text": "layout = dict(title = 'Global GDP - stereographic projection', geo = dict(projection = {'type':'stereographic'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 7569,
"s": 7278,
"text": "layout = dict(title = 'Global GDP - orthographic projection', geo = dict( projection = {'type':'orthographic'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 7631,
"s": 7569,
"text": "You can remove the boundaries to your projections as follows:"
},
{
"code": null,
"e": 7957,
"s": 7631,
"text": "layout = dict(title = 'Global GDP - robinson projection without borders', geo = dict(showframe = False, projection = {'type':'robinson'}, showlakes = True, lakecolor = 'rgb(0,191,255)'))x = pg.Figure(data = [data], layout = layout)po.iplot(x)"
},
{
"code": null,
"e": 8053,
"s": 7957,
"text": "To learn more about Plotly's map configurations and styling you can refer to its documentation."
},
{
"code": null,
"e": 8103,
"s": 8053,
"text": "The whole code to this article can be found here."
},
{
"code": null,
"e": 8175,
"s": 8103,
"text": "I hope this quick tutorial was helpful. Thank you for giving it a read!"
}
] |
SciPy Statistical Significance Tests | In statistics, statistical significance means that the result that was produced has a reason behind it, it was not produced randomly, or by chance.
SciPy provides us with a module called scipy.stats, which has functions for performing statistical significance tests.
Here are some techniques and keywords that are important when performing such tests:
Hypothesis is an assumption about a parameter in population.
It assumes that the observation is not statistically significant.
It assumes that the observations are due to some reason.
Its alternate to Null Hypothesis.
Example:
For an assessment of a student we would take:
"student is worse than average" - as a null hypothesis,
and:
"student is better than average" - as an alternate hypothesis.
When our hypothesis is testing for one side of the value only, it is called "one tailed test".
Example:
For the null hypothesis:
"the mean is equal to k", we can have alternate hypothesis:
"the mean is less than k", or:
"the mean is greater than k"
When our hypothesis is testing for both side of the values.
Example:
For the null hypothesis:
"the mean is equal to k", we can have alternate hypothesis:
"the mean is not equal to k"
In this case the mean is less than, or greater than k, and both sides are to be checked.
Alpha value is the level of significance.
Example:
How close to extremes the data must be for null hypothesis to be rejected.
It is usually taken as 0.01, 0.05, or 0.1.
P value tells how close to extreme the data actually is.
P value and alpha values are compared to establish the statistical significance.
If p value <= alpha we reject the null hypothesis and say that the data is statistically significant.
otherwise we accept the null hypothesis.
T-tests are used to determine if there is significant deference between means of two variables.
and lets us know if they belong to the same distribution.
It is a two tailed test.
The function ttest_ind() takes two samples of same size and produces a tuple of t-statistic and p-value.
Find if the given values v1 and v2 are from same distribution:
Ttest_indResult(statistic=0.40833510339674095, pvalue=0.68346891833752133)
If you want to return only the p-value, use the pvalue property:
0.68346891833752133
KS test is used to check if given values follow a distribution.
The function takes the value to be tested, and the CDF as two parameters.
A CDF can be either a string or a callable function that returns the probability.
It can be used as a one tailed or two tailed test.
By default it is two tailed. We can pass parameter alternative as a string of one of two-sided, less, or greater.
Find if the given value follows the normal distribution:
KstestResult(statistic=0.047798701221956841, pvalue=0.97630967161777515)
In order to see a summary of values in an array, we can use the describe() function.
It returns the following description:
number of observations (nobs)
minimum and maximum values = minmax
mean
variance
skewness
kurtosis
number of observations (nobs)
minimum and maximum values = minmax
mean
variance
skewness
kurtosis
Show statistical description of the values in an array:
DescribeResult(
nobs=100,
minmax=(-2.0991855456740121, 2.1304142707414964),
mean=0.11503747689121079,
variance=0.99418092655064605,
skewness=0.013953400984243667,
kurtosis=-0.671060517912661
)
Normality tests are based on the skewness and kurtosis.
The normaltest() function returns p value for the null hypothesis:
"x comes from a normal distribution".
A measure of symmetry in data.
For normal distributions it is 0.
If it is negative, it means the data is skewed left.
If it is positive it means the data is skewed right.
A measure of whether the data is heavy or lightly tailed to a normal distribution.
Positive kurtosis means heavy tailed.
Negative kurtosis means lightly tailed.
Find skewness and kurtosis of values in an array:
0.11168446328610283
-0.1879320563260931
Find if the data comes from a normal distribution:
NormaltestResult(statistic=4.4783745697002848, pvalue=0.10654505998635538)
Insert the missing method to meassure the summetry in data:
import numpy as np
from scipy.stats import skew, kurtosis
v = np.random.normal(size=100)
print((v))
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 148,
"s": 0,
"text": "In statistics, statistical significance means that the result that was produced has a reason behind it, it was not produced randomly, or by chance."
},
{
"code": null,
"e": 269,
"s": 148,
"text": "SciPy provides us with a module called scipy.stats, which has functions for performing statistical significance tests.\n\n"
},
{
"code": null,
"e": 354,
"s": 269,
"text": "Here are some techniques and keywords that are important when performing such tests:"
},
{
"code": null,
"e": 415,
"s": 354,
"text": "Hypothesis is an assumption about a parameter in population."
},
{
"code": null,
"e": 481,
"s": 415,
"text": "It assumes that the observation is not statistically significant."
},
{
"code": null,
"e": 538,
"s": 481,
"text": "It assumes that the observations are due to some reason."
},
{
"code": null,
"e": 572,
"s": 538,
"text": "Its alternate to Null Hypothesis."
},
{
"code": null,
"e": 581,
"s": 572,
"text": "Example:"
},
{
"code": null,
"e": 627,
"s": 581,
"text": "For an assessment of a student we would take:"
},
{
"code": null,
"e": 688,
"s": 627,
"text": "\"student is worse than average\" - as a null hypothesis,\nand:"
},
{
"code": null,
"e": 751,
"s": 688,
"text": "\"student is better than average\" - as an alternate hypothesis."
},
{
"code": null,
"e": 846,
"s": 751,
"text": "When our hypothesis is testing for one side of the value only, it is called \"one tailed test\"."
},
{
"code": null,
"e": 855,
"s": 846,
"text": "Example:"
},
{
"code": null,
"e": 880,
"s": 855,
"text": "For the null hypothesis:"
},
{
"code": null,
"e": 940,
"s": 880,
"text": "\"the mean is equal to k\", we can have alternate hypothesis:"
},
{
"code": null,
"e": 971,
"s": 940,
"text": "\"the mean is less than k\", or:"
},
{
"code": null,
"e": 1000,
"s": 971,
"text": "\"the mean is greater than k\""
},
{
"code": null,
"e": 1060,
"s": 1000,
"text": "When our hypothesis is testing for both side of the values."
},
{
"code": null,
"e": 1069,
"s": 1060,
"text": "Example:"
},
{
"code": null,
"e": 1094,
"s": 1069,
"text": "For the null hypothesis:"
},
{
"code": null,
"e": 1154,
"s": 1094,
"text": "\"the mean is equal to k\", we can have alternate hypothesis:"
},
{
"code": null,
"e": 1183,
"s": 1154,
"text": "\"the mean is not equal to k\""
},
{
"code": null,
"e": 1272,
"s": 1183,
"text": "In this case the mean is less than, or greater than k, and both sides are to be checked."
},
{
"code": null,
"e": 1314,
"s": 1272,
"text": "Alpha value is the level of significance."
},
{
"code": null,
"e": 1323,
"s": 1314,
"text": "Example:"
},
{
"code": null,
"e": 1398,
"s": 1323,
"text": "How close to extremes the data must be for null hypothesis to be rejected."
},
{
"code": null,
"e": 1441,
"s": 1398,
"text": "It is usually taken as 0.01, 0.05, or 0.1."
},
{
"code": null,
"e": 1498,
"s": 1441,
"text": "P value tells how close to extreme the data actually is."
},
{
"code": null,
"e": 1579,
"s": 1498,
"text": "P value and alpha values are compared to establish the statistical significance."
},
{
"code": null,
"e": 1722,
"s": 1579,
"text": "If p value <= alpha we reject the null hypothesis and say that the data is statistically significant.\notherwise we accept the null hypothesis."
},
{
"code": null,
"e": 1876,
"s": 1722,
"text": "T-tests are used to determine if there is significant deference between means of two variables.\nand lets us know if they belong to the same distribution."
},
{
"code": null,
"e": 1901,
"s": 1876,
"text": "It is a two tailed test."
},
{
"code": null,
"e": 2006,
"s": 1901,
"text": "The function ttest_ind() takes two samples of same size and produces a tuple of t-statistic and p-value."
},
{
"code": null,
"e": 2069,
"s": 2006,
"text": "Find if the given values v1 and v2 are from same distribution:"
},
{
"code": null,
"e": 2151,
"s": 2071,
"text": "\n Ttest_indResult(statistic=0.40833510339674095, pvalue=0.68346891833752133)\n\n"
},
{
"code": null,
"e": 2216,
"s": 2151,
"text": "If you want to return only the p-value, use the pvalue property:"
},
{
"code": null,
"e": 2243,
"s": 2218,
"text": "\n 0.68346891833752133\n\n"
},
{
"code": null,
"e": 2307,
"s": 2243,
"text": "KS test is used to check if given values follow a distribution."
},
{
"code": null,
"e": 2381,
"s": 2307,
"text": "The function takes the value to be tested, and the CDF as two parameters."
},
{
"code": null,
"e": 2463,
"s": 2381,
"text": "A CDF can be either a string or a callable function that returns the probability."
},
{
"code": null,
"e": 2514,
"s": 2463,
"text": "It can be used as a one tailed or two tailed test."
},
{
"code": null,
"e": 2628,
"s": 2514,
"text": "By default it is two tailed. We can pass parameter alternative as a string of one of two-sided, less, or greater."
},
{
"code": null,
"e": 2685,
"s": 2628,
"text": "Find if the given value follows the normal distribution:"
},
{
"code": null,
"e": 2765,
"s": 2687,
"text": "\n KstestResult(statistic=0.047798701221956841, pvalue=0.97630967161777515)\n\n"
},
{
"code": null,
"e": 2850,
"s": 2765,
"text": "In order to see a summary of values in an array, we can use the describe() function."
},
{
"code": null,
"e": 2888,
"s": 2850,
"text": "It returns the following description:"
},
{
"code": null,
"e": 2988,
"s": 2888,
"text": "\nnumber of observations (nobs)\nminimum and maximum values = minmax\nmean\nvariance\nskewness\nkurtosis\n"
},
{
"code": null,
"e": 3018,
"s": 2988,
"text": "number of observations (nobs)"
},
{
"code": null,
"e": 3054,
"s": 3018,
"text": "minimum and maximum values = minmax"
},
{
"code": null,
"e": 3059,
"s": 3054,
"text": "mean"
},
{
"code": null,
"e": 3068,
"s": 3059,
"text": "variance"
},
{
"code": null,
"e": 3077,
"s": 3068,
"text": "skewness"
},
{
"code": null,
"e": 3086,
"s": 3077,
"text": "kurtosis"
},
{
"code": null,
"e": 3142,
"s": 3086,
"text": "Show statistical description of the values in an array:"
},
{
"code": null,
"e": 3368,
"s": 3144,
"text": "\n DescribeResult(\n nobs=100,\n minmax=(-2.0991855456740121, 2.1304142707414964),\n mean=0.11503747689121079,\n variance=0.99418092655064605,\n skewness=0.013953400984243667,\n kurtosis=-0.671060517912661\n )\n\n"
},
{
"code": null,
"e": 3424,
"s": 3368,
"text": "Normality tests are based on the skewness and kurtosis."
},
{
"code": null,
"e": 3491,
"s": 3424,
"text": "The normaltest() function returns p value for the null hypothesis:"
},
{
"code": null,
"e": 3529,
"s": 3491,
"text": "\"x comes from a normal distribution\"."
},
{
"code": null,
"e": 3560,
"s": 3529,
"text": "A measure of symmetry in data."
},
{
"code": null,
"e": 3594,
"s": 3560,
"text": "For normal distributions it is 0."
},
{
"code": null,
"e": 3647,
"s": 3594,
"text": "If it is negative, it means the data is skewed left."
},
{
"code": null,
"e": 3700,
"s": 3647,
"text": "If it is positive it means the data is skewed right."
},
{
"code": null,
"e": 3783,
"s": 3700,
"text": "A measure of whether the data is heavy or lightly tailed to a normal distribution."
},
{
"code": null,
"e": 3821,
"s": 3783,
"text": "Positive kurtosis means heavy tailed."
},
{
"code": null,
"e": 3861,
"s": 3821,
"text": "Negative kurtosis means lightly tailed."
},
{
"code": null,
"e": 3911,
"s": 3861,
"text": "Find skewness and kurtosis of values in an array:"
},
{
"code": null,
"e": 3960,
"s": 3913,
"text": "\n 0.11168446328610283\n -0.1879320563260931\n\n"
},
{
"code": null,
"e": 4011,
"s": 3960,
"text": "Find if the data comes from a normal distribution:"
},
{
"code": null,
"e": 4093,
"s": 4013,
"text": "\n NormaltestResult(statistic=4.4783745697002848, pvalue=0.10654505998635538)\n\n"
},
{
"code": null,
"e": 4153,
"s": 4093,
"text": "Insert the missing method to meassure the summetry in data:"
},
{
"code": null,
"e": 4256,
"s": 4153,
"text": "import numpy as np\nfrom scipy.stats import skew, kurtosis\n\nv = np.random.normal(size=100)\n\nprint((v))\n"
},
{
"code": null,
"e": 4275,
"s": 4256,
"text": "Start the Exercise"
},
{
"code": null,
"e": 4308,
"s": 4275,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 4350,
"s": 4308,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 4457,
"s": 4350,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 4476,
"s": 4457,
"text": "[email protected]"
}
] |
How to create custom actionbar in android? | Before getting into example we should know what is action bar in android. Action bar just like header in android. Either we can use same action bar for all screen or we can change action bar for particular activity.
This example demonstrate about how to create a custom action bar in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Custom Action Bar"
android:textSize = "20sp"/>
</LinearLayout>
Step 2 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_action_bar);
//getSupportActionBar().setElevation(0);
View view = getSupportActionBar().getCustomView();
TextView name = view.findViewById(R.id.name);
name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "You have clicked tittle", Toast.LENGTH_LONG).show();
}
});
}
}
Step 3 − Create a layout for action bar in res folder as custom_action_bar.xml shown below
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center_vertical"
android:padding = "10dp"
android:weightSum = "1">
<LinearLayout
android:layout_width = "0dp"
android:layout_height = "match_parent"
android:layout_weight = "0.6">
<ImageView
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:src = "@drawable/ic_face_red_400_24dp" />
<TextView
android:id = "@+id/name"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginLeft = "10dp"
android:text = "Instagram"
android:textSize = "20sp"
android:textColor = "#000"
android:textStyle = "bold"
app:fontFamily = "@font/allan_bold" />
</LinearLayout>
<LinearLayout
android:layout_width = "0dp"
android:layout_height = "match_parent"
android:layout_marginRight = "10dp"
android:layout_weight = "0.4"
android:gravity = "end">
<ImageView
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:src = "@drawable/ic_local_post_office_red_400_24dp" />
<ImageView
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:layout_marginLeft = "20dp"
android:src = "@drawable/ic_send_red_400_24dp" />
</LinearLayout>
</LinearLayout>
Note − According to the project / application specification we need to change the custom layout.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
To remove action bar button shadow use the following code in onCreate() in MainActivity as shown below
this.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_action_bar);
getSupportActionBar().setElevation(0);
View view = getSupportActionBar().getCustomView();
Now run your application, it will give output as shown below −
Click here to download the project code | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "Before getting into example we should know what is action bar in android. Action bar just like header in android. Either we can use same action bar for all screen or we can change action bar for particular activity."
},
{
"code": null,
"e": 1355,
"s": 1278,
"text": "This example demonstrate about how to create a custom action bar in Android."
},
{
"code": null,
"e": 1484,
"s": 1355,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1549,
"s": 1484,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2031,
"s": 1549,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Custom Action Bar\"\n android:textSize = \"20sp\"/>\n</LinearLayout>"
},
{
"code": null,
"e": 2088,
"s": 2031,
"text": "Step 2 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3120,
"s": 2088,
"text": "import android.os.Bundle;\nimport android.support.v7.app.ActionBar;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n this.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);\n getSupportActionBar().setDisplayShowCustomEnabled(true);\n getSupportActionBar().setCustomView(R.layout.custom_action_bar);\n //getSupportActionBar().setElevation(0);\n View view = getSupportActionBar().getCustomView();\n TextView name = view.findViewById(R.id.name);\n name.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(MainActivity.this, \"You have clicked tittle\", Toast.LENGTH_LONG).show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 3211,
"s": 3120,
"text": "Step 3 − Create a layout for action bar in res folder as custom_action_bar.xml shown below"
},
{
"code": null,
"e": 4881,
"s": 3211,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center_vertical\"\n android:padding = \"10dp\"\n android:weightSum = \"1\">\n <LinearLayout\n android:layout_width = \"0dp\"\n android:layout_height = \"match_parent\"\n android:layout_weight = \"0.6\">\n <ImageView\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:src = \"@drawable/ic_face_red_400_24dp\" />\n <TextView\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_marginLeft = \"10dp\"\n android:text = \"Instagram\"\n android:textSize = \"20sp\"\n android:textColor = \"#000\"\n android:textStyle = \"bold\"\n app:fontFamily = \"@font/allan_bold\" />\n </LinearLayout>\n <LinearLayout\n android:layout_width = \"0dp\"\n android:layout_height = \"match_parent\"\n android:layout_marginRight = \"10dp\"\n android:layout_weight = \"0.4\"\n android:gravity = \"end\">\n <ImageView\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:src = \"@drawable/ic_local_post_office_red_400_24dp\" />\n <ImageView\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:layout_marginLeft = \"20dp\"\n android:src = \"@drawable/ic_send_red_400_24dp\" />\n </LinearLayout>\n</LinearLayout>"
},
{
"code": null,
"e": 4978,
"s": 4881,
"text": "Note − According to the project / application specification we need to change the custom layout."
},
{
"code": null,
"e": 5325,
"s": 4978,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
},
{
"code": null,
"e": 5428,
"s": 5325,
"text": "To remove action bar button shadow use the following code in onCreate() in MainActivity as shown below"
},
{
"code": null,
"e": 5717,
"s": 5428,
"text": "this.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);\ngetSupportActionBar().setDisplayShowCustomEnabled(true);\ngetSupportActionBar().setCustomView(R.layout.custom_action_bar);\ngetSupportActionBar().setElevation(0);\nView view = getSupportActionBar().getCustomView();"
},
{
"code": null,
"e": 5780,
"s": 5717,
"text": "Now run your application, it will give output as shown below −"
},
{
"code": null,
"e": 5820,
"s": 5780,
"text": "Click here to download the project code"
}
] |
The “Bias-Variance Trade-Off” Explained Practically (In Python) | by Samuele Mazzanti | Towards Data Science | The “bias-variance trade-off” is one of the most frequent topics in data science interviews. Still, many candidates struggle to understand the concept in depth. I guess it happens because this topic is always explained from a fully theoretical point of view.
However, I believe that the best way to understand something is to do it yourself — or, better, to code it yourself.
You don’t really understand it, until you can’t code it!
In this article, with the aid of some data, we will see what the bias-variance trade-off means in practice, and how to compute it in Python (both from scratch and using an out-of-the-box implementation).
The usual definition of the Bias-Variance decomposition is:
where MSE stands for Mean Squared Error and θ represent the parameters of the model (for instance, in linear regression, θ would be the vector containing all the regression coefficients).
But there is a problem: we can never observe the true value of θ. Moreover, in some models, it’s not possible to find explicitly what θ is. So this definition is quite useless from a practical point of view.
However, what we observe in real life is the ground truth, which is the realization of the target variable on some test data (often called y). So, from our perspective, it makes much more sense to replace θ with y, and obtain the following equation:
where:
This formula is much more convenient because in a real-life setting we actually know all these quantities.
Also, with this version of the formula, we are able to give a more informal interpretation of MSE, Variance and Bias:
This decomposition is often used to explain how the outcome of a model changes based on its “flexibility”.
Low flexibility. All the estimated models tend to be similar, thus Variance is small. On the other hand, the “average model” is not powerful enough to get close to the ground truth, thus Bias is large.
High flexibility. Each model depends heavily on the specific observations it has been trained on, so the models are very different from each other, thus Variance is large. However, in the long run, flexibility allows you to take into account all the small details. As a consequence, averaging all the models allow us to get a very precise “average model”, thus Bias is small.
This is the essence of the trade-off: if the complexity is too low or too high we will have a high Mean Squared Error respectively due to Bias or Variance. The point is how to get model flexibility just right, in order to minimize both Bias and Variance at the same time.
At this point, you are probably wondering what it means to get different models (and an “average model”).
Suppose you pick an algorithm (for example Scikit-learn’s DecisionTreeRegressor) and set its hyperparameters like this:
from sklearn.tree import DecisionTreeRegressoralgo = DecisionTreeRegressor(min_samples_leaf = 10)
At this point, you can obtain infinite possible models, based on the specific training dataset on which you train the algorithm.
Suppose you could draw many different training datasets, and train a different model for each of them. Then, you could take the average of the predictions made by each model: this is what we call the “average model”.
import pandas as pd# initialize dataframe for storing predictions on test datapreds_test = pd.DataFrame(index = y_test.index)# for each model: draw training dataset, fit model on training dataset and make predictions on test datafor i in range(1, n_models + 1): X_train, y_train = draw_training_dataset() model = algo.fit(X_train, y_train) preds_test[f'Model {i}'] = model.predict(X_test)# calculate "average model"'s predictionsmean_pred_test = preds_test.mean(axis = 1)
Now that we have all the quantities that we need, we can finally compute Mean Squared Error, (squared) Bias and Variance.
from sklearn.metrics import mean_squared_errormse = preds_test.apply(lambda pred_test: mean_squared_error(y_test, pred_test)).mean()bias_squared = mean_squared_error(y_test, mean_pred_test)variance = preds_test.apply(lambda pred_test: mean_squared_error(mean_pred_test, pred_test)).mean()
This is a conceptual sketch of the process we have just followed:
Let’s see an output example for 3 models and 5 test observations:
But there’s a problem.
In the code above, we have used a fictitious function called draw_training_dataset(). However, in real life, we cannot actually draw training datasets from an infinite sample space. In fact, we usually have just one training dataset. How to make up?
The trick is to bootstrap (i.e. to randomly draw with replacement) rows from our training dataset. So the process becomes:
Now we are ready to wrap everything together and write a Python function for computing bias and variance of an estimator. All we need to do is to take the code snippets above and replace the function draw_training_dataset() with the bootstrap procedure.
This is a solution:
import numpy as npimport pandas as pdfrom sklearn.metrics import mean_squared_errordef bias_variance_estimate( estimator, X_train, y_train, X_test, y_test, bootstrap_rounds = 100): # initialize dataframe for storing predictions on test data preds_test = pd.DataFrame(index = y_test.index) # for each round: draw bootstrap indices, train model on bootstrap data and make predictions on test data for r in range(bootstrap_rounds): boot = np.random.randint(len(y_train), size = len(y_train)) preds_test[f'Model {r}'] = estimator.fit(X_train.iloc[boot, :], y_train.iloc[boot]).predict(X_test) # calculate "average model"'s predictions mean_pred_test = preds_test.mean(axis = 1) # compute and return: mse, squared bias and variance mse = preds_test.apply(lambda pred_test: mean_squared_error(y_test, pred_test)).mean() bias_squared = mean_squared_error(y_test, mean_pred_test) variance = preds_test.apply(lambda pred_test: mean_squared_error(mean_pred_test, pred_test)).mean() return mse, bias_squared, variance
In order to see the bias-variance decomposition at work, let’s use it on some real data: the house prices dataset from Kaggle. The dataset is made of 79 predictors (such as building class, general zoning classification, linear feet of street connected to property, lot size in square feet, and so on), and the objective is to predict the final sale price (which is in thousands of dollars).
Let’s take a predictive algorithm, for instance Scikit-learn’s DecisionTreeRegressor and see how Bias and Variance change according to model’s flexibility.
But what does model’s flexibility mean? The answer depends on the specific algorithm and its hyperparameters.
In the case of DecisionTreeRegressor, we can take, for instance, min_samples_leaf. This hyperparameter determines the minimum number of samples that can end up in any terminal leaf of the decision tree. Thus:
When min_samples_leaf is high, it means that we will have few terminal leaves, each containing many samples. Therefore, the model is not flexible, because it is forced to put many different samples together.
When min_samples_leaf is low, it means that the tree is very deep. The model is then very flexible, because it is allowed to make a different prediction for any few samples.
So the idea is to make an estimate of Bias and Variance for different choices of min_samples_leaf.
We could use the function we have created previously. Alternatively, we can use the function bias_variance_decomp from the library mlxtend (here you can find a beautifully written documentation).
import pandas as pdfrom mlxtend.evaluate import bias_variance_decompout = pd.DataFrame(columns = ['MSE', 'Bias^2', 'Variance'])for min_samples_leaf in list(range(1, 11)) + list(range(15, 105, 5)): model = DecisionTreeRegressor(min_samples_leaf = min_samples_leaf) mse, bias, variance = bias_variance_decomp( model, X_train.to_numpy(), y_train.to_numpy(), X_test.to_numpy(), y_test.to_numpy(), loss = 'mse' ) out.loc[min_samples_leaf, 'Bias^2'] = bias out.loc[min_samples_leaf, 'Variance'] = variance out.loc[min_samples_leaf, 'MSE'] = mse
This is the outcome:
It’s exactly what we expected: when the flexibility of the model increases (i.e. when min_samples_leaf decreases), Bias tends to reduce, but Variance tends to grow. This is the essence of the trade-off. Finding the right balance between the two extremes is the mission of any data scientist.
Thank you for reading! I hope this walkthrough has helped you to understand the bias-variance trade-off in depth.
I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can text me at my Linkedin contact. | [
{
"code": null,
"e": 431,
"s": 172,
"text": "The “bias-variance trade-off” is one of the most frequent topics in data science interviews. Still, many candidates struggle to understand the concept in depth. I guess it happens because this topic is always explained from a fully theoretical point of view."
},
{
"code": null,
"e": 548,
"s": 431,
"text": "However, I believe that the best way to understand something is to do it yourself — or, better, to code it yourself."
},
{
"code": null,
"e": 605,
"s": 548,
"text": "You don’t really understand it, until you can’t code it!"
},
{
"code": null,
"e": 809,
"s": 605,
"text": "In this article, with the aid of some data, we will see what the bias-variance trade-off means in practice, and how to compute it in Python (both from scratch and using an out-of-the-box implementation)."
},
{
"code": null,
"e": 869,
"s": 809,
"text": "The usual definition of the Bias-Variance decomposition is:"
},
{
"code": null,
"e": 1057,
"s": 869,
"text": "where MSE stands for Mean Squared Error and θ represent the parameters of the model (for instance, in linear regression, θ would be the vector containing all the regression coefficients)."
},
{
"code": null,
"e": 1265,
"s": 1057,
"text": "But there is a problem: we can never observe the true value of θ. Moreover, in some models, it’s not possible to find explicitly what θ is. So this definition is quite useless from a practical point of view."
},
{
"code": null,
"e": 1515,
"s": 1265,
"text": "However, what we observe in real life is the ground truth, which is the realization of the target variable on some test data (often called y). So, from our perspective, it makes much more sense to replace θ with y, and obtain the following equation:"
},
{
"code": null,
"e": 1522,
"s": 1515,
"text": "where:"
},
{
"code": null,
"e": 1629,
"s": 1522,
"text": "This formula is much more convenient because in a real-life setting we actually know all these quantities."
},
{
"code": null,
"e": 1747,
"s": 1629,
"text": "Also, with this version of the formula, we are able to give a more informal interpretation of MSE, Variance and Bias:"
},
{
"code": null,
"e": 1854,
"s": 1747,
"text": "This decomposition is often used to explain how the outcome of a model changes based on its “flexibility”."
},
{
"code": null,
"e": 2056,
"s": 1854,
"text": "Low flexibility. All the estimated models tend to be similar, thus Variance is small. On the other hand, the “average model” is not powerful enough to get close to the ground truth, thus Bias is large."
},
{
"code": null,
"e": 2432,
"s": 2056,
"text": "High flexibility. Each model depends heavily on the specific observations it has been trained on, so the models are very different from each other, thus Variance is large. However, in the long run, flexibility allows you to take into account all the small details. As a consequence, averaging all the models allow us to get a very precise “average model”, thus Bias is small."
},
{
"code": null,
"e": 2704,
"s": 2432,
"text": "This is the essence of the trade-off: if the complexity is too low or too high we will have a high Mean Squared Error respectively due to Bias or Variance. The point is how to get model flexibility just right, in order to minimize both Bias and Variance at the same time."
},
{
"code": null,
"e": 2810,
"s": 2704,
"text": "At this point, you are probably wondering what it means to get different models (and an “average model”)."
},
{
"code": null,
"e": 2930,
"s": 2810,
"text": "Suppose you pick an algorithm (for example Scikit-learn’s DecisionTreeRegressor) and set its hyperparameters like this:"
},
{
"code": null,
"e": 3028,
"s": 2930,
"text": "from sklearn.tree import DecisionTreeRegressoralgo = DecisionTreeRegressor(min_samples_leaf = 10)"
},
{
"code": null,
"e": 3157,
"s": 3028,
"text": "At this point, you can obtain infinite possible models, based on the specific training dataset on which you train the algorithm."
},
{
"code": null,
"e": 3374,
"s": 3157,
"text": "Suppose you could draw many different training datasets, and train a different model for each of them. Then, you could take the average of the predictions made by each model: this is what we call the “average model”."
},
{
"code": null,
"e": 3849,
"s": 3374,
"text": "import pandas as pd# initialize dataframe for storing predictions on test datapreds_test = pd.DataFrame(index = y_test.index)# for each model: draw training dataset, fit model on training dataset and make predictions on test datafor i in range(1, n_models + 1): X_train, y_train = draw_training_dataset() model = algo.fit(X_train, y_train) preds_test[f'Model {i}'] = model.predict(X_test)# calculate \"average model\"'s predictionsmean_pred_test = preds_test.mean(axis = 1)"
},
{
"code": null,
"e": 3971,
"s": 3849,
"text": "Now that we have all the quantities that we need, we can finally compute Mean Squared Error, (squared) Bias and Variance."
},
{
"code": null,
"e": 4260,
"s": 3971,
"text": "from sklearn.metrics import mean_squared_errormse = preds_test.apply(lambda pred_test: mean_squared_error(y_test, pred_test)).mean()bias_squared = mean_squared_error(y_test, mean_pred_test)variance = preds_test.apply(lambda pred_test: mean_squared_error(mean_pred_test, pred_test)).mean()"
},
{
"code": null,
"e": 4326,
"s": 4260,
"text": "This is a conceptual sketch of the process we have just followed:"
},
{
"code": null,
"e": 4392,
"s": 4326,
"text": "Let’s see an output example for 3 models and 5 test observations:"
},
{
"code": null,
"e": 4415,
"s": 4392,
"text": "But there’s a problem."
},
{
"code": null,
"e": 4665,
"s": 4415,
"text": "In the code above, we have used a fictitious function called draw_training_dataset(). However, in real life, we cannot actually draw training datasets from an infinite sample space. In fact, we usually have just one training dataset. How to make up?"
},
{
"code": null,
"e": 4788,
"s": 4665,
"text": "The trick is to bootstrap (i.e. to randomly draw with replacement) rows from our training dataset. So the process becomes:"
},
{
"code": null,
"e": 5042,
"s": 4788,
"text": "Now we are ready to wrap everything together and write a Python function for computing bias and variance of an estimator. All we need to do is to take the code snippets above and replace the function draw_training_dataset() with the bootstrap procedure."
},
{
"code": null,
"e": 5062,
"s": 5042,
"text": "This is a solution:"
},
{
"code": null,
"e": 6109,
"s": 5062,
"text": "import numpy as npimport pandas as pdfrom sklearn.metrics import mean_squared_errordef bias_variance_estimate( estimator, X_train, y_train, X_test, y_test, bootstrap_rounds = 100): # initialize dataframe for storing predictions on test data preds_test = pd.DataFrame(index = y_test.index) # for each round: draw bootstrap indices, train model on bootstrap data and make predictions on test data for r in range(bootstrap_rounds): boot = np.random.randint(len(y_train), size = len(y_train)) preds_test[f'Model {r}'] = estimator.fit(X_train.iloc[boot, :], y_train.iloc[boot]).predict(X_test) # calculate \"average model\"'s predictions mean_pred_test = preds_test.mean(axis = 1) # compute and return: mse, squared bias and variance mse = preds_test.apply(lambda pred_test: mean_squared_error(y_test, pred_test)).mean() bias_squared = mean_squared_error(y_test, mean_pred_test) variance = preds_test.apply(lambda pred_test: mean_squared_error(mean_pred_test, pred_test)).mean() return mse, bias_squared, variance"
},
{
"code": null,
"e": 6500,
"s": 6109,
"text": "In order to see the bias-variance decomposition at work, let’s use it on some real data: the house prices dataset from Kaggle. The dataset is made of 79 predictors (such as building class, general zoning classification, linear feet of street connected to property, lot size in square feet, and so on), and the objective is to predict the final sale price (which is in thousands of dollars)."
},
{
"code": null,
"e": 6656,
"s": 6500,
"text": "Let’s take a predictive algorithm, for instance Scikit-learn’s DecisionTreeRegressor and see how Bias and Variance change according to model’s flexibility."
},
{
"code": null,
"e": 6766,
"s": 6656,
"text": "But what does model’s flexibility mean? The answer depends on the specific algorithm and its hyperparameters."
},
{
"code": null,
"e": 6975,
"s": 6766,
"text": "In the case of DecisionTreeRegressor, we can take, for instance, min_samples_leaf. This hyperparameter determines the minimum number of samples that can end up in any terminal leaf of the decision tree. Thus:"
},
{
"code": null,
"e": 7183,
"s": 6975,
"text": "When min_samples_leaf is high, it means that we will have few terminal leaves, each containing many samples. Therefore, the model is not flexible, because it is forced to put many different samples together."
},
{
"code": null,
"e": 7357,
"s": 7183,
"text": "When min_samples_leaf is low, it means that the tree is very deep. The model is then very flexible, because it is allowed to make a different prediction for any few samples."
},
{
"code": null,
"e": 7456,
"s": 7357,
"text": "So the idea is to make an estimate of Bias and Variance for different choices of min_samples_leaf."
},
{
"code": null,
"e": 7652,
"s": 7456,
"text": "We could use the function we have created previously. Alternatively, we can use the function bias_variance_decomp from the library mlxtend (here you can find a beautifully written documentation)."
},
{
"code": null,
"e": 8219,
"s": 7652,
"text": "import pandas as pdfrom mlxtend.evaluate import bias_variance_decompout = pd.DataFrame(columns = ['MSE', 'Bias^2', 'Variance'])for min_samples_leaf in list(range(1, 11)) + list(range(15, 105, 5)): model = DecisionTreeRegressor(min_samples_leaf = min_samples_leaf) mse, bias, variance = bias_variance_decomp( model, X_train.to_numpy(), y_train.to_numpy(), X_test.to_numpy(), y_test.to_numpy(), loss = 'mse' ) out.loc[min_samples_leaf, 'Bias^2'] = bias out.loc[min_samples_leaf, 'Variance'] = variance out.loc[min_samples_leaf, 'MSE'] = mse"
},
{
"code": null,
"e": 8240,
"s": 8219,
"text": "This is the outcome:"
},
{
"code": null,
"e": 8532,
"s": 8240,
"text": "It’s exactly what we expected: when the flexibility of the model increases (i.e. when min_samples_leaf decreases), Bias tends to reduce, but Variance tends to grow. This is the essence of the trade-off. Finding the right balance between the two extremes is the mission of any data scientist."
},
{
"code": null,
"e": 8646,
"s": 8532,
"text": "Thank you for reading! I hope this walkthrough has helped you to understand the bias-variance trade-off in depth."
}
] |
How can we merge two JSON arrays in Java? | A JSON is a lightweight data-interchange format and the format of JSON is a key with value pair. The JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can use org.json.simple.JSONArray class to merge two JSON arrays in Java.
We can merge two JSON arrays using the addAll() method (inherited from interface java.util.List) in the below program.
import org.json.simple.JSONArray;
import java.io.IOException;
public class MergeJSONArraysTest {
public static void main(String[] args) throws IOException {
JSONArray jsonArray1 = new JSONArray(); // first json array
jsonArray1.add("Java");
jsonArray1.add("Python");
jsonArray1.add("Spark");
JSONArray jsonArray2 = new JSONArray(); // second json array
jsonArray2.add("Selenium");
jsonArray2.add("ServiceNow");
jsonArray1.addAll(jsonArray2); // merge two arrays using addAll() method
System.out.println(jsonArray1);
}
}
["Java","Python","Spark","Selenium","ServiceNow"] | [
{
"code": null,
"e": 1350,
"s": 1062,
"text": "A JSON is a lightweight data-interchange format and the format of JSON is a key with value pair. The JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can use org.json.simple.JSONArray class to merge two JSON arrays in Java."
},
{
"code": null,
"e": 1469,
"s": 1350,
"text": "We can merge two JSON arrays using the addAll() method (inherited from interface java.util.List) in the below program."
},
{
"code": null,
"e": 2049,
"s": 1469,
"text": "import org.json.simple.JSONArray;\nimport java.io.IOException;\npublic class MergeJSONArraysTest {\n public static void main(String[] args) throws IOException {\n JSONArray jsonArray1 = new JSONArray(); // first json array\n jsonArray1.add(\"Java\");\n jsonArray1.add(\"Python\");\n jsonArray1.add(\"Spark\");\n JSONArray jsonArray2 = new JSONArray(); // second json array\n jsonArray2.add(\"Selenium\");\n jsonArray2.add(\"ServiceNow\");\n jsonArray1.addAll(jsonArray2); // merge two arrays using addAll() method\n System.out.println(jsonArray1);\n }\n}"
},
{
"code": null,
"e": 2099,
"s": 2049,
"text": "[\"Java\",\"Python\",\"Spark\",\"Selenium\",\"ServiceNow\"]"
}
] |
Program to perform an Inorder Traversal of a binary tree in Python | Suppose we have a binary tree; we have to find a list that contains the inorder traversal of root as a list. As we know the inorder traversal is a way of traversing all nodes in a tree where we −
Recursively traverse the left subtree.
Recursively traverse the left subtree.
Traverse the current node.
Traverse the current node.
Recursively traverse the right subtree.
Recursively traverse the right subtree.
We have to try to solve this problem in iterative fashion.
So, if the input is like
then the output will be [12,13,4,16,7,14,22]
To solve this, we will follow these steps −
inorder := a new list
inorder := a new list
stack := an empty stack
stack := an empty stack
Do the following infinitely, doif root is not null, thenpush root into the stackroot := left of roototherwise when stack is not empty, thenroot := top element of stack and pop from stackinsert value of root at the end of inorderroot := right of roototherwise,come out from the loop
Do the following infinitely, do
if root is not null, thenpush root into the stackroot := left of root
if root is not null, then
push root into the stack
push root into the stack
root := left of root
root := left of root
otherwise when stack is not empty, thenroot := top element of stack and pop from stackinsert value of root at the end of inorderroot := right of root
otherwise when stack is not empty, then
root := top element of stack and pop from stack
root := top element of stack and pop from stack
insert value of root at the end of inorder
insert value of root at the end of inorder
root := right of root
root := right of root
otherwise,come out from the loop
otherwise,
come out from the loop
come out from the loop
return inorder
return inorder
Let us see the following implementation to get better understanding −
Live Demo
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Solution:
def solve(self, root):
inorder = []
stack = []
while True:
if root:
stack.append(root)
root = root.left
elif stack:
root = stack.pop()
inorder.append(root.val)
root = root.right
else:
break
return inorder
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print(ob.solve(root))
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
[12, 13, 4, 16, 7, 14, 22] | [
{
"code": null,
"e": 1258,
"s": 1062,
"text": "Suppose we have a binary tree; we have to find a list that contains the inorder traversal of root as a list. As we know the inorder traversal is a way of traversing all nodes in a tree where we −"
},
{
"code": null,
"e": 1297,
"s": 1258,
"text": "Recursively traverse the left subtree."
},
{
"code": null,
"e": 1336,
"s": 1297,
"text": "Recursively traverse the left subtree."
},
{
"code": null,
"e": 1363,
"s": 1336,
"text": "Traverse the current node."
},
{
"code": null,
"e": 1390,
"s": 1363,
"text": "Traverse the current node."
},
{
"code": null,
"e": 1430,
"s": 1390,
"text": "Recursively traverse the right subtree."
},
{
"code": null,
"e": 1470,
"s": 1430,
"text": "Recursively traverse the right subtree."
},
{
"code": null,
"e": 1529,
"s": 1470,
"text": "We have to try to solve this problem in iterative fashion."
},
{
"code": null,
"e": 1554,
"s": 1529,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1599,
"s": 1554,
"text": "then the output will be [12,13,4,16,7,14,22]"
},
{
"code": null,
"e": 1643,
"s": 1599,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1665,
"s": 1643,
"text": "inorder := a new list"
},
{
"code": null,
"e": 1687,
"s": 1665,
"text": "inorder := a new list"
},
{
"code": null,
"e": 1711,
"s": 1687,
"text": "stack := an empty stack"
},
{
"code": null,
"e": 1735,
"s": 1711,
"text": "stack := an empty stack"
},
{
"code": null,
"e": 2017,
"s": 1735,
"text": "Do the following infinitely, doif root is not null, thenpush root into the stackroot := left of roototherwise when stack is not empty, thenroot := top element of stack and pop from stackinsert value of root at the end of inorderroot := right of roototherwise,come out from the loop"
},
{
"code": null,
"e": 2049,
"s": 2017,
"text": "Do the following infinitely, do"
},
{
"code": null,
"e": 2119,
"s": 2049,
"text": "if root is not null, thenpush root into the stackroot := left of root"
},
{
"code": null,
"e": 2145,
"s": 2119,
"text": "if root is not null, then"
},
{
"code": null,
"e": 2170,
"s": 2145,
"text": "push root into the stack"
},
{
"code": null,
"e": 2195,
"s": 2170,
"text": "push root into the stack"
},
{
"code": null,
"e": 2216,
"s": 2195,
"text": "root := left of root"
},
{
"code": null,
"e": 2237,
"s": 2216,
"text": "root := left of root"
},
{
"code": null,
"e": 2387,
"s": 2237,
"text": "otherwise when stack is not empty, thenroot := top element of stack and pop from stackinsert value of root at the end of inorderroot := right of root"
},
{
"code": null,
"e": 2427,
"s": 2387,
"text": "otherwise when stack is not empty, then"
},
{
"code": null,
"e": 2475,
"s": 2427,
"text": "root := top element of stack and pop from stack"
},
{
"code": null,
"e": 2523,
"s": 2475,
"text": "root := top element of stack and pop from stack"
},
{
"code": null,
"e": 2566,
"s": 2523,
"text": "insert value of root at the end of inorder"
},
{
"code": null,
"e": 2609,
"s": 2566,
"text": "insert value of root at the end of inorder"
},
{
"code": null,
"e": 2631,
"s": 2609,
"text": "root := right of root"
},
{
"code": null,
"e": 2653,
"s": 2631,
"text": "root := right of root"
},
{
"code": null,
"e": 2686,
"s": 2653,
"text": "otherwise,come out from the loop"
},
{
"code": null,
"e": 2697,
"s": 2686,
"text": "otherwise,"
},
{
"code": null,
"e": 2720,
"s": 2697,
"text": "come out from the loop"
},
{
"code": null,
"e": 2743,
"s": 2720,
"text": "come out from the loop"
},
{
"code": null,
"e": 2758,
"s": 2743,
"text": "return inorder"
},
{
"code": null,
"e": 2773,
"s": 2758,
"text": "return inorder"
},
{
"code": null,
"e": 2843,
"s": 2773,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2854,
"s": 2843,
"text": " Live Demo"
},
{
"code": null,
"e": 3561,
"s": 2854,
"text": "class TreeNode:\n def __init__(self, value):\n self.val = value\n self.left = None\n self.right = None\nclass Solution:\n def solve(self, root):\n inorder = []\n stack = []\n while True:\n if root:\n stack.append(root)\n root = root.left\n elif stack:\n root = stack.pop()\n inorder.append(root.val)\n root = root.right\n else:\n break\n return inorder\n\nob = Solution()\nroot = TreeNode(13)\nroot.left = TreeNode(12)\nroot.right = TreeNode(14)\nroot.right.left = TreeNode(16)\nroot.right.right = TreeNode(22)\nroot.right.left.left = TreeNode(4)\nroot.right.left.right = TreeNode(7)\nprint(ob.solve(root))"
},
{
"code": null,
"e": 3766,
"s": 3561,
"text": "root = TreeNode(13)\nroot.left = TreeNode(12)\nroot.right = TreeNode(14)\nroot.right.left = TreeNode(16)\nroot.right.right = TreeNode(22)\nroot.right.left.left = TreeNode(4)\nroot.right.left.right = TreeNode(7)"
},
{
"code": null,
"e": 3793,
"s": 3766,
"text": "[12, 13, 4, 16, 7, 14, 22]"
}
] |
Get the number of columns in a MySQL table? | To get the number of columns, use the aggregate function count(*) with information_schema table from MySQL. The syntax is as follows to find the number of columns −
SELECT COUNT(*) as anyVariableName from INFORMATION_SCHEMA.COLUMNS where table_schema = ’yourDatabaseName’ and table_name = ’yourTableName’;
To understand the above syntax, let us create a table with some columns. The following is the query to create a table −
mysql> create table CountColumns
−> (
−> Bookid int,
−> BookName varchar(200),
−> BookAuthorName varchar(200),
−> BookPublishedDate datetime
−> );
Query OK, 0 rows affected (0.69 sec)
Now, we have total 4 columns in my table ‘CountColumns’. You can apply the above syntax to count the number of columns. The query is as follows −
mysql> SELECT COUNT(*) as NumberofColumns FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'business'
−> and table_name = 'CountColumns';
The output displays the count of columns −
+-----------------+
| NumberofColumns |
+-----------------+
| 4 |
+-----------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1227,
"s": 1062,
"text": "To get the number of columns, use the aggregate function count(*) with information_schema table from MySQL. The syntax is as follows to find the number of columns −"
},
{
"code": null,
"e": 1368,
"s": 1227,
"text": "SELECT COUNT(*) as anyVariableName from INFORMATION_SCHEMA.COLUMNS where table_schema = ’yourDatabaseName’ and table_name = ’yourTableName’;"
},
{
"code": null,
"e": 1488,
"s": 1368,
"text": "To understand the above syntax, let us create a table with some columns. The following is the query to create a table −"
},
{
"code": null,
"e": 1684,
"s": 1488,
"text": "mysql> create table CountColumns\n−> (\n −> Bookid int,\n −> BookName varchar(200),\n −> BookAuthorName varchar(200),\n −> BookPublishedDate datetime\n−> );\nQuery OK, 0 rows affected (0.69 sec)"
},
{
"code": null,
"e": 1830,
"s": 1684,
"text": "Now, we have total 4 columns in my table ‘CountColumns’. You can apply the above syntax to count the number of columns. The query is as follows −"
},
{
"code": null,
"e": 1972,
"s": 1830,
"text": "mysql> SELECT COUNT(*) as NumberofColumns FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'business'\n−> and table_name = 'CountColumns';"
},
{
"code": null,
"e": 2015,
"s": 1972,
"text": "The output displays the count of columns −"
},
{
"code": null,
"e": 2139,
"s": 2015,
"text": "+-----------------+\n| NumberofColumns |\n+-----------------+\n| 4 |\n+-----------------+\n1 row in set (0.00 sec)"
}
] |
Convert string to integer without using any in-built functions - GeeksforGeeks | 27 Oct, 2021
Given a string str, the task is to convert the given string into the number without using any inbuilt function.
Examples:
Input: str = “985632”Output: 985632Explanation:Given input is in string form and returned output is in integer form.
Input: str = “123”Output: 123Explanation:Given input is in string form and returned output is in integer form.
Approach: The idea is to use the ASCII value of the digits from 0 to 9 start from 48 – 57.Therefore, to change the numeric character to an integer subtract 48 from the ASCII value of the character will give the corresponding digit for the given character.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
// C++ program for the above approach #include <iostream> using namespace std; // Function to convert string to // integer without using functions void convert(string s) { // Initialize a variable int num = 0; int n = s.length(); // Iterate till length of the string for (int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + (int(s[i]) - 48); // Print the answer cout << num; } // Driver Code int main() { // Given string of number char s[] = "123"; // Function Call convert(s); return 0; }
// C program for the above approach #include <stdio.h> #include <string.h> // Function to convert string to // integer without using functions void convert(char s[]) { // Initialize a variable int num = 0; int n = strlen(s); // Iterate till length of the string for (int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + (s[i] - 48); // Print the answer printf("%d", num); } // Driver Code int main() { // Given string of number char s[] = "123"; // Function Call convert(s); return 0; }
// Java program for the above approach class GFG{ // Function to convert string to // integer without using functions public static void convert(String s) { // Initialize a variable int num = 0; int n = s.length(); // Iterate till length of the string for(int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + ((int)s.charAt(i) - 48); // Print the answer System.out.print(num); } // Driver code public static void main(String[] args) { // Given string of number String s = "123"; // Function Call convert(s); } } // This code is contributed by divyeshrabadiya07
# Python3 program for the above approach # Function to convert string to # integer without using functions def convert(s): # Initialize a variable num = 0 n = len(s) # Iterate till length of the string for i in s: # Subtract 48 from the current digit num = num * 10 + (ord(i) - 48) # Print the answer print(num) # Driver code if __name__ == '__main__': # Given string of number s = "123" # Function Call convert(s) # This code is contributed by Shivam Singh
// C# program for the above approach using System; class GFG{ // Function to convert string to // integer without using functions public static void convert(string s) { // Initialize a variable int num = 0; int n = s.Length; // Iterate till length of the string for(int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + ((int)s[i] - 48); // Print the answer Console.Write(num); } // Driver codepublic static void Main(string[] args){ // Given string of number string s = "123"; // Function call convert(s); }} // This code is contributed by rock_cool
123
Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(1)
SHIVAMSINGH67
divyeshrabadiya07
rock_cool
nidhi_biet
saurabh1990aror
number-digits
Numbers
Arrays
C Programs
C++ Programs
Greedy
Mathematical
Strings
Arrays
Strings
Greedy
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Move all negative numbers to beginning and positive to end with constant extra space
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses | [
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 24908,
"s": 24796,
"text": "Given a string str, the task is to convert the given string into the number without using any inbuilt function."
},
{
"code": null,
"e": 24919,
"s": 24908,
"text": "Examples: "
},
{
"code": null,
"e": 25036,
"s": 24919,
"text": "Input: str = “985632”Output: 985632Explanation:Given input is in string form and returned output is in integer form."
},
{
"code": null,
"e": 25147,
"s": 25036,
"text": "Input: str = “123”Output: 123Explanation:Given input is in string form and returned output is in integer form."
},
{
"code": null,
"e": 25403,
"s": 25147,
"text": "Approach: The idea is to use the ASCII value of the digits from 0 to 9 start from 48 – 57.Therefore, to change the numeric character to an integer subtract 48 from the ASCII value of the character will give the corresponding digit for the given character."
},
{
"code": null,
"e": 25454,
"s": 25403,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25458,
"s": 25454,
"text": "C++"
},
{
"code": null,
"e": 25460,
"s": 25458,
"text": "C"
},
{
"code": null,
"e": 25465,
"s": 25460,
"text": "Java"
},
{
"code": null,
"e": 25473,
"s": 25465,
"text": "Python3"
},
{
"code": null,
"e": 25476,
"s": 25473,
"text": "C#"
},
{
"code": "// C++ program for the above approach #include <iostream> using namespace std; // Function to convert string to // integer without using functions void convert(string s) { // Initialize a variable int num = 0; int n = s.length(); // Iterate till length of the string for (int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + (int(s[i]) - 48); // Print the answer cout << num; } // Driver Code int main() { // Given string of number char s[] = \"123\"; // Function Call convert(s); return 0; } ",
"e": 26069,
"s": 25476,
"text": null
},
{
"code": "// C program for the above approach #include <stdio.h> #include <string.h> // Function to convert string to // integer without using functions void convert(char s[]) { // Initialize a variable int num = 0; int n = strlen(s); // Iterate till length of the string for (int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + (s[i] - 48); // Print the answer printf(\"%d\", num); } // Driver Code int main() { // Given string of number char s[] = \"123\"; // Function Call convert(s); return 0; } ",
"e": 26658,
"s": 26069,
"text": null
},
{
"code": "// Java program for the above approach class GFG{ // Function to convert string to // integer without using functions public static void convert(String s) { // Initialize a variable int num = 0; int n = s.length(); // Iterate till length of the string for(int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + ((int)s.charAt(i) - 48); // Print the answer System.out.print(num); } // Driver code public static void main(String[] args) { // Given string of number String s = \"123\"; // Function Call convert(s); } } // This code is contributed by divyeshrabadiya07 ",
"e": 27325,
"s": 26658,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to convert string to # integer without using functions def convert(s): # Initialize a variable num = 0 n = len(s) # Iterate till length of the string for i in s: # Subtract 48 from the current digit num = num * 10 + (ord(i) - 48) # Print the answer print(num) # Driver code if __name__ == '__main__': # Given string of number s = \"123\" # Function Call convert(s) # This code is contributed by Shivam Singh ",
"e": 27860,
"s": 27325,
"text": null
},
{
"code": "// C# program for the above approach using System; class GFG{ // Function to convert string to // integer without using functions public static void convert(string s) { // Initialize a variable int num = 0; int n = s.Length; // Iterate till length of the string for(int i = 0; i < n; i++) // Subtract 48 from the current digit num = num * 10 + ((int)s[i] - 48); // Print the answer Console.Write(num); } // Driver codepublic static void Main(string[] args){ // Given string of number string s = \"123\"; // Function call convert(s); }} // This code is contributed by rock_cool",
"e": 28519,
"s": 27860,
"text": null
},
{
"code": null,
"e": 28524,
"s": 28519,
"text": "123\n"
},
{
"code": null,
"e": 28611,
"s": 28524,
"text": "Time Complexity: O(N), where N is the length of the given string.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28625,
"s": 28611,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 28643,
"s": 28625,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 28653,
"s": 28643,
"text": "rock_cool"
},
{
"code": null,
"e": 28664,
"s": 28653,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28680,
"s": 28664,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28694,
"s": 28680,
"text": "number-digits"
},
{
"code": null,
"e": 28702,
"s": 28694,
"text": "Numbers"
},
{
"code": null,
"e": 28709,
"s": 28702,
"text": "Arrays"
},
{
"code": null,
"e": 28720,
"s": 28709,
"text": "C Programs"
},
{
"code": null,
"e": 28733,
"s": 28720,
"text": "C++ Programs"
},
{
"code": null,
"e": 28740,
"s": 28733,
"text": "Greedy"
},
{
"code": null,
"e": 28753,
"s": 28740,
"text": "Mathematical"
},
{
"code": null,
"e": 28761,
"s": 28753,
"text": "Strings"
},
{
"code": null,
"e": 28768,
"s": 28761,
"text": "Arrays"
},
{
"code": null,
"e": 28776,
"s": 28768,
"text": "Strings"
},
{
"code": null,
"e": 28783,
"s": 28776,
"text": "Greedy"
},
{
"code": null,
"e": 28796,
"s": 28783,
"text": "Mathematical"
},
{
"code": null,
"e": 28804,
"s": 28796,
"text": "Numbers"
},
{
"code": null,
"e": 28902,
"s": 28804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28927,
"s": 28902,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28947,
"s": 28927,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 28985,
"s": 28947,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 29010,
"s": 28985,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 29095,
"s": 29010,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 29108,
"s": 29095,
"text": "Strings in C"
},
{
"code": null,
"e": 29149,
"s": 29108,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29187,
"s": 29149,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29228,
"s": 29187,
"text": "C Program to read contents of Whole File"
}
] |
Bottom View of a Binary Tree - GeeksforGeeks | 02 Jul, 2021
Given a Binary Tree, we need to print the bottom view from left to right. A node x is there in output if x is the bottommost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1.
Examples:
20
/ \
8 22
/ \ \
5 3 25
/ \
10 14
For the above tree the output should be 5, 10, 3, 14, 25.If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottom-most nodes at horizontal distance 0, we need to print 4.
20
/ \
8 22
/ \ / \
5 3 4 25
/ \
10 14
For the above tree the output should be 5, 10, 4, 14, 25.
Method 1 – Using Queue The following are steps to print Bottom View of Binary Tree. 1. We put tree nodes in a queue for the level order traversal. 2. Start with the horizontal distance(hd) 0 of the root node, keep on adding left child to queue along with the horizontal distance as hd-1 and right child as hd+1. 3. Also, use a TreeMap which stores key value pair sorted on key. 4. Every time, we encounter a new horizontal distance or an existing horizontal distance put the node data for the horizontal distance as key. For the first time it will add to the map, next time it will replace the value. This will make sure that the bottom most element for that horizontal distance is present in the map and if you see the tree from beneath that you will see that element.
Below is the implementation of the above:
C++
Java
Python3
C#
Javascript
// C++ Program to print Bottom View of Binary Tree#include<bits/stdc++.h>using namespace std; // Tree node classstruct Node{ int data; //data of the node int hd; //horizontal distance of the node Node *left, *right; //left and right references // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; }}; // Method that prints the bottom view.void bottomView(Node *root){ if (root == NULL) return; // Initialize a variable 'hd' with 0 // for the root element. int hd = 0; // TreeMap which stores key value pair // sorted on key value map<int, int> m; // Queue to store tree nodes in level // order traversal queue<Node *> q; // Assign initialized horizontal distance // value to root node and add it to the queue. root->hd = hd; q.push(root); // In STL, push() is used enqueue an item // Loop until the queue is empty (standard // level order loop) while (!q.empty()) { Node *temp = q.front(); q.pop(); // In STL, pop() is used dequeue an item // Extract the horizontal distance value // from the dequeued tree node. hd = temp->hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. Every // time we find a node having same horizontal // distance we need to replace the data in // the map. m[hd] = temp->data; // If the dequeued node has a left child, add // it to the queue with a horizontal distance hd-1. if (temp->left != NULL) { temp->left->hd = hd-1; q.push(temp->left); } // If the dequeued node has a right child, add // it to the queue with a horizontal distance // hd+1. if (temp->right != NULL) { temp->right->hd = hd+1; q.push(temp->right); } } // Traverse the map elements using the iterator. for (auto i = m.begin(); i != m.end(); ++i) cout << i->second << " ";} // Driver Codeint main(){ Node *root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(5); root->left->right = new Node(3); root->right->left = new Node(4); root->right->right = new Node(25); root->left->right->left = new Node(10); root->left->right->right = new Node(14); cout << "Bottom view of the given binary tree :\n" bottomView(root); return 0;}
// Java Program to print Bottom View of Binary Treeimport java.util.*;import java.util.Map.Entry; // Tree node classclass Node{ int data; //data of the node int hd; //horizontal distance of the node Node left, right; //left and right references // Constructor of tree node public Node(int key) { data = key; hd = Integer.MAX_VALUE; left = right = null; }} //Tree classclass Tree{ Node root; //root node of tree // Default constructor public Tree() {} // Parameterized tree constructor public Tree(Node node) { root = node; } // Method that prints the bottom view. public void bottomView() { if (root == null) return; // Initialize a variable 'hd' with 0 for the root element. int hd = 0; // TreeMap which stores key value pair sorted on key value Map<Integer, Integer> map = new TreeMap<>(); // Queue to store tree nodes in level order traversal Queue<Node> queue = new LinkedList<Node>(); // Assign initialized horizontal distance value to root // node and add it to the queue. root.hd = hd; queue.add(root); // Loop until the queue is empty (standard level order loop) while (!queue.isEmpty()) { Node temp = queue.remove(); // Extract the horizontal distance value from the // dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap having key // as horizontal distance. Every time we find a node // having same horizontal distance we need to replace // the data in the map. map.put(hd, temp.data); // If the dequeued node has a left child add it to the // queue with a horizontal distance hd-1. if (temp.left != null) { temp.left.hd = hd-1; queue.add(temp.left); } // If the dequeued node has a right child add it to the // queue with a horizontal distance hd+1. if (temp.right != null) { temp.right.hd = hd+1; queue.add(temp.right); } } // Extract the entries of map into a set to traverse // an iterator over that. Set<Entry<Integer, Integer>> set = map.entrySet(); // Make an iterator Iterator<Entry<Integer, Integer>> iterator = set.iterator(); // Traverse the map elements using the iterator. while (iterator.hasNext()) { Map.Entry<Integer, Integer> me = iterator.next(); System.out.print(me.getValue()+" "); } }} // Main driver classpublic class BottomView{ public static void main(String[] args) { Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Tree tree = new Tree(root); System.out.println("Bottom view of the given binary tree:"); tree.bottomView(); }}
# Python3 program to print Bottom# View of Binary Tree # Tree node classclass Node: def __init__(self, key): self.data = key self.hd = 1000000 self.left = None self.right = None # Method that prints the bottom view.def bottomView(root): if (root == None): return # Initialize a variable 'hd' with 0 # for the root element. hd = 0 # TreeMap which stores key value pair # sorted on key value m = dict() # Queue to store tree nodes in level # order traversal q = [] # Assign initialized horizontal distance # value to root node and add it to the queue. root.hd = hd # In STL, append() is used enqueue an item q.append(root) # Loop until the queue is empty (standard # level order loop) while (len(q) != 0): temp = q[0] # In STL, pop() is used dequeue an item q.pop(0) # Extract the horizontal distance value # from the dequeued tree node. hd = temp.hd # Put the dequeued tree node to TreeMap # having key as horizontal distance. Every # time we find a node having same horizontal # distance we need to replace the data in # the map. m[hd] = temp.data # If the dequeued node has a left child, add # it to the queue with a horizontal distance hd-1. if (temp.left != None): temp.left.hd = hd - 1 q.append(temp.left) # If the dequeued node has a right child, add # it to the queue with a horizontal distance # hd+1. if (temp.right != None): temp.right.hd = hd + 1 q.append(temp.right) # Traverse the map elements using the iterator. for i in sorted(m.keys()): print(m[i], end = ' ') # Driver Codeif __name__=='__main__': root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(5) root.left.right = Node(3) root.right.left = Node(4) root.right.right = Node(25) root.left.right.left = Node(10) root.left.right.right = Node(14) print("Bottom view of the given binary tree :") bottomView(root) # This code is contributed by rutvik_56
// C# program to print Bottom View of Binary Treeusing System;using System.Collections;using System.Collections.Generic; // Tree node classclass Node{ // Data of the node public int data; // Horizontal distance of the node public int hd; // left and right references public Node left, right; // Constructor of tree node public Node(int key) { data = key; hd = 1000000; left = right = null; }} // Tree classclass Tree{ // Root node of tree Node root; // Default constructor public Tree(){} // Parameterized tree constructor public Tree(Node node) { root = node; } // Method that prints the bottom view. public void bottomView() { if (root == null) return; // Initialize a variable 'hd' with // 0 for the root element. int hd = 0; // TreeMap which stores key value // pair sorted on key value SortedDictionary<int, int> map = new SortedDictionary<int, int>(); // Queue to store tree nodes in level order // traversal Queue queue = new Queue(); // Assign initialized horizontal distance // value to root node and add it to the queue. root.hd = hd; queue.Enqueue(root); // Loop until the queue is empty // (standard level order loop) while (queue.Count != 0) { Node temp = (Node) queue.Dequeue(); // Extract the horizontal distance value // from the dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. // Every time we find a node having same // horizontal distance we need to replace // the data in the map. map[hd] = temp.data; // If the dequeued node has a left child // add it to the queue with a horizontal // distance hd-1. if (temp.left != null) { temp.left.hd = hd - 1; queue.Enqueue(temp.left); } // If the dequeued node has a right // child add it to the queue with a // horizontal distance hd+1. if (temp.right != null) { temp.right.hd = hd + 1; queue.Enqueue(temp.right); } } foreach(int i in map.Values) { Console.Write(i + " "); } }} public class BottomView{ // Driver codepublic static void Main(string[] args){ Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Tree tree = new Tree(root); Console.WriteLine("Bottom view of the " + "given binary tree:"); tree.bottomView();}} // This code is contributed by pratham76
<script> // JavaScript program to print Bottom View of Binary Tree // Tree node class class Node { // Constructor of tree node constructor(key) { this.data = key; // Data of the node this.hd = 1000000; // Horizontal distance of the node this.left = null; // left and right references this.right = null; } } // Tree class class Tree { // Parameterized tree constructor constructor(node) { // Root node of tree this.root = node; } // Method that prints the bottom view. bottomView() { if (this.root == null) return; // Initialize a variable 'hd' with // 0 for the root element. var hd = 0; // TreeMap which stores key value // pair sorted on key value var map = {}; // Queue to store tree nodes in level order // traversal var queue = []; // Assign initialized horizontal distance // value to root node and add it to the queue. this.root.hd = hd; queue.push(this.root); // Loop until the queue is empty // (standard level order loop) while (queue.length != 0) { var temp = queue.shift(); // Extract the horizontal distance value // from the dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. // Every time we find a node having same // horizontal distance we need to replace // the data in the map. map[hd] = temp.data; // If the dequeued node has a left child // add it to the queue with a horizontal // distance hd-1. if (temp.left != null) { temp.left.hd = hd - 1; queue.push(temp.left); } // If the dequeued node has a right // child add it to the queue with a // horizontal distance hd+1. if (temp.right != null) { temp.right.hd = hd + 1; queue.push(temp.right); } } for (const [key, value] of Object.entries(map).sort( (a, b) => a[0] - b[0] )) { document.write(value + " "); } } } // Driver code var root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); var tree = new Tree(root); document.write("Bottom view of the " + "given binary tree:<br>"); tree.bottomView(); </script>
Output:
Bottom view of the given binary tree:
5 10 4 14 25
Method 2- Using HashMap() This method is contributed by Ekta Goel.
Approach: Create a map like, map where key is the horizontal distance and value is a pair(a, b) where a is the value of the node and b is the height of the node. Perform a pre-order traversal of the tree. If the current node at a horizontal distance of h is the first we’ve seen, insert it in the map. Otherwise, compare the node with the existing one in map and if the height of the new node is greater, update in the Map.
Below is the implementation of the above:
C++
Java
Python3
// C++ Program to print Bottom View of Binary Tree#include <bits/stdc++.h>#include <map>using namespace std; // Tree node classstruct Node{ // data of the node int data; // horizontal distance of the node int hd; //left and right references Node * left, * right; // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; }}; void printBottomViewUtil(Node * root, int curr, int hd, map <int, pair <int, int>> & m){ // Base case if (root == NULL) return; // If node for a particular // horizontal distance is not // present, add to the map. if (m.find(hd) == m.end()) { m[hd] = make_pair(root -> data, curr); } // Compare height for already // present node at similar horizontal // distance else { pair < int, int > p = m[hd]; if (p.second <= curr) { m[hd].second = curr; m[hd].first = root -> data; } } // Recur for left subtree printBottomViewUtil(root -> left, curr + 1, hd - 1, m); // Recur for right subtree printBottomViewUtil(root -> right, curr + 1, hd + 1, m);} void printBottomView(Node * root){ // Map to store Horizontal Distance, // Height and Data. map < int, pair < int, int > > m; printBottomViewUtil(root, 0, 0, m); // Prints the values stored by printBottomViewUtil() map < int, pair < int, int > > ::iterator it; for (it = m.begin(); it != m.end(); ++it) { pair < int, int > p = it -> second; cout << p.first << " "; }} int main(){ Node * root = new Node(20); root -> left = new Node(8); root -> right = new Node(22); root -> left -> left = new Node(5); root -> left -> right = new Node(3); root -> right -> left = new Node(4); root -> right -> right = new Node(25); root -> left -> right -> left = new Node(10); root -> left -> right -> right = new Node(14); cout << "Bottom view of the given binary tree :\n"; printBottomView(root); return 0;}
// Java program to print Bottom View of Binary Treeimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Tree node classstatic class Node{ // Data of the node int data; // Horizontal distance of the node int hd; // Left and right references Node left, right; // Constructor of tree node public Node(int key) { data = key; hd = Integer.MAX_VALUE; left = right = null; }} static void printBottomViewUtil(Node root, int curr, int hd, TreeMap<Integer, int[]> m){ // Base case if (root == null) return; // If node for a particular // horizontal distance is not // present, add to the map. if (!m.containsKey(hd)) { m.put(hd, new int[]{ root.data, curr }); } // Compare height for already // present node at similar horizontal // distance else { int[] p = m.get(hd); if (p[1] <= curr) { p[1] = curr; p[0] = root.data; } m.put(hd, p); } // Recur for left subtree printBottomViewUtil(root.left, curr + 1, hd - 1, m); // Recur for right subtree printBottomViewUtil(root.right, curr + 1, hd + 1, m);} static void printBottomView(Node root){ // Map to store Horizontal Distance, // Height and Data. TreeMap<Integer, int[]> m = new TreeMap<>(); printBottomViewUtil(root, 0, 0, m); // Prints the values stored by printBottomViewUtil() for(int val[] : m.values()) { System.out.print(val[0] + " "); }} // Driver Codepublic static void main(String[] args){ Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); System.out.println( "Bottom view of the given binary tree:"); printBottomView(root);}} // This code is contributed by Kingash
# Python3 program to print Bottom# View of Binary Treeclass Node: def __init__(self, key = None, left = None, right = None): self.data = key self.left = left self.right = right def printBottomView(root): # Create a dictionary where # key -> relative horizontal distance # of the node from root node and # value -> pair containing node's # value and its level d = dict() printBottomViewUtil(root, d, 0, 0) # Traverse the dictionary in sorted # order of their keys and print # the bottom view for i in sorted(d.keys()): print(d[i][0], end = " ") def printBottomViewUtil(root, d, hd, level): # Base case if root is None: return # If current level is more than or equal # to maximum level seen so far for the # same horizontal distance or horizontal # distance is seen for the first time, # update the dictionary if hd in d: if level >= d[hd][1]: d[hd] = [root.data, level] else: d[hd] = [root.data, level] # recur for left subtree by decreasing # horizontal distance and increasing # level by 1 printBottomViewUtil(root.left, d, hd - 1, level + 1) # recur for right subtree by increasing # horizontal distance and increasing # level by 1 printBottomViewUtil(root.right, d, hd + 1, level + 1) # Driver Code if __name__ == '__main__': root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(5) root.left.right = Node(3) root.right.left = Node(4) root.right.right = Node(25) root.left.right.left = Node(10) root.left.right.right = Node(14) print("Bottom view of the given binary tree :") printBottomView(root) # This code is contributed by tusharroy
YouTubeGeeksforGeeks502K subscribersBottom View of a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fPhgtqKdG5k" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
tusharroy
pratham76
rutvik_56
Kingash
rdtank
Accolite
Amazon
CouponDunia
Flipkart
Paytm
tree-view
Walmart
Tree
Paytm
Flipkart
Accolite
Amazon
Walmart
CouponDunia
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
BFS vs DFS for Binary Tree | [
{
"code": null,
"e": 25280,
"s": 25252,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 25591,
"s": 25280,
"text": "Given a Binary Tree, we need to print the bottom view from left to right. A node x is there in output if x is the bottommost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1. "
},
{
"code": null,
"e": 25602,
"s": 25591,
"text": "Examples: "
},
{
"code": null,
"e": 25800,
"s": 25602,
"text": " 20\n / \\\n 8 22\n / \\ \\\n 5 3 25\n / \\ \n 10 14"
},
{
"code": null,
"e": 26100,
"s": 25800,
"text": "For the above tree the output should be 5, 10, 3, 14, 25.If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottom-most nodes at horizontal distance 0, we need to print 4. "
},
{
"code": null,
"e": 26321,
"s": 26100,
"text": " \n 20\n / \\\n 8 22\n / \\ / \\\n 5 3 4 25\n / \\ \n 10 14"
},
{
"code": null,
"e": 26380,
"s": 26321,
"text": "For the above tree the output should be 5, 10, 4, 14, 25. "
},
{
"code": null,
"e": 27150,
"s": 26380,
"text": "Method 1 – Using Queue The following are steps to print Bottom View of Binary Tree. 1. We put tree nodes in a queue for the level order traversal. 2. Start with the horizontal distance(hd) 0 of the root node, keep on adding left child to queue along with the horizontal distance as hd-1 and right child as hd+1. 3. Also, use a TreeMap which stores key value pair sorted on key. 4. Every time, we encounter a new horizontal distance or an existing horizontal distance put the node data for the horizontal distance as key. For the first time it will add to the map, next time it will replace the value. This will make sure that the bottom most element for that horizontal distance is present in the map and if you see the tree from beneath that you will see that element."
},
{
"code": null,
"e": 27192,
"s": 27150,
"text": "Below is the implementation of the above:"
},
{
"code": null,
"e": 27196,
"s": 27192,
"text": "C++"
},
{
"code": null,
"e": 27201,
"s": 27196,
"text": "Java"
},
{
"code": null,
"e": 27209,
"s": 27201,
"text": "Python3"
},
{
"code": null,
"e": 27212,
"s": 27209,
"text": "C#"
},
{
"code": null,
"e": 27223,
"s": 27212,
"text": "Javascript"
},
{
"code": "// C++ Program to print Bottom View of Binary Tree#include<bits/stdc++.h>using namespace std; // Tree node classstruct Node{ int data; //data of the node int hd; //horizontal distance of the node Node *left, *right; //left and right references // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; }}; // Method that prints the bottom view.void bottomView(Node *root){ if (root == NULL) return; // Initialize a variable 'hd' with 0 // for the root element. int hd = 0; // TreeMap which stores key value pair // sorted on key value map<int, int> m; // Queue to store tree nodes in level // order traversal queue<Node *> q; // Assign initialized horizontal distance // value to root node and add it to the queue. root->hd = hd; q.push(root); // In STL, push() is used enqueue an item // Loop until the queue is empty (standard // level order loop) while (!q.empty()) { Node *temp = q.front(); q.pop(); // In STL, pop() is used dequeue an item // Extract the horizontal distance value // from the dequeued tree node. hd = temp->hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. Every // time we find a node having same horizontal // distance we need to replace the data in // the map. m[hd] = temp->data; // If the dequeued node has a left child, add // it to the queue with a horizontal distance hd-1. if (temp->left != NULL) { temp->left->hd = hd-1; q.push(temp->left); } // If the dequeued node has a right child, add // it to the queue with a horizontal distance // hd+1. if (temp->right != NULL) { temp->right->hd = hd+1; q.push(temp->right); } } // Traverse the map elements using the iterator. for (auto i = m.begin(); i != m.end(); ++i) cout << i->second << \" \";} // Driver Codeint main(){ Node *root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(5); root->left->right = new Node(3); root->right->left = new Node(4); root->right->right = new Node(25); root->left->right->left = new Node(10); root->left->right->right = new Node(14); cout << \"Bottom view of the given binary tree :\\n\" bottomView(root); return 0;}",
"e": 29730,
"s": 27223,
"text": null
},
{
"code": "// Java Program to print Bottom View of Binary Treeimport java.util.*;import java.util.Map.Entry; // Tree node classclass Node{ int data; //data of the node int hd; //horizontal distance of the node Node left, right; //left and right references // Constructor of tree node public Node(int key) { data = key; hd = Integer.MAX_VALUE; left = right = null; }} //Tree classclass Tree{ Node root; //root node of tree // Default constructor public Tree() {} // Parameterized tree constructor public Tree(Node node) { root = node; } // Method that prints the bottom view. public void bottomView() { if (root == null) return; // Initialize a variable 'hd' with 0 for the root element. int hd = 0; // TreeMap which stores key value pair sorted on key value Map<Integer, Integer> map = new TreeMap<>(); // Queue to store tree nodes in level order traversal Queue<Node> queue = new LinkedList<Node>(); // Assign initialized horizontal distance value to root // node and add it to the queue. root.hd = hd; queue.add(root); // Loop until the queue is empty (standard level order loop) while (!queue.isEmpty()) { Node temp = queue.remove(); // Extract the horizontal distance value from the // dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap having key // as horizontal distance. Every time we find a node // having same horizontal distance we need to replace // the data in the map. map.put(hd, temp.data); // If the dequeued node has a left child add it to the // queue with a horizontal distance hd-1. if (temp.left != null) { temp.left.hd = hd-1; queue.add(temp.left); } // If the dequeued node has a right child add it to the // queue with a horizontal distance hd+1. if (temp.right != null) { temp.right.hd = hd+1; queue.add(temp.right); } } // Extract the entries of map into a set to traverse // an iterator over that. Set<Entry<Integer, Integer>> set = map.entrySet(); // Make an iterator Iterator<Entry<Integer, Integer>> iterator = set.iterator(); // Traverse the map elements using the iterator. while (iterator.hasNext()) { Map.Entry<Integer, Integer> me = iterator.next(); System.out.print(me.getValue()+\" \"); } }} // Main driver classpublic class BottomView{ public static void main(String[] args) { Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Tree tree = new Tree(root); System.out.println(\"Bottom view of the given binary tree:\"); tree.bottomView(); }}",
"e": 33007,
"s": 29730,
"text": null
},
{
"code": "# Python3 program to print Bottom# View of Binary Tree # Tree node classclass Node: def __init__(self, key): self.data = key self.hd = 1000000 self.left = None self.right = None # Method that prints the bottom view.def bottomView(root): if (root == None): return # Initialize a variable 'hd' with 0 # for the root element. hd = 0 # TreeMap which stores key value pair # sorted on key value m = dict() # Queue to store tree nodes in level # order traversal q = [] # Assign initialized horizontal distance # value to root node and add it to the queue. root.hd = hd # In STL, append() is used enqueue an item q.append(root) # Loop until the queue is empty (standard # level order loop) while (len(q) != 0): temp = q[0] # In STL, pop() is used dequeue an item q.pop(0) # Extract the horizontal distance value # from the dequeued tree node. hd = temp.hd # Put the dequeued tree node to TreeMap # having key as horizontal distance. Every # time we find a node having same horizontal # distance we need to replace the data in # the map. m[hd] = temp.data # If the dequeued node has a left child, add # it to the queue with a horizontal distance hd-1. if (temp.left != None): temp.left.hd = hd - 1 q.append(temp.left) # If the dequeued node has a right child, add # it to the queue with a horizontal distance # hd+1. if (temp.right != None): temp.right.hd = hd + 1 q.append(temp.right) # Traverse the map elements using the iterator. for i in sorted(m.keys()): print(m[i], end = ' ') # Driver Codeif __name__=='__main__': root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(5) root.left.right = Node(3) root.right.left = Node(4) root.right.right = Node(25) root.left.right.left = Node(10) root.left.right.right = Node(14) print(\"Bottom view of the given binary tree :\") bottomView(root) # This code is contributed by rutvik_56",
"e": 35262,
"s": 33007,
"text": null
},
{
"code": "// C# program to print Bottom View of Binary Treeusing System;using System.Collections;using System.Collections.Generic; // Tree node classclass Node{ // Data of the node public int data; // Horizontal distance of the node public int hd; // left and right references public Node left, right; // Constructor of tree node public Node(int key) { data = key; hd = 1000000; left = right = null; }} // Tree classclass Tree{ // Root node of tree Node root; // Default constructor public Tree(){} // Parameterized tree constructor public Tree(Node node) { root = node; } // Method that prints the bottom view. public void bottomView() { if (root == null) return; // Initialize a variable 'hd' with // 0 for the root element. int hd = 0; // TreeMap which stores key value // pair sorted on key value SortedDictionary<int, int> map = new SortedDictionary<int, int>(); // Queue to store tree nodes in level order // traversal Queue queue = new Queue(); // Assign initialized horizontal distance // value to root node and add it to the queue. root.hd = hd; queue.Enqueue(root); // Loop until the queue is empty // (standard level order loop) while (queue.Count != 0) { Node temp = (Node) queue.Dequeue(); // Extract the horizontal distance value // from the dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. // Every time we find a node having same // horizontal distance we need to replace // the data in the map. map[hd] = temp.data; // If the dequeued node has a left child // add it to the queue with a horizontal // distance hd-1. if (temp.left != null) { temp.left.hd = hd - 1; queue.Enqueue(temp.left); } // If the dequeued node has a right // child add it to the queue with a // horizontal distance hd+1. if (temp.right != null) { temp.right.hd = hd + 1; queue.Enqueue(temp.right); } } foreach(int i in map.Values) { Console.Write(i + \" \"); } }} public class BottomView{ // Driver codepublic static void Main(string[] args){ Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Tree tree = new Tree(root); Console.WriteLine(\"Bottom view of the \" + \"given binary tree:\"); tree.bottomView();}} // This code is contributed by pratham76",
"e": 38495,
"s": 35262,
"text": null
},
{
"code": "<script> // JavaScript program to print Bottom View of Binary Tree // Tree node class class Node { // Constructor of tree node constructor(key) { this.data = key; // Data of the node this.hd = 1000000; // Horizontal distance of the node this.left = null; // left and right references this.right = null; } } // Tree class class Tree { // Parameterized tree constructor constructor(node) { // Root node of tree this.root = node; } // Method that prints the bottom view. bottomView() { if (this.root == null) return; // Initialize a variable 'hd' with // 0 for the root element. var hd = 0; // TreeMap which stores key value // pair sorted on key value var map = {}; // Queue to store tree nodes in level order // traversal var queue = []; // Assign initialized horizontal distance // value to root node and add it to the queue. this.root.hd = hd; queue.push(this.root); // Loop until the queue is empty // (standard level order loop) while (queue.length != 0) { var temp = queue.shift(); // Extract the horizontal distance value // from the dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. // Every time we find a node having same // horizontal distance we need to replace // the data in the map. map[hd] = temp.data; // If the dequeued node has a left child // add it to the queue with a horizontal // distance hd-1. if (temp.left != null) { temp.left.hd = hd - 1; queue.push(temp.left); } // If the dequeued node has a right // child add it to the queue with a // horizontal distance hd+1. if (temp.right != null) { temp.right.hd = hd + 1; queue.push(temp.right); } } for (const [key, value] of Object.entries(map).sort( (a, b) => a[0] - b[0] )) { document.write(value + \" \"); } } } // Driver code var root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); var tree = new Tree(root); document.write(\"Bottom view of the \" + \"given binary tree:<br>\"); tree.bottomView(); </script>",
"e": 41378,
"s": 38495,
"text": null
},
{
"code": null,
"e": 41387,
"s": 41378,
"text": "Output: "
},
{
"code": null,
"e": 41438,
"s": 41387,
"text": "Bottom view of the given binary tree:\n5 10 4 14 25"
},
{
"code": null,
"e": 41506,
"s": 41438,
"text": "Method 2- Using HashMap() This method is contributed by Ekta Goel. "
},
{
"code": null,
"e": 41930,
"s": 41506,
"text": "Approach: Create a map like, map where key is the horizontal distance and value is a pair(a, b) where a is the value of the node and b is the height of the node. Perform a pre-order traversal of the tree. If the current node at a horizontal distance of h is the first we’ve seen, insert it in the map. Otherwise, compare the node with the existing one in map and if the height of the new node is greater, update in the Map."
},
{
"code": null,
"e": 41972,
"s": 41930,
"text": "Below is the implementation of the above:"
},
{
"code": null,
"e": 41976,
"s": 41972,
"text": "C++"
},
{
"code": null,
"e": 41981,
"s": 41976,
"text": "Java"
},
{
"code": null,
"e": 41989,
"s": 41981,
"text": "Python3"
},
{
"code": "// C++ Program to print Bottom View of Binary Tree#include <bits/stdc++.h>#include <map>using namespace std; // Tree node classstruct Node{ // data of the node int data; // horizontal distance of the node int hd; //left and right references Node * left, * right; // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; }}; void printBottomViewUtil(Node * root, int curr, int hd, map <int, pair <int, int>> & m){ // Base case if (root == NULL) return; // If node for a particular // horizontal distance is not // present, add to the map. if (m.find(hd) == m.end()) { m[hd] = make_pair(root -> data, curr); } // Compare height for already // present node at similar horizontal // distance else { pair < int, int > p = m[hd]; if (p.second <= curr) { m[hd].second = curr; m[hd].first = root -> data; } } // Recur for left subtree printBottomViewUtil(root -> left, curr + 1, hd - 1, m); // Recur for right subtree printBottomViewUtil(root -> right, curr + 1, hd + 1, m);} void printBottomView(Node * root){ // Map to store Horizontal Distance, // Height and Data. map < int, pair < int, int > > m; printBottomViewUtil(root, 0, 0, m); // Prints the values stored by printBottomViewUtil() map < int, pair < int, int > > ::iterator it; for (it = m.begin(); it != m.end(); ++it) { pair < int, int > p = it -> second; cout << p.first << \" \"; }} int main(){ Node * root = new Node(20); root -> left = new Node(8); root -> right = new Node(22); root -> left -> left = new Node(5); root -> left -> right = new Node(3); root -> right -> left = new Node(4); root -> right -> right = new Node(25); root -> left -> right -> left = new Node(10); root -> left -> right -> right = new Node(14); cout << \"Bottom view of the given binary tree :\\n\"; printBottomView(root); return 0;}",
"e": 44077,
"s": 41989,
"text": null
},
{
"code": "// Java program to print Bottom View of Binary Treeimport java.io.*;import java.lang.*;import java.util.*; class GFG{ // Tree node classstatic class Node{ // Data of the node int data; // Horizontal distance of the node int hd; // Left and right references Node left, right; // Constructor of tree node public Node(int key) { data = key; hd = Integer.MAX_VALUE; left = right = null; }} static void printBottomViewUtil(Node root, int curr, int hd, TreeMap<Integer, int[]> m){ // Base case if (root == null) return; // If node for a particular // horizontal distance is not // present, add to the map. if (!m.containsKey(hd)) { m.put(hd, new int[]{ root.data, curr }); } // Compare height for already // present node at similar horizontal // distance else { int[] p = m.get(hd); if (p[1] <= curr) { p[1] = curr; p[0] = root.data; } m.put(hd, p); } // Recur for left subtree printBottomViewUtil(root.left, curr + 1, hd - 1, m); // Recur for right subtree printBottomViewUtil(root.right, curr + 1, hd + 1, m);} static void printBottomView(Node root){ // Map to store Horizontal Distance, // Height and Data. TreeMap<Integer, int[]> m = new TreeMap<>(); printBottomViewUtil(root, 0, 0, m); // Prints the values stored by printBottomViewUtil() for(int val[] : m.values()) { System.out.print(val[0] + \" \"); }} // Driver Codepublic static void main(String[] args){ Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); System.out.println( \"Bottom view of the given binary tree:\"); printBottomView(root);}} // This code is contributed by Kingash",
"e": 46188,
"s": 44077,
"text": null
},
{
"code": "# Python3 program to print Bottom# View of Binary Treeclass Node: def __init__(self, key = None, left = None, right = None): self.data = key self.left = left self.right = right def printBottomView(root): # Create a dictionary where # key -> relative horizontal distance # of the node from root node and # value -> pair containing node's # value and its level d = dict() printBottomViewUtil(root, d, 0, 0) # Traverse the dictionary in sorted # order of their keys and print # the bottom view for i in sorted(d.keys()): print(d[i][0], end = \" \") def printBottomViewUtil(root, d, hd, level): # Base case if root is None: return # If current level is more than or equal # to maximum level seen so far for the # same horizontal distance or horizontal # distance is seen for the first time, # update the dictionary if hd in d: if level >= d[hd][1]: d[hd] = [root.data, level] else: d[hd] = [root.data, level] # recur for left subtree by decreasing # horizontal distance and increasing # level by 1 printBottomViewUtil(root.left, d, hd - 1, level + 1) # recur for right subtree by increasing # horizontal distance and increasing # level by 1 printBottomViewUtil(root.right, d, hd + 1, level + 1) # Driver Code if __name__ == '__main__': root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(5) root.left.right = Node(3) root.right.left = Node(4) root.right.right = Node(25) root.left.right.left = Node(10) root.left.right.right = Node(14) print(\"Bottom view of the given binary tree :\") printBottomView(root) # This code is contributed by tusharroy",
"e": 48145,
"s": 46188,
"text": null
},
{
"code": null,
"e": 48972,
"s": 48145,
"text": "YouTubeGeeksforGeeks502K subscribersBottom View of a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fPhgtqKdG5k\" 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": 48982,
"s": 48972,
"text": "tusharroy"
},
{
"code": null,
"e": 48992,
"s": 48982,
"text": "pratham76"
},
{
"code": null,
"e": 49002,
"s": 48992,
"text": "rutvik_56"
},
{
"code": null,
"e": 49010,
"s": 49002,
"text": "Kingash"
},
{
"code": null,
"e": 49017,
"s": 49010,
"text": "rdtank"
},
{
"code": null,
"e": 49026,
"s": 49017,
"text": "Accolite"
},
{
"code": null,
"e": 49033,
"s": 49026,
"text": "Amazon"
},
{
"code": null,
"e": 49045,
"s": 49033,
"text": "CouponDunia"
},
{
"code": null,
"e": 49054,
"s": 49045,
"text": "Flipkart"
},
{
"code": null,
"e": 49060,
"s": 49054,
"text": "Paytm"
},
{
"code": null,
"e": 49070,
"s": 49060,
"text": "tree-view"
},
{
"code": null,
"e": 49078,
"s": 49070,
"text": "Walmart"
},
{
"code": null,
"e": 49083,
"s": 49078,
"text": "Tree"
},
{
"code": null,
"e": 49089,
"s": 49083,
"text": "Paytm"
},
{
"code": null,
"e": 49098,
"s": 49089,
"text": "Flipkart"
},
{
"code": null,
"e": 49107,
"s": 49098,
"text": "Accolite"
},
{
"code": null,
"e": 49114,
"s": 49107,
"text": "Amazon"
},
{
"code": null,
"e": 49122,
"s": 49114,
"text": "Walmart"
},
{
"code": null,
"e": 49134,
"s": 49122,
"text": "CouponDunia"
},
{
"code": null,
"e": 49139,
"s": 49134,
"text": "Tree"
},
{
"code": null,
"e": 49237,
"s": 49139,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49278,
"s": 49237,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 49321,
"s": 49278,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 49354,
"s": 49321,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 49368,
"s": 49354,
"text": "Decision Tree"
},
{
"code": null,
"e": 49418,
"s": 49368,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 49501,
"s": 49418,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 49559,
"s": 49501,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 49595,
"s": 49559,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 49643,
"s": 49595,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
}
] |
How to find the real user home directory using Python? | To get the homedir in python, you can use os.path.expanduser('~') from the os module. This also works if its a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. You can use it like −
import os
print(os.path.expanduser('~'))
You can also query the environment variables for the HOME variable −
import os
print(os.environ['HOME'])
If you're on Python 3.4+, you can also use pathlib module to get the home directory.
from pathlib import Path
print(Path.home()) | [
{
"code": null,
"e": 1321,
"s": 1062,
"text": "To get the homedir in python, you can use os.path.expanduser('~') from the os module. This also works if its a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. You can use it like −"
},
{
"code": null,
"e": 1362,
"s": 1321,
"text": "import os\nprint(os.path.expanduser('~'))"
},
{
"code": null,
"e": 1431,
"s": 1362,
"text": "You can also query the environment variables for the HOME variable −"
},
{
"code": null,
"e": 1467,
"s": 1431,
"text": "import os\nprint(os.environ['HOME'])"
},
{
"code": null,
"e": 1553,
"s": 1467,
"text": "If you're on Python 3.4+, you can also use pathlib module to get the home directory. "
},
{
"code": null,
"e": 1597,
"s": 1553,
"text": "from pathlib import Path\nprint(Path.home())"
}
] |
DAX Other - UNION function | Creates a union (join) table from the specified tables.
DAX UNION function is new in Excel 2016.
UNION (<table_expression1>, <table_expression2>, [<table_expression3>] ...)
table_expression
Any DAX expression that returns a table.
A table that contains all the rows from each of the table expressions.
The tables must have the same number of columns.
The tables must have the same number of columns.
Columns are combined by the position in their respective tables.
Columns are combined by the position in their respective tables.
The column names in the return table will match the column names in table_expression1.
The column names in the return table will match the column names in table_expression1.
Duplicate rows are retained.
Duplicate rows are retained.
The returned table has lineage where possible. For example, if the first column of each table_expression has lineage to the same base column C1 in the model, the first column in the UNION result will have lineage to C1. However, if combined columns have a lineage to different base columns, or if there is an extension column, the resulting column in UNION will have no lineage.
The returned table has lineage where possible. For example, if the first column of each table_expression has lineage to the same base column C1 in the model, the first column in the UNION result will have lineage to C1. However, if combined columns have a lineage to different base columns, or if there is an extension column, the resulting column in UNION will have no lineage.
When data types differ, the resulting data type is determined based on the rules for data type coercion.
When data types differ, the resulting data type is determined based on the rules for data type coercion.
The returned table will not contain columns from related tables.
The returned table will not contain columns from related tables.
= SUMX (UNION (SalesOldData, SalesNewData), [Sales Amount])
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2057,
"s": 2001,
"text": "Creates a union (join) table from the specified tables."
},
{
"code": null,
"e": 2098,
"s": 2057,
"text": "DAX UNION function is new in Excel 2016."
},
{
"code": null,
"e": 2176,
"s": 2098,
"text": "UNION (<table_expression1>, <table_expression2>, [<table_expression3>] ...) \n"
},
{
"code": null,
"e": 2193,
"s": 2176,
"text": "table_expression"
},
{
"code": null,
"e": 2234,
"s": 2193,
"text": "Any DAX expression that returns a table."
},
{
"code": null,
"e": 2305,
"s": 2234,
"text": "A table that contains all the rows from each of the table expressions."
},
{
"code": null,
"e": 2354,
"s": 2305,
"text": "The tables must have the same number of columns."
},
{
"code": null,
"e": 2403,
"s": 2354,
"text": "The tables must have the same number of columns."
},
{
"code": null,
"e": 2468,
"s": 2403,
"text": "Columns are combined by the position in their respective tables."
},
{
"code": null,
"e": 2533,
"s": 2468,
"text": "Columns are combined by the position in their respective tables."
},
{
"code": null,
"e": 2620,
"s": 2533,
"text": "The column names in the return table will match the column names in table_expression1."
},
{
"code": null,
"e": 2707,
"s": 2620,
"text": "The column names in the return table will match the column names in table_expression1."
},
{
"code": null,
"e": 2736,
"s": 2707,
"text": "Duplicate rows are retained."
},
{
"code": null,
"e": 2765,
"s": 2736,
"text": "Duplicate rows are retained."
},
{
"code": null,
"e": 3144,
"s": 2765,
"text": "The returned table has lineage where possible. For example, if the first column of each table_expression has lineage to the same base column C1 in the model, the first column in the UNION result will have lineage to C1. However, if combined columns have a lineage to different base columns, or if there is an extension column, the resulting column in UNION will have no lineage."
},
{
"code": null,
"e": 3523,
"s": 3144,
"text": "The returned table has lineage where possible. For example, if the first column of each table_expression has lineage to the same base column C1 in the model, the first column in the UNION result will have lineage to C1. However, if combined columns have a lineage to different base columns, or if there is an extension column, the resulting column in UNION will have no lineage."
},
{
"code": null,
"e": 3628,
"s": 3523,
"text": "When data types differ, the resulting data type is determined based on the rules for data type coercion."
},
{
"code": null,
"e": 3733,
"s": 3628,
"text": "When data types differ, the resulting data type is determined based on the rules for data type coercion."
},
{
"code": null,
"e": 3798,
"s": 3733,
"text": "The returned table will not contain columns from related tables."
},
{
"code": null,
"e": 3863,
"s": 3798,
"text": "The returned table will not contain columns from related tables."
},
{
"code": null,
"e": 3924,
"s": 3863,
"text": "= SUMX (UNION (SalesOldData, SalesNewData), [Sales Amount]) "
},
{
"code": null,
"e": 3959,
"s": 3924,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3973,
"s": 3959,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 4006,
"s": 3973,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4020,
"s": 4006,
"text": " Randy Minder"
},
{
"code": null,
"e": 4055,
"s": 4020,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4069,
"s": 4055,
"text": " Randy Minder"
},
{
"code": null,
"e": 4076,
"s": 4069,
"text": " Print"
},
{
"code": null,
"e": 4087,
"s": 4076,
"text": " Add Notes"
}
] |
How to call a jQuery function after a certain delay? | To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.
You can try to run the following code to learn how to work with setTimeout() method in jQuery to call a jQuery function after a delay −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").bind("click",function() {
setTimeout(function() {
$('#list').fadeOut();}, 2000);
});
});
</script>
</head>
<body>
<input type="button" id="button1" value="Fade Out" />
<br/>
<br/>
<div id="list">
<ul>
<li>Voice</li>
<li>Speak</li>
<li>Write</li>
</ul>
</div>
<p>The above content will fade out after 2 seconds</p>
</body>
</html> | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds."
},
{
"code": null,
"e": 1339,
"s": 1203,
"text": "You can try to run the following code to learn how to work with setTimeout() method in jQuery to call a jQuery function after a delay −"
},
{
"code": null,
"e": 1349,
"s": 1339,
"text": "Live Demo"
},
{
"code": null,
"e": 1920,
"s": 1349,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"#button1\").bind(\"click\",function() {\n setTimeout(function() {\n $('#list').fadeOut();}, 2000);\n });\n });\n </script>\n</head>\n<body>\n <input type=\"button\" id=\"button1\" value=\"Fade Out\" />\n <br/>\n <br/>\n <div id=\"list\">\n <ul>\n <li>Voice</li> \n <li>Speak</li>\n <li>Write</li>\n </ul>\n </div>\n <p>The above content will fade out after 2 seconds</p>\n</body>\n</html>"
}
] |
How to invoke the IE browser in Selenium with python? | We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package.
For invoking the internet explorer browser, we have to select the Ie class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation.
Every internet explorer browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser.
Next we need to download the internet explorer driver version as per our browser version. The path of the IEDriverServer.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser.
Code Implementation
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Ie(executable_path="C:\\IEDriverServer.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to close the browser
driver.close() | [
{
"code": null,
"e": 1309,
"s": 1062,
"text": "We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package."
},
{
"code": null,
"e": 1500,
"s": 1309,
"text": "For invoking the internet explorer browser, we have to select the Ie class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation."
},
{
"code": null,
"e": 1675,
"s": 1500,
"text": "Every internet explorer browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser."
},
{
"code": null,
"e": 1939,
"s": 1675,
"text": "Next we need to download the internet explorer driver version as per our browser version. The path of the IEDriverServer.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser."
},
{
"code": null,
"e": 1959,
"s": 1939,
"text": "Code Implementation"
},
{
"code": null,
"e": 2408,
"s": 1959,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Ie(executable_path=\"C:\\\\IEDriverServer.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n#to close the browser\ndriver.close()"
}
] |
Clone an Undirected Graph - GeeksforGeeks | 24 Jan, 2019
Cloning of a LinkedList and a Binary Tree with random pointers has already been discussed. The idea behind cloning a graph is pretty much similar.
The idea is to do a BFS traversal of the graph and while visiting a node make a clone node of it (a copy of original node). If a node is encountered which is already visited then it already has a clone node.
How to keep track of the visited/cloned nodes?A HashMap/Map is required in order to maintain all the nodes which have already been created.Key stores: Reference/Address of original NodeValue stores: Reference/Address of cloned Node
A copy of all the graph nodes has been made, how to connect clone nodes?While visiting the neighboring vertices of a node u get the corresponding cloned node for u , let’s call that cloneNodeU , now visit all the neighboring nodes for u and for each neighbor find the corresponding clone node(if not found create one) and then push into the neighboring vector of cloneNodeU node.
How to verify if the cloned graph is a correct?Do a BFS traversal before and after the cloning of graph. In BFS traversal display the value of a node along with its address/reference.Compare the order in which nodes are displayed, if the values are same but the address/reference is different for both the traversals than the cloned graph is correct.
C++
Java
// A C++ program to Clone an Undirected Graph#include<bits/stdc++.h>using namespace std; struct GraphNode{ int val; //A neighbour vector which contains addresses to //all the neighbours of a GraphNode vector<GraphNode*> neighbours;}; // A function which clones a Graph and// returns the address to the cloned// src nodeGraphNode *cloneGraph(GraphNode *src){ //A Map to keep track of all the //nodes which have already been created map<GraphNode*, GraphNode*> m; queue<GraphNode*> q; // Enqueue src node q.push(src); GraphNode *node; // Make a clone Node node = new GraphNode(); node->val = src->val; // Put the clone node into the Map m[src] = node; while (!q.empty()) { //Get the front node from the queue //and then visit all its neighbours GraphNode *u = q.front(); q.pop(); vector<GraphNode *> v = u->neighbours; int n = v.size(); for (int i = 0; i < n; i++) { // Check if this node has already been created if (m[v[i]] == NULL) { // If not then create a new Node and // put into the HashMap node = new GraphNode(); node->val = v[i]->val; m[v[i]] = node; q.push(v[i]); } // add these neighbours to the cloned graph node m[u]->neighbours.push_back(m[v[i]]); } } // Return the address of cloned src Node return m[src];} // Build the desired graphGraphNode *buildGraph(){ /* Note : All the edges are Undirected Given Graph: 1--2 | | 4--3 */ GraphNode *node1 = new GraphNode(); node1->val = 1; GraphNode *node2 = new GraphNode(); node2->val = 2; GraphNode *node3 = new GraphNode(); node3->val = 3; GraphNode *node4 = new GraphNode(); node4->val = 4; vector<GraphNode *> v; v.push_back(node2); v.push_back(node4); node1->neighbours = v; v.clear(); v.push_back(node1); v.push_back(node3); node2->neighbours = v; v.clear(); v.push_back(node2); v.push_back(node4); node3->neighbours = v; v.clear(); v.push_back(node3); v.push_back(node1); node4->neighbours = v; return node1;} // A simple bfs traversal of a graph to// check for proper cloning of the graphvoid bfs(GraphNode *src){ map<GraphNode*, bool> visit; queue<GraphNode*> q; q.push(src); visit[src] = true; while (!q.empty()) { GraphNode *u = q.front(); cout << "Value of Node " << u->val << "\n"; cout << "Address of Node " <<u << "\n"; q.pop(); vector<GraphNode *> v = u->neighbours; int n = v.size(); for (int i = 0; i < n; i++) { if (!visit[v[i]]) { visit[v[i]] = true; q.push(v[i]); } } } cout << endl;} // Driver program to test above functionint main(){ GraphNode *src = buildGraph(); cout << "BFS Traversal before cloning\n"; bfs(src); GraphNode *newsrc = cloneGraph(src); cout << "BFS Traversal after cloning\n"; bfs(newsrc); return 0;}
// Java program to Clone an Undirected Graphimport java.util.*; // GraphNode class represents each// Node of the Graphclass GraphNode{ int val; // A neighbour Vector which contains references to // all the neighbours of a GraphNode Vector<GraphNode> neighbours; public GraphNode(int val) { this.val = val; neighbours = new Vector<GraphNode>(); }} class Graph{ // A method which clones the graph and // returns the reference of new cloned source node public GraphNode cloneGraph(GraphNode source) { Queue<GraphNode> q = new LinkedList<GraphNode>(); q.add(source); // An HashMap to keep track of all the // nodes which have already been created HashMap<GraphNode,GraphNode> hm = new HashMap<GraphNode,GraphNode>(); //Put the node into the HashMap hm.put(source,new GraphNode(source.val)); while (!q.isEmpty()) { // Get the front node from the queue // and then visit all its neighbours GraphNode u = q.poll(); // Get corresponding Cloned Graph Node GraphNode cloneNodeU = hm.get(u); if (u.neighbours != null) { Vector<GraphNode> v = u.neighbours; for (GraphNode graphNode : v) { // Get the corresponding cloned node // If the node is not cloned then we will // simply get a null GraphNode cloneNodeG = hm.get(graphNode); // Check if this node has already been created if (cloneNodeG == null) { q.add(graphNode); // If not then create a new Node and // put into the HashMap cloneNodeG = new GraphNode(graphNode.val); hm.put(graphNode,cloneNodeG); } // add the 'cloneNodeG' to neighbour // vector of the cloneNodeG cloneNodeU.neighbours.add(cloneNodeG); } } } // Return the reference of cloned source Node return hm.get(source); } // Build the desired graph public GraphNode buildGraph() { /* Note : All the edges are Undirected Given Graph: 1--2 | | 4--3 */ GraphNode node1 = new GraphNode(1); GraphNode node2 = new GraphNode(2); GraphNode node3 = new GraphNode(3); GraphNode node4 = new GraphNode(4); Vector<GraphNode> v = new Vector<GraphNode>(); v.add(node2); v.add(node4); node1.neighbours = v; v = new Vector<GraphNode>(); v.add(node1); v.add(node3); node2.neighbours = v; v = new Vector<GraphNode>(); v.add(node2); v.add(node4); node3.neighbours = v; v = new Vector<GraphNode>(); v.add(node3); v.add(node1); node4.neighbours = v; return node1; } // BFS traversal of a graph to // check if the cloned graph is correct public void bfs(GraphNode source) { Queue<GraphNode> q = new LinkedList<GraphNode>(); q.add(source); HashMap<GraphNode,Boolean> visit = new HashMap<GraphNode,Boolean>(); visit.put(source,true); while (!q.isEmpty()) { GraphNode u = q.poll(); System.out.println("Value of Node " + u.val); System.out.println("Address of Node " + u); if (u.neighbours != null) { Vector<GraphNode> v = u.neighbours; for (GraphNode g : v) { if (visit.get(g) == null) { q.add(g); visit.put(g,true); } } } } System.out.println(); }} // Driver codeclass Main{ public static void main(String args[]) { Graph graph = new Graph(); GraphNode source = graph.buildGraph(); System.out.println("BFS traversal of a graph before cloning"); graph.bfs(source); GraphNode newSource = graph.cloneGraph(source); System.out.println("BFS traversal of a graph after cloning"); graph.bfs(newSource); }}
BFS traversal of a graph before cloning
Value of Node 1
Address of Node GraphNode@15db9742
Value of Node 2
Address of Node GraphNode@6d06d69c
Value of Node 4
Address of Node GraphNode@7852e922
Value of Node 3
Address of Node GraphNode@4e25154f
BFS traversal of a graph after cloning
Value of Node 1
Address of Node GraphNode@70dea4e
Value of Node 2
Address of Node GraphNode@5c647e05
Value of Node 4
Address of Node GraphNode@33909752
Value of Node 3
Address of Node GraphNode@55f96302
Output in C++:
BFS Traversal before cloning
Value of Node 1
Address of Node 0x24ccc20
Value of Node 2
Address of Node 0x24ccc50
Value of Node 4
Address of Node 0x24cccb0
Value of Node 3
Address of Node 0x24ccc80
BFS Traversal after cloning
Value of Node 1
Address of Node 0x24cd030
Value of Node 2
Address of Node 0x24cd0e0
Value of Node 4
Address of Node 0x24cd170
Value of Node 3
Address of Node 0x24cd200
Clone an undirected graph with multiple connected components
This article is contributed by Chirag Agarwal. 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.
BFS
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Detect Cycle in a Directed Graph
Bellman–Ford Algorithm | DP-23
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Detect cycle in an undirected graph
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 | [
{
"code": null,
"e": 24757,
"s": 24729,
"text": "\n24 Jan, 2019"
},
{
"code": null,
"e": 24904,
"s": 24757,
"text": "Cloning of a LinkedList and a Binary Tree with random pointers has already been discussed. The idea behind cloning a graph is pretty much similar."
},
{
"code": null,
"e": 25112,
"s": 24904,
"text": "The idea is to do a BFS traversal of the graph and while visiting a node make a clone node of it (a copy of original node). If a node is encountered which is already visited then it already has a clone node."
},
{
"code": null,
"e": 25344,
"s": 25112,
"text": "How to keep track of the visited/cloned nodes?A HashMap/Map is required in order to maintain all the nodes which have already been created.Key stores: Reference/Address of original NodeValue stores: Reference/Address of cloned Node"
},
{
"code": null,
"e": 25724,
"s": 25344,
"text": "A copy of all the graph nodes has been made, how to connect clone nodes?While visiting the neighboring vertices of a node u get the corresponding cloned node for u , let’s call that cloneNodeU , now visit all the neighboring nodes for u and for each neighbor find the corresponding clone node(if not found create one) and then push into the neighboring vector of cloneNodeU node."
},
{
"code": null,
"e": 26075,
"s": 25724,
"text": "How to verify if the cloned graph is a correct?Do a BFS traversal before and after the cloning of graph. In BFS traversal display the value of a node along with its address/reference.Compare the order in which nodes are displayed, if the values are same but the address/reference is different for both the traversals than the cloned graph is correct."
},
{
"code": null,
"e": 26079,
"s": 26075,
"text": "C++"
},
{
"code": null,
"e": 26084,
"s": 26079,
"text": "Java"
},
{
"code": "// A C++ program to Clone an Undirected Graph#include<bits/stdc++.h>using namespace std; struct GraphNode{ int val; //A neighbour vector which contains addresses to //all the neighbours of a GraphNode vector<GraphNode*> neighbours;}; // A function which clones a Graph and// returns the address to the cloned// src nodeGraphNode *cloneGraph(GraphNode *src){ //A Map to keep track of all the //nodes which have already been created map<GraphNode*, GraphNode*> m; queue<GraphNode*> q; // Enqueue src node q.push(src); GraphNode *node; // Make a clone Node node = new GraphNode(); node->val = src->val; // Put the clone node into the Map m[src] = node; while (!q.empty()) { //Get the front node from the queue //and then visit all its neighbours GraphNode *u = q.front(); q.pop(); vector<GraphNode *> v = u->neighbours; int n = v.size(); for (int i = 0; i < n; i++) { // Check if this node has already been created if (m[v[i]] == NULL) { // If not then create a new Node and // put into the HashMap node = new GraphNode(); node->val = v[i]->val; m[v[i]] = node; q.push(v[i]); } // add these neighbours to the cloned graph node m[u]->neighbours.push_back(m[v[i]]); } } // Return the address of cloned src Node return m[src];} // Build the desired graphGraphNode *buildGraph(){ /* Note : All the edges are Undirected Given Graph: 1--2 | | 4--3 */ GraphNode *node1 = new GraphNode(); node1->val = 1; GraphNode *node2 = new GraphNode(); node2->val = 2; GraphNode *node3 = new GraphNode(); node3->val = 3; GraphNode *node4 = new GraphNode(); node4->val = 4; vector<GraphNode *> v; v.push_back(node2); v.push_back(node4); node1->neighbours = v; v.clear(); v.push_back(node1); v.push_back(node3); node2->neighbours = v; v.clear(); v.push_back(node2); v.push_back(node4); node3->neighbours = v; v.clear(); v.push_back(node3); v.push_back(node1); node4->neighbours = v; return node1;} // A simple bfs traversal of a graph to// check for proper cloning of the graphvoid bfs(GraphNode *src){ map<GraphNode*, bool> visit; queue<GraphNode*> q; q.push(src); visit[src] = true; while (!q.empty()) { GraphNode *u = q.front(); cout << \"Value of Node \" << u->val << \"\\n\"; cout << \"Address of Node \" <<u << \"\\n\"; q.pop(); vector<GraphNode *> v = u->neighbours; int n = v.size(); for (int i = 0; i < n; i++) { if (!visit[v[i]]) { visit[v[i]] = true; q.push(v[i]); } } } cout << endl;} // Driver program to test above functionint main(){ GraphNode *src = buildGraph(); cout << \"BFS Traversal before cloning\\n\"; bfs(src); GraphNode *newsrc = cloneGraph(src); cout << \"BFS Traversal after cloning\\n\"; bfs(newsrc); return 0;}",
"e": 29269,
"s": 26084,
"text": null
},
{
"code": "// Java program to Clone an Undirected Graphimport java.util.*; // GraphNode class represents each// Node of the Graphclass GraphNode{ int val; // A neighbour Vector which contains references to // all the neighbours of a GraphNode Vector<GraphNode> neighbours; public GraphNode(int val) { this.val = val; neighbours = new Vector<GraphNode>(); }} class Graph{ // A method which clones the graph and // returns the reference of new cloned source node public GraphNode cloneGraph(GraphNode source) { Queue<GraphNode> q = new LinkedList<GraphNode>(); q.add(source); // An HashMap to keep track of all the // nodes which have already been created HashMap<GraphNode,GraphNode> hm = new HashMap<GraphNode,GraphNode>(); //Put the node into the HashMap hm.put(source,new GraphNode(source.val)); while (!q.isEmpty()) { // Get the front node from the queue // and then visit all its neighbours GraphNode u = q.poll(); // Get corresponding Cloned Graph Node GraphNode cloneNodeU = hm.get(u); if (u.neighbours != null) { Vector<GraphNode> v = u.neighbours; for (GraphNode graphNode : v) { // Get the corresponding cloned node // If the node is not cloned then we will // simply get a null GraphNode cloneNodeG = hm.get(graphNode); // Check if this node has already been created if (cloneNodeG == null) { q.add(graphNode); // If not then create a new Node and // put into the HashMap cloneNodeG = new GraphNode(graphNode.val); hm.put(graphNode,cloneNodeG); } // add the 'cloneNodeG' to neighbour // vector of the cloneNodeG cloneNodeU.neighbours.add(cloneNodeG); } } } // Return the reference of cloned source Node return hm.get(source); } // Build the desired graph public GraphNode buildGraph() { /* Note : All the edges are Undirected Given Graph: 1--2 | | 4--3 */ GraphNode node1 = new GraphNode(1); GraphNode node2 = new GraphNode(2); GraphNode node3 = new GraphNode(3); GraphNode node4 = new GraphNode(4); Vector<GraphNode> v = new Vector<GraphNode>(); v.add(node2); v.add(node4); node1.neighbours = v; v = new Vector<GraphNode>(); v.add(node1); v.add(node3); node2.neighbours = v; v = new Vector<GraphNode>(); v.add(node2); v.add(node4); node3.neighbours = v; v = new Vector<GraphNode>(); v.add(node3); v.add(node1); node4.neighbours = v; return node1; } // BFS traversal of a graph to // check if the cloned graph is correct public void bfs(GraphNode source) { Queue<GraphNode> q = new LinkedList<GraphNode>(); q.add(source); HashMap<GraphNode,Boolean> visit = new HashMap<GraphNode,Boolean>(); visit.put(source,true); while (!q.isEmpty()) { GraphNode u = q.poll(); System.out.println(\"Value of Node \" + u.val); System.out.println(\"Address of Node \" + u); if (u.neighbours != null) { Vector<GraphNode> v = u.neighbours; for (GraphNode g : v) { if (visit.get(g) == null) { q.add(g); visit.put(g,true); } } } } System.out.println(); }} // Driver codeclass Main{ public static void main(String args[]) { Graph graph = new Graph(); GraphNode source = graph.buildGraph(); System.out.println(\"BFS traversal of a graph before cloning\"); graph.bfs(source); GraphNode newSource = graph.cloneGraph(source); System.out.println(\"BFS traversal of a graph after cloning\"); graph.bfs(newSource); }}",
"e": 33714,
"s": 29269,
"text": null
},
{
"code": null,
"e": 34202,
"s": 33714,
"text": "BFS traversal of a graph before cloning\nValue of Node 1\nAddress of Node GraphNode@15db9742\nValue of Node 2\nAddress of Node GraphNode@6d06d69c\nValue of Node 4\nAddress of Node GraphNode@7852e922\nValue of Node 3\nAddress of Node GraphNode@4e25154f\n\nBFS traversal of a graph after cloning\nValue of Node 1\nAddress of Node GraphNode@70dea4e\nValue of Node 2\nAddress of Node GraphNode@5c647e05\nValue of Node 4\nAddress of Node GraphNode@33909752\nValue of Node 3\nAddress of Node GraphNode@55f96302\n"
},
{
"code": null,
"e": 34217,
"s": 34202,
"text": "Output in C++:"
},
{
"code": null,
"e": 34612,
"s": 34217,
"text": "BFS Traversal before cloning\nValue of Node 1\nAddress of Node 0x24ccc20\nValue of Node 2\nAddress of Node 0x24ccc50\nValue of Node 4\nAddress of Node 0x24cccb0\nValue of Node 3\nAddress of Node 0x24ccc80\n\nBFS Traversal after cloning\nValue of Node 1\nAddress of Node 0x24cd030\nValue of Node 2\nAddress of Node 0x24cd0e0\nValue of Node 4\nAddress of Node 0x24cd170\nValue of Node 3\nAddress of Node 0x24cd200\n"
},
{
"code": null,
"e": 34673,
"s": 34612,
"text": "Clone an undirected graph with multiple connected components"
},
{
"code": null,
"e": 34975,
"s": 34673,
"text": "This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 35100,
"s": 34975,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 35104,
"s": 35100,
"text": "BFS"
},
{
"code": null,
"e": 35110,
"s": 35104,
"text": "Graph"
},
{
"code": null,
"e": 35116,
"s": 35110,
"text": "Graph"
},
{
"code": null,
"e": 35120,
"s": 35116,
"text": "BFS"
},
{
"code": null,
"e": 35218,
"s": 35120,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35227,
"s": 35218,
"text": "Comments"
},
{
"code": null,
"e": 35240,
"s": 35227,
"text": "Old Comments"
},
{
"code": null,
"e": 35298,
"s": 35240,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 35318,
"s": 35298,
"text": "Topological Sorting"
},
{
"code": null,
"e": 35351,
"s": 35318,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 35382,
"s": 35351,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 35450,
"s": 35382,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 35525,
"s": 35450,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 35561,
"s": 35525,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 35611,
"s": 35561,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 35659,
"s": 35611,
"text": "Traveling Salesman Problem (TSP) Implementation"
}
] |
SudachiPy: A Japanese Morphological Analyzer in Python | by Ng Wai Foong | Towards Data Science | Python version of Sudachi that focuses on Natural Language Processing (NLP) for Japanese text
This article covers the basic functionality of SudachiPy which can be used to perform simple natural language processing tasks such as tokenization for Japanese language. Based on the official Github page:
Sudachi & SudachiPy are developed in WAP Tokushima Laboratory of AI and NLP, an institute under Works Applications that focuses on Natural Language Processing (NLP).
The original version is in Java while SudachiPy is the python implementation of it. Having said that, some functions are still incompatible with Java Sudachi. This article consists of 4 main sections:
SetupCommand LineBasic UsageConclusion
Setup
Command Line
Basic Usage
Conclusion
Let’s get started by creating a virtual environment and activate it. Once you are done, run the following command in the terminal:
pip install SudachiPy
This will install the latest version of SudachiPy which is 0.3.11 at the time of this writing. SudachiPy‘s version that is higher that 0.3.0 refers to system.dic of SudachiDict_core package by default. This package is not included in SudachiPy and have to be installed manually.
You can install the package by running the following command:
pip install https://object-storage.tyo2.conoha.io/v1/nc_2520839e1f9641b08211a5c85243124a/sudachi/SudachiDict_core-20190718.tar.gz
It will automatically install the default dictionary. Let’s jump to the next section once you are ready. The paragraph below are meant for setting your own custom dictionary.
Sudachi provides us with 3 different kind of dictionaries
Small: includes only the vocabulary of UniDic
Core: includes basic vocabulary (default)
Full: includes miscellaneous proper nouns
You should be able to download a system.dic file. You can modify the dictionary to any built-in or custom dictionary.
Path modification: Create a sudachi.json and place it anywhere as you like. By default, the package contains this file at the following directory.
<virtual_env>/Lib/site-packages/sudachipy/resources/
You can choose to edit the file or create a new one and paste the following code:
Modify the systemDict to the relative path of systemDict to point to the system.dic file.
Direct Replacement: Go to the following directory:
<virtual_env>/Lib/site-packages/sudachidict_core/resources
You should be able to see just one file called system.dic
Replace the file with your custom dictionary or the one that you downloaded from official site.
If you are using Windows OS and experience issue with OSError: symbolic link privilege not held. Kindly run your terminal as administrator. Then, type the following and run it:
sudachipy link -t core
SudachiPy also provides us with a few commands line. You can straightaway use it once you have installed the SudachiPy and SudachiDict_core modules. I will just use it to test whether we have installed the modules correctly. There are 4 main usable commands:
tokenize
link
build
ubuild (contains bug when using version 0.3.*)
Open up a terminal and run the following command:
sudachipy tokenize -h
You should be able to see the following result.
If you encounter any issue, make sure that you have correctly install both the SudachiPy and SudachiDict_core modules.
First, let’s import the tokenizer and dictionary module.
from sudachipy import tokenizerfrom sudachipy import dictionary
Both of the modules are required to create a tokenizer object. Continue to add the following code:
tokenizer_obj = dictionary.Dictionary().create()
Next up, we will need to define the mode for the tokenizer. Mode is used to determine how the tokenizer should split the text.
A: texts are divided into the shortest units equivalent to the UniDic short unit
B: split the text into middle units between A and C
C: extracts named entities
Let’s test it out by setting it to mode A:
mode = tokenizer.Tokenizer.SplitMode.A
Create a new variable and assign any Japanese text. Then, call the tokenize function in a list comprehension as follow:
txt = "医薬品安全管理責任者"print([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])
You should be able to obtain the following results:
['医薬', '品', '安全', '管理', '責任', '者']
You can test it out to see the results for all three output as follow:
from sudachipy import tokenizerfrom sudachipy import dictionarytokenizer_obj = dictionary.Dictionary().create()txt = "医薬品安全管理責任者"mode = tokenizer.Tokenizer.SplitMode.Aprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])mode = tokenizer.Tokenizer.SplitMode.Bprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])mode = tokenizer.Tokenizer.SplitMode.Cprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])
Japanese language is known for the complicated verb conjugation. SudachiPy also provides a way for us to transform them freely via built-in functions. We will just going to explore three main functions that we can access after splitting the text via the tokenizer obj.
The first one is the original text which can be called using the surface() function
print([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])
Apart from that, we also have the dictionary_form() function
print([m.dictionary_form() for m in tokenizer_obj.tokenize(txt, mode)])
The last one is the normalized_form() function
print([m.normalized_form() for m in tokenizer_obj.tokenize(txt, mode)])
Let’s combine them together to see the difference:
from sudachipy import tokenizerfrom sudachipy import dictionarytokenizer_obj = dictionary.Dictionary().create()txt = "ゲームデータを消失してしまいました。"mode = tokenizer.Tokenizer.SplitMode.Aprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])print([m.normalized_form() for m in tokenizer_obj.tokenize(txt, mode)])print([m.dictionary_form() for m in tokenizer_obj.tokenize(txt, mode)])
You should be able to get the following results:
['ゲーム', 'データ', 'を', '消失', 'し', 'て', 'しまい', 'まし', 'た', '。']['ゲーム', 'データ', 'を', '消失', '為る', 'て', '仕舞う', 'ます', 'た', '。']['ゲーム', 'データ', 'を', '消失', 'する', 'て', 'しまう', 'ます', 'た', '。']
One of the most important feature in any Natural Language Processing is the part of speech tag. We can easily get it via the part_of_speech() function:
print([m.part_of_speech() for m in tokenizer_obj.tokenize(txt, mode)])
The output result is as follow:
[['名詞', '普通名詞', '一般', '*', '*', '*'], ['名詞', '普通名詞', '一般', '*', '*', '*'], ['助詞', '格助詞', '*', '*', '*', '*'], ['名詞', '普通名詞', 'サ変可能', '*', '*', '*'], ['動詞', '非自立可能', '*', '*', 'サ行変格', '連用形-一般'], ['助詞', '接続助詞', '*', '*', '*', '*'], ['動詞', '非自立可能', '*', '*', '五段-ワア行', '連用形-一般'], ['助動詞', '*', '*', '*', '助動詞-マス', '連用形-一般'], ['助動詞', '*', '*', '*', '助動詞-タ', '終止形-一般'], ['補助記号', '句点', '*', '*', '*', '*']]
Let’s recap on what we have learned today. We started out by installing the necessary python modules, SudachiPy and SudachiDict_core. There is also an option to configure it to load your own custom dictionary.
Then, we explored some basic commands that can be called in the terminal to test out the installation.
Next, we dive deep into the basic python codes to learn to tokenize the Japanese text. Besides, we can get the output tokens in dictionary or normalized form. Not to mention the part_of_speech() function that can help use to identify the POS tag for each of the tokens.
Thanks for reading and have a good day. See you in the next article. | [
{
"code": null,
"e": 266,
"s": 172,
"text": "Python version of Sudachi that focuses on Natural Language Processing (NLP) for Japanese text"
},
{
"code": null,
"e": 472,
"s": 266,
"text": "This article covers the basic functionality of SudachiPy which can be used to perform simple natural language processing tasks such as tokenization for Japanese language. Based on the official Github page:"
},
{
"code": null,
"e": 638,
"s": 472,
"text": "Sudachi & SudachiPy are developed in WAP Tokushima Laboratory of AI and NLP, an institute under Works Applications that focuses on Natural Language Processing (NLP)."
},
{
"code": null,
"e": 839,
"s": 638,
"text": "The original version is in Java while SudachiPy is the python implementation of it. Having said that, some functions are still incompatible with Java Sudachi. This article consists of 4 main sections:"
},
{
"code": null,
"e": 878,
"s": 839,
"text": "SetupCommand LineBasic UsageConclusion"
},
{
"code": null,
"e": 884,
"s": 878,
"text": "Setup"
},
{
"code": null,
"e": 897,
"s": 884,
"text": "Command Line"
},
{
"code": null,
"e": 909,
"s": 897,
"text": "Basic Usage"
},
{
"code": null,
"e": 920,
"s": 909,
"text": "Conclusion"
},
{
"code": null,
"e": 1051,
"s": 920,
"text": "Let’s get started by creating a virtual environment and activate it. Once you are done, run the following command in the terminal:"
},
{
"code": null,
"e": 1073,
"s": 1051,
"text": "pip install SudachiPy"
},
{
"code": null,
"e": 1352,
"s": 1073,
"text": "This will install the latest version of SudachiPy which is 0.3.11 at the time of this writing. SudachiPy‘s version that is higher that 0.3.0 refers to system.dic of SudachiDict_core package by default. This package is not included in SudachiPy and have to be installed manually."
},
{
"code": null,
"e": 1414,
"s": 1352,
"text": "You can install the package by running the following command:"
},
{
"code": null,
"e": 1544,
"s": 1414,
"text": "pip install https://object-storage.tyo2.conoha.io/v1/nc_2520839e1f9641b08211a5c85243124a/sudachi/SudachiDict_core-20190718.tar.gz"
},
{
"code": null,
"e": 1719,
"s": 1544,
"text": "It will automatically install the default dictionary. Let’s jump to the next section once you are ready. The paragraph below are meant for setting your own custom dictionary."
},
{
"code": null,
"e": 1777,
"s": 1719,
"text": "Sudachi provides us with 3 different kind of dictionaries"
},
{
"code": null,
"e": 1823,
"s": 1777,
"text": "Small: includes only the vocabulary of UniDic"
},
{
"code": null,
"e": 1865,
"s": 1823,
"text": "Core: includes basic vocabulary (default)"
},
{
"code": null,
"e": 1907,
"s": 1865,
"text": "Full: includes miscellaneous proper nouns"
},
{
"code": null,
"e": 2025,
"s": 1907,
"text": "You should be able to download a system.dic file. You can modify the dictionary to any built-in or custom dictionary."
},
{
"code": null,
"e": 2172,
"s": 2025,
"text": "Path modification: Create a sudachi.json and place it anywhere as you like. By default, the package contains this file at the following directory."
},
{
"code": null,
"e": 2225,
"s": 2172,
"text": "<virtual_env>/Lib/site-packages/sudachipy/resources/"
},
{
"code": null,
"e": 2307,
"s": 2225,
"text": "You can choose to edit the file or create a new one and paste the following code:"
},
{
"code": null,
"e": 2397,
"s": 2307,
"text": "Modify the systemDict to the relative path of systemDict to point to the system.dic file."
},
{
"code": null,
"e": 2448,
"s": 2397,
"text": "Direct Replacement: Go to the following directory:"
},
{
"code": null,
"e": 2507,
"s": 2448,
"text": "<virtual_env>/Lib/site-packages/sudachidict_core/resources"
},
{
"code": null,
"e": 2565,
"s": 2507,
"text": "You should be able to see just one file called system.dic"
},
{
"code": null,
"e": 2661,
"s": 2565,
"text": "Replace the file with your custom dictionary or the one that you downloaded from official site."
},
{
"code": null,
"e": 2838,
"s": 2661,
"text": "If you are using Windows OS and experience issue with OSError: symbolic link privilege not held. Kindly run your terminal as administrator. Then, type the following and run it:"
},
{
"code": null,
"e": 2861,
"s": 2838,
"text": "sudachipy link -t core"
},
{
"code": null,
"e": 3120,
"s": 2861,
"text": "SudachiPy also provides us with a few commands line. You can straightaway use it once you have installed the SudachiPy and SudachiDict_core modules. I will just use it to test whether we have installed the modules correctly. There are 4 main usable commands:"
},
{
"code": null,
"e": 3129,
"s": 3120,
"text": "tokenize"
},
{
"code": null,
"e": 3134,
"s": 3129,
"text": "link"
},
{
"code": null,
"e": 3140,
"s": 3134,
"text": "build"
},
{
"code": null,
"e": 3187,
"s": 3140,
"text": "ubuild (contains bug when using version 0.3.*)"
},
{
"code": null,
"e": 3237,
"s": 3187,
"text": "Open up a terminal and run the following command:"
},
{
"code": null,
"e": 3259,
"s": 3237,
"text": "sudachipy tokenize -h"
},
{
"code": null,
"e": 3307,
"s": 3259,
"text": "You should be able to see the following result."
},
{
"code": null,
"e": 3426,
"s": 3307,
"text": "If you encounter any issue, make sure that you have correctly install both the SudachiPy and SudachiDict_core modules."
},
{
"code": null,
"e": 3483,
"s": 3426,
"text": "First, let’s import the tokenizer and dictionary module."
},
{
"code": null,
"e": 3547,
"s": 3483,
"text": "from sudachipy import tokenizerfrom sudachipy import dictionary"
},
{
"code": null,
"e": 3646,
"s": 3547,
"text": "Both of the modules are required to create a tokenizer object. Continue to add the following code:"
},
{
"code": null,
"e": 3695,
"s": 3646,
"text": "tokenizer_obj = dictionary.Dictionary().create()"
},
{
"code": null,
"e": 3822,
"s": 3695,
"text": "Next up, we will need to define the mode for the tokenizer. Mode is used to determine how the tokenizer should split the text."
},
{
"code": null,
"e": 3903,
"s": 3822,
"text": "A: texts are divided into the shortest units equivalent to the UniDic short unit"
},
{
"code": null,
"e": 3955,
"s": 3903,
"text": "B: split the text into middle units between A and C"
},
{
"code": null,
"e": 3982,
"s": 3955,
"text": "C: extracts named entities"
},
{
"code": null,
"e": 4025,
"s": 3982,
"text": "Let’s test it out by setting it to mode A:"
},
{
"code": null,
"e": 4064,
"s": 4025,
"text": "mode = tokenizer.Tokenizer.SplitMode.A"
},
{
"code": null,
"e": 4184,
"s": 4064,
"text": "Create a new variable and assign any Japanese text. Then, call the tokenize function in a list comprehension as follow:"
},
{
"code": null,
"e": 4266,
"s": 4184,
"text": "txt = \"医薬品安全管理責任者\"print([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])"
},
{
"code": null,
"e": 4318,
"s": 4266,
"text": "You should be able to obtain the following results:"
},
{
"code": null,
"e": 4353,
"s": 4318,
"text": "['医薬', '品', '安全', '管理', '責任', '者']"
},
{
"code": null,
"e": 4424,
"s": 4353,
"text": "You can test it out to see the results for all three output as follow:"
},
{
"code": null,
"e": 4857,
"s": 4424,
"text": "from sudachipy import tokenizerfrom sudachipy import dictionarytokenizer_obj = dictionary.Dictionary().create()txt = \"医薬品安全管理責任者\"mode = tokenizer.Tokenizer.SplitMode.Aprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])mode = tokenizer.Tokenizer.SplitMode.Bprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])mode = tokenizer.Tokenizer.SplitMode.Cprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])"
},
{
"code": null,
"e": 5126,
"s": 4857,
"text": "Japanese language is known for the complicated verb conjugation. SudachiPy also provides a way for us to transform them freely via built-in functions. We will just going to explore three main functions that we can access after splitting the text via the tokenizer obj."
},
{
"code": null,
"e": 5210,
"s": 5126,
"text": "The first one is the original text which can be called using the surface() function"
},
{
"code": null,
"e": 5274,
"s": 5210,
"text": "print([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])"
},
{
"code": null,
"e": 5335,
"s": 5274,
"text": "Apart from that, we also have the dictionary_form() function"
},
{
"code": null,
"e": 5407,
"s": 5335,
"text": "print([m.dictionary_form() for m in tokenizer_obj.tokenize(txt, mode)])"
},
{
"code": null,
"e": 5454,
"s": 5407,
"text": "The last one is the normalized_form() function"
},
{
"code": null,
"e": 5526,
"s": 5454,
"text": "print([m.normalized_form() for m in tokenizer_obj.tokenize(txt, mode)])"
},
{
"code": null,
"e": 5577,
"s": 5526,
"text": "Let’s combine them together to see the difference:"
},
{
"code": null,
"e": 5960,
"s": 5577,
"text": "from sudachipy import tokenizerfrom sudachipy import dictionarytokenizer_obj = dictionary.Dictionary().create()txt = \"ゲームデータを消失してしまいました。\"mode = tokenizer.Tokenizer.SplitMode.Aprint([m.surface() for m in tokenizer_obj.tokenize(txt, mode)])print([m.normalized_form() for m in tokenizer_obj.tokenize(txt, mode)])print([m.dictionary_form() for m in tokenizer_obj.tokenize(txt, mode)])"
},
{
"code": null,
"e": 6009,
"s": 5960,
"text": "You should be able to get the following results:"
},
{
"code": null,
"e": 6192,
"s": 6009,
"text": "['ゲーム', 'データ', 'を', '消失', 'し', 'て', 'しまい', 'まし', 'た', '。']['ゲーム', 'データ', 'を', '消失', '為る', 'て', '仕舞う', 'ます', 'た', '。']['ゲーム', 'データ', 'を', '消失', 'する', 'て', 'しまう', 'ます', 'た', '。']"
},
{
"code": null,
"e": 6344,
"s": 6192,
"text": "One of the most important feature in any Natural Language Processing is the part of speech tag. We can easily get it via the part_of_speech() function:"
},
{
"code": null,
"e": 6415,
"s": 6344,
"text": "print([m.part_of_speech() for m in tokenizer_obj.tokenize(txt, mode)])"
},
{
"code": null,
"e": 6447,
"s": 6415,
"text": "The output result is as follow:"
},
{
"code": null,
"e": 6847,
"s": 6447,
"text": "[['名詞', '普通名詞', '一般', '*', '*', '*'], ['名詞', '普通名詞', '一般', '*', '*', '*'], ['助詞', '格助詞', '*', '*', '*', '*'], ['名詞', '普通名詞', 'サ変可能', '*', '*', '*'], ['動詞', '非自立可能', '*', '*', 'サ行変格', '連用形-一般'], ['助詞', '接続助詞', '*', '*', '*', '*'], ['動詞', '非自立可能', '*', '*', '五段-ワア行', '連用形-一般'], ['助動詞', '*', '*', '*', '助動詞-マス', '連用形-一般'], ['助動詞', '*', '*', '*', '助動詞-タ', '終止形-一般'], ['補助記号', '句点', '*', '*', '*', '*']]"
},
{
"code": null,
"e": 7057,
"s": 6847,
"text": "Let’s recap on what we have learned today. We started out by installing the necessary python modules, SudachiPy and SudachiDict_core. There is also an option to configure it to load your own custom dictionary."
},
{
"code": null,
"e": 7160,
"s": 7057,
"text": "Then, we explored some basic commands that can be called in the terminal to test out the installation."
},
{
"code": null,
"e": 7430,
"s": 7160,
"text": "Next, we dive deep into the basic python codes to learn to tokenize the Japanese text. Besides, we can get the output tokens in dictionary or normalized form. Not to mention the part_of_speech() function that can help use to identify the POS tag for each of the tokens."
}
] |
Data Science and Machine Learning with Scala and Spark (Episode 02/03) | by MA Raza, Ph.D. | Towards Data Science | Spark’s inventors chose Scala to write the low-level modules. In Data Science and Machine Learning with Scala and Spark (Episode 01/03), we covered the basics of Scala programming language while using a Google Colab environment. In this article, we learn about the Spark ecosystem and its higher-level API for Scala users. As before, we still use Spark 3.0.0 and Google Colab for practicing some code snippets.
According to Apache Spark and Delta Lake Under the Hood
Apache Spark is a unified computing engine and a set of libraries for parallel data processing on computer clusters. As of the time this writing, Spark is the most actively developed open source engine for this task; making it the de facto tool for any developer or data scientist interested in big data. Spark supports multiple widely used programming languages (Python, Java, Scala and R), includes libraries for diverse tasks ranging from SQL to streaming and machine learning, and runs anywhere from a laptop to a cluster of thousands of servers. This makes it an easy system to start with and scale up to big data processing or incredibly large scale.
I highly recommend reading the Apache Spark and Delta Lake Under the Hood quick reference booklet. It is a 45-page document with examples in Scala and pyspark APIs and would not take more than 30 minutes to go through.
Being a data scientist, we can ask the question “what is the importance of Spark for machine learning tasks?” With the increase in the use of electronic devices, social media platforms, and advanced IT systems rollouts, data is being generated at a level never seen before. Also, due to cheap data storage, clients are happy to collect big data for values to be extracted. Machine Learning models have been proven and work for business to better understand and strategize for future expansions. For having access to big data, Spark is the de-facto choice for machine learning to churn through enormous volumes of collected data to build models.
DataFrame API is the most important higher-level API for Machine Learning. Spark’s MLlib has dropped the support of RDD in favor of DataFrame API.
Scala was selected to be the core the language to write the Spark engine. However, Apache Spark provides high-level APIs in Java, Scala, Python, and R. In this article, we will use spark 3.0.0.
Below are the commands to get modules for Scala and Spark in Google colab
// Run below commandsimport $ivy.`org.apache.spark::spark-sql:3.0.0`import org.apache.spark.sql._import $ivy.`sh.almond::ammonite-spark:0.3.0`
There are two important abstractions of Spark, Spark Context, and Spark Session. Using the below lines, we create a spark session and context.
import org.apache.spark.SparkContextimport org.apache.spark.SparkConf
Usually, when running spark there are a lot of warnings, using below commands, you can turn them off.
// TIP: Turn off the millions lines of logsimport org.apache.log4j.{Level, Logger}Logger.getLogger(“org”).setLevel(Level.OFF)// define spark sessionval spark = {SparkSession.builder().master("local[*]").getOrCreate()}// Define Spark Contextdef sc = spark.sparkContext
Resilient Distributed Datasets (RDD) is the most common abstraction of Spark data structure related closely with Scala. It is very similar to Scala native parallel feature. Let's write some snippets about RRD in Scala.
// Spark RDDimport scala.util.Random// Define variable in Scalaval bigRng = scala.util.Random.shuffle(1 to 100000)// convert Scala variable to spark RDDval bigPRng = sc.parallelize(bigRng)
You can apply many operations on bigPRng , it will run on Spark.
// calculate the mean of the populationbigPRng.mean// Find the min of the populationbigPRng.min// Find the stanndard deviation of the populationbigPRng.popStdev
Applying the function on each element of RDD is very similar to Scala parallel map function.
// Map function on RDD, similar to Paralell in Scalaval bigPRng2 = bigPRng.map(_ * 2)// Scala function function to apply on RDDdef div3(x:Int) : Boolean = {val y:Int=(x%3); return(y==0)}val bigBool = bigPRng2.map(div3(_))
In the previous sections, we have included examples about the RDD and how RDD can be used to compute in parallel. Another popular API in spark is Dataframe. Coming from a Data Scientist background, probably, DataFrame API would make more sense. However, there is a major difference is how to spark data frames and pandas data frames operate under the hood.
Spark DataFrames can live on multiple physical machines and hence their computations are performed in distributed way opposed to pandas DataFrames.
Spark MLlib is implemented in DataFrame API going forward.
Let us learn some basic tricks of Spark DataFrame API mostly useful for machine learning tasks.
Read through Section 0 in the Google colab about the preparation of data for below snippets.
// Read the .txt fileval df_emps = spark.read.option("header", "true").csv(data_dir + "employee.txt")// print the schemadf_emps.printSchema()// show top 10 records similar to df.head(10) in pandasdf_emps.show(10, false)
Read the second table
// Read the .txt fileval df_cr = spark.read.option("header", "true").csv(data_dir + "country_region.txt")// print the schemadf_cr.printSchema()// show top 10 records similar to df.head(10) in pandasdf_cr.show(10, false)
Read the third table
// Read the .txt fileval df_dd = spark.read.option("header", "true").csv(data_dir + "dept_div.txt")// print the schemadf_dd.printSchema()// show top 10 records similar to df.head(10) in pandasdf_dd.show(10, false)
Merging is one of the most common and efficient operations in Spark compared with pandas.
// Merge all three tablesval df_joined = df_emps.join(df_cr, "region_id").join(df_dd, "department")
I have prepared a functional Google colab notebook. Feel free to use the notebook for practice.
In this tutorial, we will learn data science and machine learning with scala.
SCALA is functional and objecte oriented progarmming running with JVM with aim to be scalable hence name as SCALA.
Spark is written in scala which makes scala a native choice for processing big data. We will also cover the basic of using scala with spark and machine learning using spark and scala.
Key Objectives
Install Scala to work with Google Colab
Introduction and basics of Scala
Scala for Data Science
Scala with Spark Introduction
Machine Learning with Scala
Install Scala to work with Google Colab
Introduction and basics of Scala
Scala for Data Science
Scala with Spark Introduction
Machine Learning with Scala
Above is the bigger scope of this tutorial. The aim is to provide a working google colab notebook for all above sections.
In this tutorial, we will focus on spark computations using Scala.
To get a better understanding of spark framework and its modules, I would highly recommend [Apache SparkTM Under the Hood] https://databricks.com/p/ebook/apache-spark-under-the-hood. We will go through some of the examples given in this hand book. Therefore, download the associated data from this github data Location.
Another source is using excercise files from https://www.lynda.com/Scala-tutorials/Scala-Essential-Training-Data-Science/559182-2.html
I have downloaded the data and put it together in one of my repositories for easy access on this consoldated blog data
We need to mount the google drive to read the data stored in google drive. Below is the simplest way to mount it. You will asked to enter the token generated by your access procedure. Her eis the link to the article about mounting gdrive
from google.colab import drive
drive.mount('/content/drive')
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly
Enter your authorization code:
··········
Mounted at /content/drive
# Location of exercise data (I have uploaded the data to my google drive). Youhave to change to your location.
root_example_data = '/content/drive/My Drive/scala_machine_learning/'
!ls '/content/drive/My Drive/scala_machine_learning/'
departuredelays.csv.gz Ex_Files_Scala_EssT_Data_Science
I followed the tutorial Machine Learning with Scala in Google Colaboratory by Shadad Laddad to start Scala kernel in the google colab.
If you get a "scala" kernel not recognized warning when loading up the notebook for the first time, start by running the two cells below. Once you are done reload the page to load the notebook in the installed Scala kernel.
%%shell
SCALA_VERSION=2.12.8 ALMOND_VERSION=0.3.0+16-548dc10f-SNAPSHOT
curl -Lo coursier https://git.io/coursier-cli
chmod +x coursier
./coursier bootstrap \
-r jitpack -r sonatype:snapshots \
-i user -I user:sh.almond:scala-kernel-api_$SCALA_VERSION:$ALMOND_VERSION \
sh.almond:scala-kernel_$SCALA_VERSION:$ALMOND_VERSION \
--sources --default=true \
-o almond-snapshot --embed-files=false
rm coursier
./almond-snapshot --install --global --force
rm almond-snapshot
%%shell
echo "{
\"language\" : \"scala\",
\"display_name\" : \"Scala\",
\"argv\" : [
\"bash\",
\"-c\",
\"env LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libpython3.6m.so:\$LD_PRELOAD java -jar /usr/local/share/jupyter/kernels/scala/launcher.jar --connection-file {connection_file}\"
]
}" > /usr/local/share/jupyter/kernels/scala/kernel.json
Lets check if the scala is working or not. if it does not work refresh the page.
println("Hello, world!")
Hello, world!
Apache Spark is a lightning fast cluster computing system solving the limititaion of previously favoutite MapReduce systems for large data sets. It is the framework of choice among data scientists and machine learning engineers to work with big data problems.
Scala was selected is preffered languange to write Spark engine. However Apcahe Spark privides high level APIs in Java, Scala, Python and R.
According to Apache Spark Introduction for Beginners
Spark is one of Hadoop's sub venture created in 2009 in UC Berkeley's AMPLab by Matei Zaharia. It was Open Sourced in 2010 under a BSD license. It was given to Apache programming establishment in 2013, and now Apache Spark has turned into the best level Apache venture from Feb-2014. And now the results are pretty booming.
Spark 3.0.0 released on 18th June 2020 after passing the vote on 10th of June 2020. However, the preview of Spark 3.0.0 was released late 2019.
Spark 3.0 is roughly two times faster than Spark 2.4
In this tutorial, we will use Scala as higher level API to run spark computations.
To learn more about Spark, you may want to read below articles
https://towardsdatascience.com/introduction-to-apache-spark-207a479c3001
https://spark.apache.org/
https://medium.com/@amjadraza24/spark-ifying-pandas-databricks-koalas-with-google-colab-93028890db5
https://medium.com/@amjadraza24/getting-started-spark3-0-0-with-google-colab-9796d350d78
https://towardsdatascience.com/introduction-to-apache-spark-207a479c3001
https://spark.apache.org/
https://medium.com/@amjadraza24/spark-ifying-pandas-databricks-koalas-with-google-colab-93028890db5
https://medium.com/@amjadraza24/getting-started-spark3-0-0-with-google-colab-9796d350d78
// Run below commands
import $ivy.`org.apache.spark::spark-sql:3.0.0`
import $ivy.$
import org.apache.spark.sql._
import org.apache.spark.sql._
import $ivy.`sh.almond::ammonite-spark:0.3.0`
import $ivy.$
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
// TIP: Turn off the millions lines of logs
import org.apache.log4j.{Level, Logger}
Logger.getLogger("org").setLevel(Level.OFF)
import org.apache.log4j.{Level, Logger}
val conf = new SparkConf().setAppName("test_scala_machine_learning").setMaster("local[*]")
new SparkContext(conf)
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
conf: SparkConf = org.apache.spark.SparkConf@34a88b7a
res6_1: SparkContext = org.apache.spark.SparkContext@5368b6be
# spark.stop()
20/06/21 09:04:44 INFO SparkContext: SparkContext already stopped.
val spark = {
SparkSession.builder()
.master("local[*]")
.getOrCreate()
}
spark: SparkSession = org.apache.spark.sql.SparkSession@7dec4dc6
def sc = spark.sparkContext
defined function sc
Resilient Distributed Datasets (RDD) is the most common abstraction of Spark data structure related closely with Scala. It is very similar to Scala native parallel feature. Let's write some snippets about RRD in Scala.
// Spark RDD
import scala.util.Random
import scala.util.Random
val bigRng = scala.util.Random.shuffle(1 to 100000)
bigRng: collection.immutable.IndexedSeq[Int] = Vector(
56811,
43866,
39908,
15474,
21501,
96554,
29846,
56881,
29337,
12277,
98105,
31018,
49771,
86256,
43551,
66319,
50308,
57732,
27969,
15028,
60441,
4125,
92598,
29572,
22279,
39084,
73300,
64156,
19123,
50993,
81177,
59026,
70870,
42779,
15839,
52508,
22562,
69156,
...
// convert to RDD
val bigPRng = sc.parallelize(bigRng)
bigPRng: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[0] at parallelize at cmd11.sc:1
// calculate the mean of the population
bigPRng.mean
res12: Double = 50000.50000000018
// Find the min of the population
bigPRng.min
res25: Int = 1
// Find the max of the population
bigPRng.max
res13: Int = 100000
// Find the stanndard deviation of the population
bigPRng.popStdev
res14: Double = 28867.513458037993
bigPRng.take(25)
res28: Array[Int] = Array(
95614,
44945,
85237,
90417,
92032,
55788,
14288,
32807,
44044,
9755,
3331,
94537,
5991,
61000,
35500,
84313,
49472,
29350,
92789,
78992,
42190,
60047,
15325,
84589,
49274
)
// Map function on RDD, similar to Paralell in Scala
val bigPRng2 = bigPRng.map(_ * 2)
bigPRng2: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[5] at map at cmd15.sc:1
bigPRng2.take(25)
res30: Array[Int] = Array(
191228,
89890,
170474,
180834,
184064,
111576,
28576,
65614,
88088,
19510,
6662,
189074,
11982,
122000,
71000,
168626,
98944,
58700,
185578,
157984,
84380,
120094,
30650,
169178,
98548
)
bigPRng2.mean()
res16: Double = 100001.00000000036
// Scala function function to apply on RDD
def div3(x:Int) : Boolean = {val y:Int=(x%3); return(y==0)}
defined function div3
div3(9)
res18: Boolean = true
val bigBool = bigPRng2.map(div3(_))
bigBool: org.apache.spark.rdd.RDD[Boolean] = MapPartitionsRDD[8] at map at cmd19.sc:1
bigBool.take(25)
res20: Array[Boolean] = Array(
true,
true,
false,
true,
true,
false,
false,
false,
true,
false,
false,
false,
false,
true,
true,
false,
false,
true,
true,
false,
true,
true,
true,
false,
false
)
In the previous sections, we have included examples about the RDD and how RDD can be used to compute in parallel. Another popular API in spark is Dataframe. Coming from a Data Scientist background, probably, DataFrame API would make more sense. However, there is a major difference is how to spark data frames and pandas data frames operate under the hood.
Spark DataFrames can live on multiple physical machines and hence their computations are performed in distributed way opposed to pandas DataFrames.
Spark MLlib is implemented in DataFrame API going forward.
Let us learn some basic tricks of Spark DataFrame API mostly useful for machine learning tasks.
//spark data frames
val data_dir = "/content/drive/My Drive//scala_machine_learning/Ex_Files_Scala_EssT_Data_Science/Exercise Files/Chapter 5/05_01/"
data_dir: String = "/content/drive/My Drive//scala_machine_learning/Ex_Files_Scala_EssT_Data_Science/Exercise Files/Chapter 5/05_01/"
val df_emps = spark.read.option("header", "true").csv(data_dir + "employee.txt")
df_emps: DataFrame = [id: string, last_name: string ... 7 more fields]
// print schema
df_emps.printSchema()
root
|-- id: string (nullable = true)
|-- last_name: string (nullable = true)
|-- email: string (nullable = true)
|-- gender: string (nullable = true)
|-- department: string (nullable = true)
|-- start_date: string (nullable = true)
|-- salary: string (nullable = true)
|-- job_title: string (nullable = true)
|-- region_id: string (nullable = true)
// show top 10 records similar to df.head(10) in pandas
df_emps.show(10, false)
+---+------------+----------------------------+--------+------------+------------+------+----------------------------+---------+
|id |last_name |email |gender |department |start_date |salary|job_title |region_id|
+---+------------+----------------------------+--------+------------+------------+------+----------------------------+---------+
|1 |'Kelley' |'[email protected]' |'Female'|'Computers' |'10/2/2009' |67470 |'Structural Engineer' |2 |
|2 |'Armstrong' |'[email protected]'|'Male' |'Sports' |'3/31/2008' |71869 |'Financial Advisor' |2 |
|3 |'Carr' |'[email protected]' |'Male' |'Automotive'|'7/12/2009' |101768|'Recruiting Manager' |3 |
|4 |'Murray' |'[email protected]' |'Female'|'Jewelery' |'12/25/2014'|96897 |'Desktop Support Technician'|3 |
|5 |'Ellis' |'[email protected]' |'Female'|'Grocery' |'9/19/2002' |63702 |'Software Engineer III' |7 |
|6 |'Phillips' |'[email protected]' |'Male' |'Tools' |'8/21/2013' |118497|'Executive Secretary' |1 |
|7 |'Williamson'|'[email protected]' |'Male' |'Computers' |'5/14/2006' |65889 |'Dental Hygienist' |6 |
|8 |'Harris' |'[email protected]' |'Female'|'Toys' |'8/12/2003' |84427 |'Safety Technician I' |4 |
|9 |'James' |'[email protected]' |'Male' |'Jewelery' |'9/7/2005' |108657|'Sales Associate' |2 |
|10 |'Sanchez' |'[email protected]' |'Male' |'Movies' |'3/13/2013' |108093|'Sales Representative' |1 |
+---+------------+----------------------------+--------+------------+------------+------+----------------------------+---------+
only showing top 10 rows
val df_cr = spark.read.option("header", "true").csv(data_dir + "country_region.txt")
df_cr: DataFrame = [region_id: string, company_regions: string ... 1 more field]
df_cr.printSchema()
root
|-- region_id: string (nullable = true)
|-- company_regions: string (nullable = true)
|-- country: string (nullable = true)
df_cr.show(10, false)
+---------+-------------------+---------+
|region_id|company_regions |country |
+---------+-------------------+---------+
|1 | 'Northeast' | 'USA' |
|2 | 'Southeast' | 'USA' |
|3 | 'Northwest' | 'USA' |
|4 | 'Southwest' | 'USA' |
|5 | 'British Columbia'| 'Canada'|
|6 | 'Quebec' | 'Canada'|
|7 | 'Nova Scotia' | 'Canada'|
+---------+-------------------+---------+
val df_dd = spark.read.option("header", "true").csv(data_dir + "dept_div.txt")
df_dd: DataFrame = [department: string, company_division: string]
df_dd.show(10, false)
+-------------+----------------------+
|department |company_division |
+-------------+----------------------+
|'Automotive' |'Auto & Hardware' |
|'Baby' |'Domestic' |
|'Beauty' |'Domestic' |
|'Clothing' |'Domestic' |
|'Computers' |'Electronic Equipment'|
|'Electronics'|'Electronic Equipment'|
|'Games' |'Domestic' |
|'Garden' |'Outdoors & Garden' |
|'Grocery' |'Domestic' |
|'Health' |'Domestic' |
+-------------+----------------------+
only showing top 10 rows
// merge all thres tables
val df_joined = df_emps.join(df_cr, "region_id").join(df_dd, "department")
df_joined: DataFrame = [department: string, region_id: string ... 10 more fields]
df_joined.columns
res35: Array[String] = Array(
"department",
"region_id",
"id",
"last_name",
"email",
"gender",
"start_date",
"salary",
"job_title",
"company_regions",
"country",
"company_division"
)
df_joined.show(20, false)
+-------------+---------+---+------------+----------------------------+--------+------------+------+-------------------------------+-------------------+---------+----------------------+
|department |region_id|id |last_name |email |gender |start_date |salary|job_title |company_regions |country |company_division |
+-------------+---------+---+------------+----------------------------+--------+------------+------+-------------------------------+-------------------+---------+----------------------+
|'Computers' |2 |1 |'Kelley' |'[email protected]' |'Female'|'10/2/2009' |67470 |'Structural Engineer' | 'Southeast' | 'USA' |'Electronic Equipment'|
|'Sports' |2 |2 |'Armstrong' |'[email protected]'|'Male' |'3/31/2008' |71869 |'Financial Advisor' | 'Southeast' | 'USA' |'Games & Sports' |
|'Automotive' |3 |3 |'Carr' |'[email protected]' |'Male' |'7/12/2009' |101768|'Recruiting Manager' | 'Northwest' | 'USA' |'Auto & Hardware' |
|'Jewelery' |3 |4 |'Murray' |'[email protected]' |'Female'|'12/25/2014'|96897 |'Desktop Support Technician' | 'Northwest' | 'USA' |'Fashion' |
|'Grocery' |7 |5 |'Ellis' |'[email protected]' |'Female'|'9/19/2002' |63702 |'Software Engineer III' | 'Nova Scotia' | 'Canada'|'Domestic' |
|'Tools' |1 |6 |'Phillips' |'[email protected]' |'Male' |'8/21/2013' |118497|'Executive Secretary' | 'Northeast' | 'USA' |'Auto & Hardware' |
|'Computers' |6 |7 |'Williamson'|'[email protected]' |'Male' |'5/14/2006' |65889 |'Dental Hygienist' | 'Quebec' | 'Canada'|'Electronic Equipment'|
|'Toys' |4 |8 |'Harris' |'[email protected]' |'Female'|'8/12/2003' |84427 |'Safety Technician I' | 'Southwest' | 'USA' |'Games & Sports' |
|'Jewelery' |2 |9 |'James' |'[email protected]' |'Male' |'9/7/2005' |108657|'Sales Associate' | 'Southeast' | 'USA' |'Fashion' |
|'Movies' |1 |10 |'Sanchez' |'[email protected]' |'Male' |'3/13/2013' |108093|'Sales Representative' | 'Northeast' | 'USA' |'Entertainment' |
|'Jewelery' |7 |11 |'Jacobs' |'[email protected]' |'Female'|'11/27/2003'|121966|'Community Outreach Specialist'| 'Nova Scotia' | 'Canada'|'Fashion' |
|'Clothing' |7 |12 |'Black' |'[email protected]' |'Male' |'2/4/2003' |44179 |'Data Coordiator' | 'Nova Scotia' | 'Canada'|'Domestic' |
|'Baby' |3 |13 |'Schmidt' |'[email protected]' |'Male' |'10/13/2002'|85227 |'Compensation Analyst' | 'Northwest' | 'USA' |'Domestic' |
|'Computers' |4 |14 |'Webb' |'[email protected]' |'Female'|'10/22/2006'|59763 |'Software Test Engineer III' | 'Southwest' | 'USA' |'Electronic Equipment'|
|'Games' |7 |15 |'Jacobs' |'[email protected]' |'Female'|'3/4/2007' |141139|'Community Outreach Specialist'| 'Nova Scotia' | 'Canada'|'Domestic' |
|'Baby' |1 |16 |'Medina' |'[email protected]' |'Female'|'3/14/2008' |106659|'Web Developer III' | 'Northeast' | 'USA' |'Domestic' |
|'Kids' |6 |17 |'Morgan' |'[email protected]' |'Female'|'5/4/2011' |148952|'Programmer IV' | 'Quebec' | 'Canada'|'Domestic' |
|'Home' |5 |18 |'Nguyen' |'[email protected]' |'Male' |'11/3/2014' |93804 |'Geologist II' | 'British Columbia'| 'Canada'|'Domestic' |
|'Electronics'|3 |19 |'Day' |'[email protected]' |'Male' |'9/22/2004' |109890|'VP Sales' | 'Northwest' | 'USA' |'Electronic Equipment'|
|'Movies' |5 |20 |'Carr' |'[email protected]' |'Female'|'11/22/2007'|115274|'VP Quality Control' | 'British Columbia'| 'Canada'|'Entertainment' |
+-------------+---------+---+------------+----------------------------+--------+------------+------+-------------------------------+-------------------+---------+----------------------+
only showing top 20 rows
for more examples, you can follow the official documentations at
In this episode, we have learned the basics of Spark with Scala and covered below key concepts with exercises.
Running Scala in Google colab
Basic's of Spark
Spark's RDD with Scala
Sparks' DataFrame API with Scala
In the next episode, we will learn about Machine Learning models with Spark and Scala using Google colab runtime.
For more examples, consult the Spark official documentation
In this episode, we have learned the basics of Spark with Scala and covered below key concepts with exercises.
Running Scala in Google Colab
Basic’s of Spark
Spark’s RDD with Scala
Sparks’ DataFrame API with Scala
In the next episode, we will learn about Machine Learning models with Spark and Scala using Google Colab runtime.
Machine Learning with Scala in Google Colaboratory
Scala Docs -https://docs.scala-lang.org/tour/tour-of-scala.html | [
{
"code": null,
"e": 582,
"s": 171,
"text": "Spark’s inventors chose Scala to write the low-level modules. In Data Science and Machine Learning with Scala and Spark (Episode 01/03), we covered the basics of Scala programming language while using a Google Colab environment. In this article, we learn about the Spark ecosystem and its higher-level API for Scala users. As before, we still use Spark 3.0.0 and Google Colab for practicing some code snippets."
},
{
"code": null,
"e": 638,
"s": 582,
"text": "According to Apache Spark and Delta Lake Under the Hood"
},
{
"code": null,
"e": 1295,
"s": 638,
"text": "Apache Spark is a unified computing engine and a set of libraries for parallel data processing on computer clusters. As of the time this writing, Spark is the most actively developed open source engine for this task; making it the de facto tool for any developer or data scientist interested in big data. Spark supports multiple widely used programming languages (Python, Java, Scala and R), includes libraries for diverse tasks ranging from SQL to streaming and machine learning, and runs anywhere from a laptop to a cluster of thousands of servers. This makes it an easy system to start with and scale up to big data processing or incredibly large scale."
},
{
"code": null,
"e": 1514,
"s": 1295,
"text": "I highly recommend reading the Apache Spark and Delta Lake Under the Hood quick reference booklet. It is a 45-page document with examples in Scala and pyspark APIs and would not take more than 30 minutes to go through."
},
{
"code": null,
"e": 2159,
"s": 1514,
"text": "Being a data scientist, we can ask the question “what is the importance of Spark for machine learning tasks?” With the increase in the use of electronic devices, social media platforms, and advanced IT systems rollouts, data is being generated at a level never seen before. Also, due to cheap data storage, clients are happy to collect big data for values to be extracted. Machine Learning models have been proven and work for business to better understand and strategize for future expansions. For having access to big data, Spark is the de-facto choice for machine learning to churn through enormous volumes of collected data to build models."
},
{
"code": null,
"e": 2306,
"s": 2159,
"text": "DataFrame API is the most important higher-level API for Machine Learning. Spark’s MLlib has dropped the support of RDD in favor of DataFrame API."
},
{
"code": null,
"e": 2500,
"s": 2306,
"text": "Scala was selected to be the core the language to write the Spark engine. However, Apache Spark provides high-level APIs in Java, Scala, Python, and R. In this article, we will use spark 3.0.0."
},
{
"code": null,
"e": 2574,
"s": 2500,
"text": "Below are the commands to get modules for Scala and Spark in Google colab"
},
{
"code": null,
"e": 2717,
"s": 2574,
"text": "// Run below commandsimport $ivy.`org.apache.spark::spark-sql:3.0.0`import org.apache.spark.sql._import $ivy.`sh.almond::ammonite-spark:0.3.0`"
},
{
"code": null,
"e": 2860,
"s": 2717,
"text": "There are two important abstractions of Spark, Spark Context, and Spark Session. Using the below lines, we create a spark session and context."
},
{
"code": null,
"e": 2930,
"s": 2860,
"text": "import org.apache.spark.SparkContextimport org.apache.spark.SparkConf"
},
{
"code": null,
"e": 3032,
"s": 2930,
"text": "Usually, when running spark there are a lot of warnings, using below commands, you can turn them off."
},
{
"code": null,
"e": 3300,
"s": 3032,
"text": "// TIP: Turn off the millions lines of logsimport org.apache.log4j.{Level, Logger}Logger.getLogger(“org”).setLevel(Level.OFF)// define spark sessionval spark = {SparkSession.builder().master(\"local[*]\").getOrCreate()}// Define Spark Contextdef sc = spark.sparkContext"
},
{
"code": null,
"e": 3519,
"s": 3300,
"text": "Resilient Distributed Datasets (RDD) is the most common abstraction of Spark data structure related closely with Scala. It is very similar to Scala native parallel feature. Let's write some snippets about RRD in Scala."
},
{
"code": null,
"e": 3708,
"s": 3519,
"text": "// Spark RDDimport scala.util.Random// Define variable in Scalaval bigRng = scala.util.Random.shuffle(1 to 100000)// convert Scala variable to spark RDDval bigPRng = sc.parallelize(bigRng)"
},
{
"code": null,
"e": 3773,
"s": 3708,
"text": "You can apply many operations on bigPRng , it will run on Spark."
},
{
"code": null,
"e": 3934,
"s": 3773,
"text": "// calculate the mean of the populationbigPRng.mean// Find the min of the populationbigPRng.min// Find the stanndard deviation of the populationbigPRng.popStdev"
},
{
"code": null,
"e": 4027,
"s": 3934,
"text": "Applying the function on each element of RDD is very similar to Scala parallel map function."
},
{
"code": null,
"e": 4249,
"s": 4027,
"text": "// Map function on RDD, similar to Paralell in Scalaval bigPRng2 = bigPRng.map(_ * 2)// Scala function function to apply on RDDdef div3(x:Int) : Boolean = {val y:Int=(x%3); return(y==0)}val bigBool = bigPRng2.map(div3(_))"
},
{
"code": null,
"e": 4606,
"s": 4249,
"text": "In the previous sections, we have included examples about the RDD and how RDD can be used to compute in parallel. Another popular API in spark is Dataframe. Coming from a Data Scientist background, probably, DataFrame API would make more sense. However, there is a major difference is how to spark data frames and pandas data frames operate under the hood."
},
{
"code": null,
"e": 4754,
"s": 4606,
"text": "Spark DataFrames can live on multiple physical machines and hence their computations are performed in distributed way opposed to pandas DataFrames."
},
{
"code": null,
"e": 4813,
"s": 4754,
"text": "Spark MLlib is implemented in DataFrame API going forward."
},
{
"code": null,
"e": 4909,
"s": 4813,
"text": "Let us learn some basic tricks of Spark DataFrame API mostly useful for machine learning tasks."
},
{
"code": null,
"e": 5002,
"s": 4909,
"text": "Read through Section 0 in the Google colab about the preparation of data for below snippets."
},
{
"code": null,
"e": 5222,
"s": 5002,
"text": "// Read the .txt fileval df_emps = spark.read.option(\"header\", \"true\").csv(data_dir + \"employee.txt\")// print the schemadf_emps.printSchema()// show top 10 records similar to df.head(10) in pandasdf_emps.show(10, false)"
},
{
"code": null,
"e": 5244,
"s": 5222,
"text": "Read the second table"
},
{
"code": null,
"e": 5464,
"s": 5244,
"text": "// Read the .txt fileval df_cr = spark.read.option(\"header\", \"true\").csv(data_dir + \"country_region.txt\")// print the schemadf_cr.printSchema()// show top 10 records similar to df.head(10) in pandasdf_cr.show(10, false)"
},
{
"code": null,
"e": 5485,
"s": 5464,
"text": "Read the third table"
},
{
"code": null,
"e": 5699,
"s": 5485,
"text": "// Read the .txt fileval df_dd = spark.read.option(\"header\", \"true\").csv(data_dir + \"dept_div.txt\")// print the schemadf_dd.printSchema()// show top 10 records similar to df.head(10) in pandasdf_dd.show(10, false)"
},
{
"code": null,
"e": 5789,
"s": 5699,
"text": "Merging is one of the most common and efficient operations in Spark compared with pandas."
},
{
"code": null,
"e": 5889,
"s": 5789,
"text": "// Merge all three tablesval df_joined = df_emps.join(df_cr, \"region_id\").join(df_dd, \"department\")"
},
{
"code": null,
"e": 5985,
"s": 5889,
"text": "I have prepared a functional Google colab notebook. Feel free to use the notebook for practice."
},
{
"code": null,
"e": 6063,
"s": 5985,
"text": "In this tutorial, we will learn data science and machine learning with scala."
},
{
"code": null,
"e": 6178,
"s": 6063,
"text": "SCALA is functional and objecte oriented progarmming running with JVM with aim to be scalable hence name as SCALA."
},
{
"code": null,
"e": 6362,
"s": 6178,
"text": "Spark is written in scala which makes scala a native choice for processing big data. We will also cover the basic of using scala with spark and machine learning using spark and scala."
},
{
"code": null,
"e": 6377,
"s": 6362,
"text": "Key Objectives"
},
{
"code": null,
"e": 6533,
"s": 6377,
"text": "\nInstall Scala to work with Google Colab\nIntroduction and basics of Scala\nScala for Data Science\nScala with Spark Introduction\nMachine Learning with Scala\n"
},
{
"code": null,
"e": 6573,
"s": 6533,
"text": "Install Scala to work with Google Colab"
},
{
"code": null,
"e": 6606,
"s": 6573,
"text": "Introduction and basics of Scala"
},
{
"code": null,
"e": 6629,
"s": 6606,
"text": "Scala for Data Science"
},
{
"code": null,
"e": 6659,
"s": 6629,
"text": "Scala with Spark Introduction"
},
{
"code": null,
"e": 6687,
"s": 6659,
"text": "Machine Learning with Scala"
},
{
"code": null,
"e": 6809,
"s": 6687,
"text": "Above is the bigger scope of this tutorial. The aim is to provide a working google colab notebook for all above sections."
},
{
"code": null,
"e": 6876,
"s": 6809,
"text": "In this tutorial, we will focus on spark computations using Scala."
},
{
"code": null,
"e": 7196,
"s": 6876,
"text": "To get a better understanding of spark framework and its modules, I would highly recommend [Apache SparkTM Under the Hood] https://databricks.com/p/ebook/apache-spark-under-the-hood. We will go through some of the examples given in this hand book. Therefore, download the associated data from this github data Location."
},
{
"code": null,
"e": 7331,
"s": 7196,
"text": "Another source is using excercise files from https://www.lynda.com/Scala-tutorials/Scala-Essential-Training-Data-Science/559182-2.html"
},
{
"code": null,
"e": 7450,
"s": 7331,
"text": "I have downloaded the data and put it together in one of my repositories for easy access on this consoldated blog data"
},
{
"code": null,
"e": 7688,
"s": 7450,
"text": "We need to mount the google drive to read the data stored in google drive. Below is the simplest way to mount it. You will asked to enter the token generated by your access procedure. Her eis the link to the article about mounting gdrive"
},
{
"code": null,
"e": 7750,
"s": 7688,
"text": "from google.colab import drive\ndrive.mount('/content/drive')\n"
},
{
"code": null,
"e": 8287,
"s": 7750,
"text": "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n\nEnter your authorization code:\n··········\nMounted at /content/drive\n"
},
{
"code": null,
"e": 8469,
"s": 8287,
"text": "# Location of exercise data (I have uploaded the data to my google drive). Youhave to change to your location.\nroot_example_data = '/content/drive/My Drive/scala_machine_learning/'\n"
},
{
"code": null,
"e": 8524,
"s": 8469,
"text": "!ls '/content/drive/My Drive/scala_machine_learning/'\n"
},
{
"code": null,
"e": 8581,
"s": 8524,
"text": "departuredelays.csv.gz\tEx_Files_Scala_EssT_Data_Science\n"
},
{
"code": null,
"e": 8716,
"s": 8581,
"text": "I followed the tutorial Machine Learning with Scala in Google Colaboratory by Shadad Laddad to start Scala kernel in the google colab."
},
{
"code": null,
"e": 8940,
"s": 8716,
"text": "If you get a \"scala\" kernel not recognized warning when loading up the notebook for the first time, start by running the two cells below. Once you are done reload the page to load the notebook in the installed Scala kernel."
},
{
"code": null,
"e": 9428,
"s": 8940,
"text": "%%shell\nSCALA_VERSION=2.12.8 ALMOND_VERSION=0.3.0+16-548dc10f-SNAPSHOT\ncurl -Lo coursier https://git.io/coursier-cli\nchmod +x coursier\n./coursier bootstrap \\\n -r jitpack -r sonatype:snapshots \\\n -i user -I user:sh.almond:scala-kernel-api_$SCALA_VERSION:$ALMOND_VERSION \\\n sh.almond:scala-kernel_$SCALA_VERSION:$ALMOND_VERSION \\\n --sources --default=true \\\n -o almond-snapshot --embed-files=false\nrm coursier\n./almond-snapshot --install --global --force\nrm almond-snapshot\n"
},
{
"code": null,
"e": 9783,
"s": 9428,
"text": "%%shell\necho \"{\n \\\"language\\\" : \\\"scala\\\",\n \\\"display_name\\\" : \\\"Scala\\\",\n \\\"argv\\\" : [\n \\\"bash\\\",\n \\\"-c\\\",\n \\\"env LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libpython3.6m.so:\\$LD_PRELOAD java -jar /usr/local/share/jupyter/kernels/scala/launcher.jar --connection-file {connection_file}\\\"\n ]\n}\" > /usr/local/share/jupyter/kernels/scala/kernel.json\n"
},
{
"code": null,
"e": 9864,
"s": 9783,
"text": "Lets check if the scala is working or not. if it does not work refresh the page."
},
{
"code": null,
"e": 9890,
"s": 9864,
"text": "println(\"Hello, world!\")\n"
},
{
"code": null,
"e": 9905,
"s": 9890,
"text": "Hello, world!\n"
},
{
"code": null,
"e": 10166,
"s": 9905,
"text": "Apache Spark is a lightning fast cluster computing system solving the limititaion of previously favoutite MapReduce systems for large data sets. It is the framework of choice among data scientists and machine learning engineers to work with big data problems."
},
{
"code": null,
"e": 10308,
"s": 10166,
"text": "Scala was selected is preffered languange to write Spark engine. However Apcahe Spark privides high level APIs in Java, Scala, Python and R."
},
{
"code": null,
"e": 10361,
"s": 10308,
"text": "According to Apache Spark Introduction for Beginners"
},
{
"code": null,
"e": 10685,
"s": 10361,
"text": "Spark is one of Hadoop's sub venture created in 2009 in UC Berkeley's AMPLab by Matei Zaharia. It was Open Sourced in 2010 under a BSD license. It was given to Apache programming establishment in 2013, and now Apache Spark has turned into the best level Apache venture from Feb-2014. And now the results are pretty booming."
},
{
"code": null,
"e": 10829,
"s": 10685,
"text": "Spark 3.0.0 released on 18th June 2020 after passing the vote on 10th of June 2020. However, the preview of Spark 3.0.0 was released late 2019."
},
{
"code": null,
"e": 10882,
"s": 10829,
"text": "Spark 3.0 is roughly two times faster than Spark 2.4"
},
{
"code": null,
"e": 10965,
"s": 10882,
"text": "In this tutorial, we will use Scala as higher level API to run spark computations."
},
{
"code": null,
"e": 11028,
"s": 10965,
"text": "To learn more about Spark, you may want to read below articles"
},
{
"code": null,
"e": 11318,
"s": 11028,
"text": "\nhttps://towardsdatascience.com/introduction-to-apache-spark-207a479c3001\nhttps://spark.apache.org/\nhttps://medium.com/@amjadraza24/spark-ifying-pandas-databricks-koalas-with-google-colab-93028890db5\nhttps://medium.com/@amjadraza24/getting-started-spark3-0-0-with-google-colab-9796d350d78\n"
},
{
"code": null,
"e": 11391,
"s": 11318,
"text": "https://towardsdatascience.com/introduction-to-apache-spark-207a479c3001"
},
{
"code": null,
"e": 11417,
"s": 11391,
"text": "https://spark.apache.org/"
},
{
"code": null,
"e": 11517,
"s": 11417,
"text": "https://medium.com/@amjadraza24/spark-ifying-pandas-databricks-koalas-with-google-colab-93028890db5"
},
{
"code": null,
"e": 11606,
"s": 11517,
"text": "https://medium.com/@amjadraza24/getting-started-spark3-0-0-with-google-colab-9796d350d78"
},
{
"code": null,
"e": 11677,
"s": 11606,
"text": "// Run below commands\nimport $ivy.`org.apache.spark::spark-sql:3.0.0`\n"
},
{
"code": null,
"e": 11725,
"s": 11677,
"text": "import $ivy.$ "
},
{
"code": null,
"e": 11756,
"s": 11725,
"text": "import org.apache.spark.sql._\n"
},
{
"code": null,
"e": 11786,
"s": 11756,
"text": "import org.apache.spark.sql._"
},
{
"code": null,
"e": 11833,
"s": 11786,
"text": "import $ivy.`sh.almond::ammonite-spark:0.3.0`\n"
},
{
"code": null,
"e": 11879,
"s": 11833,
"text": "import $ivy.$ "
},
{
"code": null,
"e": 11951,
"s": 11879,
"text": "import org.apache.spark.SparkContext\nimport org.apache.spark.SparkConf\n"
},
{
"code": null,
"e": 12023,
"s": 11951,
"text": "import org.apache.spark.SparkContext\n\nimport org.apache.spark.SparkConf"
},
{
"code": null,
"e": 12152,
"s": 12023,
"text": "// TIP: Turn off the millions lines of logs\nimport org.apache.log4j.{Level, Logger}\nLogger.getLogger(\"org\").setLevel(Level.OFF)\n"
},
{
"code": null,
"e": 12193,
"s": 12152,
"text": "import org.apache.log4j.{Level, Logger}\n"
},
{
"code": null,
"e": 12308,
"s": 12193,
"text": "val conf = new SparkConf().setAppName(\"test_scala_machine_learning\").setMaster(\"local[*]\")\nnew SparkContext(conf)\n"
},
{
"code": null,
"e": 12389,
"s": 12308,
"text": "Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties\n"
},
{
"code": null,
"e": 12505,
"s": 12389,
"text": "conf: SparkConf = org.apache.spark.SparkConf@34a88b7a\nres6_1: SparkContext = org.apache.spark.SparkContext@5368b6be"
},
{
"code": null,
"e": 12521,
"s": 12505,
"text": "# spark.stop()\n"
},
{
"code": null,
"e": 12589,
"s": 12521,
"text": "20/06/21 09:04:44 INFO SparkContext: SparkContext already stopped.\n"
},
{
"code": null,
"e": 12682,
"s": 12589,
"text": "val spark = {\n SparkSession.builder()\n .master(\"local[*]\")\n .getOrCreate()\n }\n"
},
{
"code": null,
"e": 12747,
"s": 12682,
"text": "spark: SparkSession = org.apache.spark.sql.SparkSession@7dec4dc6"
},
{
"code": null,
"e": 12776,
"s": 12747,
"text": "def sc = spark.sparkContext\n"
},
{
"code": null,
"e": 12796,
"s": 12776,
"text": "defined function sc"
},
{
"code": null,
"e": 13015,
"s": 12796,
"text": "Resilient Distributed Datasets (RDD) is the most common abstraction of Spark data structure related closely with Scala. It is very similar to Scala native parallel feature. Let's write some snippets about RRD in Scala."
},
{
"code": null,
"e": 13054,
"s": 13015,
"text": "// Spark RDD\nimport scala.util.Random\n"
},
{
"code": null,
"e": 13079,
"s": 13054,
"text": "import scala.util.Random"
},
{
"code": null,
"e": 13132,
"s": 13079,
"text": "val bigRng = scala.util.Random.shuffle(1 to 100000)\n"
},
{
"code": null,
"e": 13532,
"s": 13132,
"text": "bigRng: collection.immutable.IndexedSeq[Int] = Vector(\n 56811,\n 43866,\n 39908,\n 15474,\n 21501,\n 96554,\n 29846,\n 56881,\n 29337,\n 12277,\n 98105,\n 31018,\n 49771,\n 86256,\n 43551,\n 66319,\n 50308,\n 57732,\n 27969,\n 15028,\n 60441,\n 4125,\n 92598,\n 29572,\n 22279,\n 39084,\n 73300,\n 64156,\n 19123,\n 50993,\n 81177,\n 59026,\n 70870,\n 42779,\n 15839,\n 52508,\n 22562,\n 69156,\n..."
},
{
"code": null,
"e": 13588,
"s": 13532,
"text": "// convert to RDD\nval bigPRng = sc.parallelize(bigRng)\n"
},
{
"code": null,
"e": 13683,
"s": 13588,
"text": "bigPRng: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[0] at parallelize at cmd11.sc:1"
},
{
"code": null,
"e": 13737,
"s": 13683,
"text": "// calculate the mean of the population\nbigPRng.mean\n"
},
{
"code": null,
"e": 13771,
"s": 13737,
"text": "res12: Double = 50000.50000000018"
},
{
"code": null,
"e": 13818,
"s": 13771,
"text": "// Find the min of the population\nbigPRng.min\n"
},
{
"code": null,
"e": 13833,
"s": 13818,
"text": "res25: Int = 1"
},
{
"code": null,
"e": 13880,
"s": 13833,
"text": "// Find the max of the population\nbigPRng.max\n"
},
{
"code": null,
"e": 13900,
"s": 13880,
"text": "res13: Int = 100000"
},
{
"code": null,
"e": 13968,
"s": 13900,
"text": "// Find the stanndard deviation of the population\nbigPRng.popStdev\n"
},
{
"code": null,
"e": 14003,
"s": 13968,
"text": "res14: Double = 28867.513458037993"
},
{
"code": null,
"e": 14021,
"s": 14003,
"text": "bigPRng.take(25)\n"
},
{
"code": null,
"e": 14271,
"s": 14021,
"text": "res28: Array[Int] = Array(\n 95614,\n 44945,\n 85237,\n 90417,\n 92032,\n 55788,\n 14288,\n 32807,\n 44044,\n 9755,\n 3331,\n 94537,\n 5991,\n 61000,\n 35500,\n 84313,\n 49472,\n 29350,\n 92789,\n 78992,\n 42190,\n 60047,\n 15325,\n 84589,\n 49274\n)"
},
{
"code": null,
"e": 14359,
"s": 14271,
"text": "// Map function on RDD, similar to Paralell in Scala\nval bigPRng2 = bigPRng.map(_ * 2)\n"
},
{
"code": null,
"e": 14442,
"s": 14359,
"text": "bigPRng2: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[5] at map at cmd15.sc:1"
},
{
"code": null,
"e": 14461,
"s": 14442,
"text": "bigPRng2.take(25)\n"
},
{
"code": null,
"e": 14725,
"s": 14461,
"text": "res30: Array[Int] = Array(\n 191228,\n 89890,\n 170474,\n 180834,\n 184064,\n 111576,\n 28576,\n 65614,\n 88088,\n 19510,\n 6662,\n 189074,\n 11982,\n 122000,\n 71000,\n 168626,\n 98944,\n 58700,\n 185578,\n 157984,\n 84380,\n 120094,\n 30650,\n 169178,\n 98548\n)"
},
{
"code": null,
"e": 14742,
"s": 14725,
"text": "bigPRng2.mean()\n"
},
{
"code": null,
"e": 14777,
"s": 14742,
"text": "res16: Double = 100001.00000000036"
},
{
"code": null,
"e": 14881,
"s": 14777,
"text": "// Scala function function to apply on RDD\ndef div3(x:Int) : Boolean = {val y:Int=(x%3); return(y==0)}\n"
},
{
"code": null,
"e": 14903,
"s": 14881,
"text": "defined function div3"
},
{
"code": null,
"e": 14912,
"s": 14903,
"text": "div3(9)\n"
},
{
"code": null,
"e": 14934,
"s": 14912,
"text": "res18: Boolean = true"
},
{
"code": null,
"e": 14971,
"s": 14934,
"text": "val bigBool = bigPRng2.map(div3(_))\n"
},
{
"code": null,
"e": 15057,
"s": 14971,
"text": "bigBool: org.apache.spark.rdd.RDD[Boolean] = MapPartitionsRDD[8] at map at cmd19.sc:1"
},
{
"code": null,
"e": 15075,
"s": 15057,
"text": "bigBool.take(25)\n"
},
{
"code": null,
"e": 15320,
"s": 15075,
"text": "res20: Array[Boolean] = Array(\n true,\n true,\n false,\n true,\n true,\n false,\n false,\n false,\n true,\n false,\n false,\n false,\n false,\n true,\n true,\n false,\n false,\n true,\n true,\n false,\n true,\n true,\n true,\n false,\n false\n)"
},
{
"code": null,
"e": 15677,
"s": 15320,
"text": "In the previous sections, we have included examples about the RDD and how RDD can be used to compute in parallel. Another popular API in spark is Dataframe. Coming from a Data Scientist background, probably, DataFrame API would make more sense. However, there is a major difference is how to spark data frames and pandas data frames operate under the hood."
},
{
"code": null,
"e": 15884,
"s": 15677,
"text": "Spark DataFrames can live on multiple physical machines and hence their computations are performed in distributed way opposed to pandas DataFrames.\nSpark MLlib is implemented in DataFrame API going forward."
},
{
"code": null,
"e": 15980,
"s": 15884,
"text": "Let us learn some basic tricks of Spark DataFrame API mostly useful for machine learning tasks."
},
{
"code": null,
"e": 16133,
"s": 15980,
"text": "//spark data frames\n\nval data_dir = \"/content/drive/My Drive//scala_machine_learning/Ex_Files_Scala_EssT_Data_Science/Exercise Files/Chapter 5/05_01/\"\n"
},
{
"code": null,
"e": 16267,
"s": 16133,
"text": "data_dir: String = \"/content/drive/My Drive//scala_machine_learning/Ex_Files_Scala_EssT_Data_Science/Exercise Files/Chapter 5/05_01/\""
},
{
"code": null,
"e": 16349,
"s": 16267,
"text": "val df_emps = spark.read.option(\"header\", \"true\").csv(data_dir + \"employee.txt\")\n"
},
{
"code": null,
"e": 16420,
"s": 16349,
"text": "df_emps: DataFrame = [id: string, last_name: string ... 7 more fields]"
},
{
"code": null,
"e": 16459,
"s": 16420,
"text": "// print schema\ndf_emps.printSchema()\n"
},
{
"code": null,
"e": 16820,
"s": 16459,
"text": "root\n |-- id: string (nullable = true)\n |-- last_name: string (nullable = true)\n |-- email: string (nullable = true)\n |-- gender: string (nullable = true)\n |-- department: string (nullable = true)\n |-- start_date: string (nullable = true)\n |-- salary: string (nullable = true)\n |-- job_title: string (nullable = true)\n |-- region_id: string (nullable = true)\n\n"
},
{
"code": null,
"e": 16901,
"s": 16820,
"text": "// show top 10 records similar to df.head(10) in pandas\ndf_emps.show(10, false)\n"
},
{
"code": null,
"e": 18734,
"s": 16901,
"text": "+---+------------+----------------------------+--------+------------+------------+------+----------------------------+---------+\n|id |last_name |email |gender |department |start_date |salary|job_title |region_id|\n+---+------------+----------------------------+--------+------------+------------+------+----------------------------+---------+\n|1 |'Kelley' |'[email protected]' |'Female'|'Computers' |'10/2/2009' |67470 |'Structural Engineer' |2 |\n|2 |'Armstrong' |'[email protected]'|'Male' |'Sports' |'3/31/2008' |71869 |'Financial Advisor' |2 |\n|3 |'Carr' |'[email protected]' |'Male' |'Automotive'|'7/12/2009' |101768|'Recruiting Manager' |3 |\n|4 |'Murray' |'[email protected]' |'Female'|'Jewelery' |'12/25/2014'|96897 |'Desktop Support Technician'|3 |\n|5 |'Ellis' |'[email protected]' |'Female'|'Grocery' |'9/19/2002' |63702 |'Software Engineer III' |7 |\n|6 |'Phillips' |'[email protected]' |'Male' |'Tools' |'8/21/2013' |118497|'Executive Secretary' |1 |\n|7 |'Williamson'|'[email protected]' |'Male' |'Computers' |'5/14/2006' |65889 |'Dental Hygienist' |6 |\n|8 |'Harris' |'[email protected]' |'Female'|'Toys' |'8/12/2003' |84427 |'Safety Technician I' |4 |\n|9 |'James' |'[email protected]' |'Male' |'Jewelery' |'9/7/2005' |108657|'Sales Associate' |2 |\n|10 |'Sanchez' |'[email protected]' |'Male' |'Movies' |'3/13/2013' |108093|'Sales Representative' |1 |\n+---+------------+----------------------------+--------+------------+------------+------+----------------------------+---------+\nonly showing top 10 rows\n\n"
},
{
"code": null,
"e": 18820,
"s": 18734,
"text": "val df_cr = spark.read.option(\"header\", \"true\").csv(data_dir + \"country_region.txt\")\n"
},
{
"code": null,
"e": 18901,
"s": 18820,
"text": "df_cr: DataFrame = [region_id: string, company_regions: string ... 1 more field]"
},
{
"code": null,
"e": 18922,
"s": 18901,
"text": "df_cr.printSchema()\n"
},
{
"code": null,
"e": 19056,
"s": 18922,
"text": "root\n |-- region_id: string (nullable = true)\n |-- company_regions: string (nullable = true)\n |-- country: string (nullable = true)\n\n"
},
{
"code": null,
"e": 19079,
"s": 19056,
"text": "df_cr.show(10, false)\n"
},
{
"code": null,
"e": 19543,
"s": 19079,
"text": "+---------+-------------------+---------+\n|region_id|company_regions |country |\n+---------+-------------------+---------+\n|1 | 'Northeast' | 'USA' |\n|2 | 'Southeast' | 'USA' |\n|3 | 'Northwest' | 'USA' |\n|4 | 'Southwest' | 'USA' |\n|5 | 'British Columbia'| 'Canada'|\n|6 | 'Quebec' | 'Canada'|\n|7 | 'Nova Scotia' | 'Canada'|\n+---------+-------------------+---------+\n\n"
},
{
"code": null,
"e": 19623,
"s": 19543,
"text": "val df_dd = spark.read.option(\"header\", \"true\").csv(data_dir + \"dept_div.txt\")\n"
},
{
"code": null,
"e": 19689,
"s": 19623,
"text": "df_dd: DataFrame = [department: string, company_division: string]"
},
{
"code": null,
"e": 19712,
"s": 19689,
"text": "df_dd.show(10, false)\n"
},
{
"code": null,
"e": 20285,
"s": 19712,
"text": "+-------------+----------------------+\n|department |company_division |\n+-------------+----------------------+\n|'Automotive' |'Auto & Hardware' |\n|'Baby' |'Domestic' |\n|'Beauty' |'Domestic' |\n|'Clothing' |'Domestic' |\n|'Computers' |'Electronic Equipment'|\n|'Electronics'|'Electronic Equipment'|\n|'Games' |'Domestic' |\n|'Garden' |'Outdoors & Garden' |\n|'Grocery' |'Domestic' |\n|'Health' |'Domestic' |\n+-------------+----------------------+\nonly showing top 10 rows\n\n"
},
{
"code": null,
"e": 20388,
"s": 20285,
"text": "// merge all thres tables\n\nval df_joined = df_emps.join(df_cr, \"region_id\").join(df_dd, \"department\")\n"
},
{
"code": null,
"e": 20470,
"s": 20388,
"text": "df_joined: DataFrame = [department: string, region_id: string ... 10 more fields]"
},
{
"code": null,
"e": 20489,
"s": 20470,
"text": "df_joined.columns\n"
},
{
"code": null,
"e": 20696,
"s": 20489,
"text": "res35: Array[String] = Array(\n \"department\",\n \"region_id\",\n \"id\",\n \"last_name\",\n \"email\",\n \"gender\",\n \"start_date\",\n \"salary\",\n \"job_title\",\n \"company_regions\",\n \"country\",\n \"company_division\"\n)"
},
{
"code": null,
"e": 20723,
"s": 20696,
"text": "df_joined.show(20, false)\n"
},
{
"code": null,
"e": 25214,
"s": 20723,
"text": "+-------------+---------+---+------------+----------------------------+--------+------------+------+-------------------------------+-------------------+---------+----------------------+\n|department |region_id|id |last_name |email |gender |start_date |salary|job_title |company_regions |country |company_division |\n+-------------+---------+---+------------+----------------------------+--------+------------+------+-------------------------------+-------------------+---------+----------------------+\n|'Computers' |2 |1 |'Kelley' |'[email protected]' |'Female'|'10/2/2009' |67470 |'Structural Engineer' | 'Southeast' | 'USA' |'Electronic Equipment'|\n|'Sports' |2 |2 |'Armstrong' |'[email protected]'|'Male' |'3/31/2008' |71869 |'Financial Advisor' | 'Southeast' | 'USA' |'Games & Sports' |\n|'Automotive' |3 |3 |'Carr' |'[email protected]' |'Male' |'7/12/2009' |101768|'Recruiting Manager' | 'Northwest' | 'USA' |'Auto & Hardware' |\n|'Jewelery' |3 |4 |'Murray' |'[email protected]' |'Female'|'12/25/2014'|96897 |'Desktop Support Technician' | 'Northwest' | 'USA' |'Fashion' |\n|'Grocery' |7 |5 |'Ellis' |'[email protected]' |'Female'|'9/19/2002' |63702 |'Software Engineer III' | 'Nova Scotia' | 'Canada'|'Domestic' |\n|'Tools' |1 |6 |'Phillips' |'[email protected]' |'Male' |'8/21/2013' |118497|'Executive Secretary' | 'Northeast' | 'USA' |'Auto & Hardware' |\n|'Computers' |6 |7 |'Williamson'|'[email protected]' |'Male' |'5/14/2006' |65889 |'Dental Hygienist' | 'Quebec' | 'Canada'|'Electronic Equipment'|\n|'Toys' |4 |8 |'Harris' |'[email protected]' |'Female'|'8/12/2003' |84427 |'Safety Technician I' | 'Southwest' | 'USA' |'Games & Sports' |\n|'Jewelery' |2 |9 |'James' |'[email protected]' |'Male' |'9/7/2005' |108657|'Sales Associate' | 'Southeast' | 'USA' |'Fashion' |\n|'Movies' |1 |10 |'Sanchez' |'[email protected]' |'Male' |'3/13/2013' |108093|'Sales Representative' | 'Northeast' | 'USA' |'Entertainment' |\n|'Jewelery' |7 |11 |'Jacobs' |'[email protected]' |'Female'|'11/27/2003'|121966|'Community Outreach Specialist'| 'Nova Scotia' | 'Canada'|'Fashion' |\n|'Clothing' |7 |12 |'Black' |'[email protected]' |'Male' |'2/4/2003' |44179 |'Data Coordiator' | 'Nova Scotia' | 'Canada'|'Domestic' |\n|'Baby' |3 |13 |'Schmidt' |'[email protected]' |'Male' |'10/13/2002'|85227 |'Compensation Analyst' | 'Northwest' | 'USA' |'Domestic' |\n|'Computers' |4 |14 |'Webb' |'[email protected]' |'Female'|'10/22/2006'|59763 |'Software Test Engineer III' | 'Southwest' | 'USA' |'Electronic Equipment'|\n|'Games' |7 |15 |'Jacobs' |'[email protected]' |'Female'|'3/4/2007' |141139|'Community Outreach Specialist'| 'Nova Scotia' | 'Canada'|'Domestic' |\n|'Baby' |1 |16 |'Medina' |'[email protected]' |'Female'|'3/14/2008' |106659|'Web Developer III' | 'Northeast' | 'USA' |'Domestic' |\n|'Kids' |6 |17 |'Morgan' |'[email protected]' |'Female'|'5/4/2011' |148952|'Programmer IV' | 'Quebec' | 'Canada'|'Domestic' |\n|'Home' |5 |18 |'Nguyen' |'[email protected]' |'Male' |'11/3/2014' |93804 |'Geologist II' | 'British Columbia'| 'Canada'|'Domestic' |\n|'Electronics'|3 |19 |'Day' |'[email protected]' |'Male' |'9/22/2004' |109890|'VP Sales' | 'Northwest' | 'USA' |'Electronic Equipment'|\n|'Movies' |5 |20 |'Carr' |'[email protected]' |'Female'|'11/22/2007'|115274|'VP Quality Control' | 'British Columbia'| 'Canada'|'Entertainment' |\n+-------------+---------+---+------------+----------------------------+--------+------------+------+-------------------------------+-------------------+---------+----------------------+\nonly showing top 20 rows\n\n"
},
{
"code": null,
"e": 25279,
"s": 25214,
"text": "for more examples, you can follow the official documentations at"
},
{
"code": null,
"e": 25390,
"s": 25279,
"text": "In this episode, we have learned the basics of Spark with Scala and covered below key concepts with exercises."
},
{
"code": null,
"e": 25420,
"s": 25390,
"text": "Running Scala in Google colab"
},
{
"code": null,
"e": 25437,
"s": 25420,
"text": "Basic's of Spark"
},
{
"code": null,
"e": 25460,
"s": 25437,
"text": "Spark's RDD with Scala"
},
{
"code": null,
"e": 25493,
"s": 25460,
"text": "Sparks' DataFrame API with Scala"
},
{
"code": null,
"e": 25607,
"s": 25493,
"text": "In the next episode, we will learn about Machine Learning models with Spark and Scala using Google colab runtime."
},
{
"code": null,
"e": 25673,
"s": 25613,
"text": "For more examples, consult the Spark official documentation"
},
{
"code": null,
"e": 25784,
"s": 25673,
"text": "In this episode, we have learned the basics of Spark with Scala and covered below key concepts with exercises."
},
{
"code": null,
"e": 25814,
"s": 25784,
"text": "Running Scala in Google Colab"
},
{
"code": null,
"e": 25831,
"s": 25814,
"text": "Basic’s of Spark"
},
{
"code": null,
"e": 25854,
"s": 25831,
"text": "Spark’s RDD with Scala"
},
{
"code": null,
"e": 25887,
"s": 25854,
"text": "Sparks’ DataFrame API with Scala"
},
{
"code": null,
"e": 26001,
"s": 25887,
"text": "In the next episode, we will learn about Machine Learning models with Spark and Scala using Google Colab runtime."
},
{
"code": null,
"e": 26052,
"s": 26001,
"text": "Machine Learning with Scala in Google Colaboratory"
}
] |
Iterator vs ListIterator in Java? | An Iterator is an interface in Java and we can traverse the elements of a list in a forward direction whereas a ListIterator is an interface that extends the Iterator interface and we can traverse the elements in both forward and backward directions. An Iterator can be used in these collection types like List, Set, and Queue whereas ListIterator can be used in List collection only. The important methods of Iterator interface are hasNext(), next() and remove() whereas important methods of ListIterator interface are add(), hasNext(), hasPrevious() and remove().
public interface Iterator<E>
import java.util.*;
public class IteratorTest {
public static void main(String[] args) {
List<String> listObject = new ArrayList<String>();
listObject.add("India");
listObject.add("Australia");
listObject.add("England");
listObject.add("Bangladesh");
listObject.add("South Africa");
Iterator it = listObject.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
India
Australia
England
Bangladesh
South Africa
public interface ListIterator<E> extends Iterator<E>
import java.util.*;
public class ListIteratorTest {
public static void main(String[] args) {
List<String> listObject = new ArrayList<String>();
listObject.add("Java");
listObject.add("Selenium");
listObject.add("Python");
listObject.add("Java Script");
listObject.add("Cloud Computing");
ListIterator it = listObject.listIterator();
System.out.println("Iterating the elements in forward direction: ");
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("--------------------------------------------");
System.out.println("Iterating the elements in backward direction: ");
while (it.hasPrevious()) {
System.out.println(it.previous());
}
}
}
Iterating the elementrs in forward direction:
Java
Selenium
Python
Java Script
Cloud Computing
-----------------------------------------------
Iterating the elements in backward direction:
Cloud Computing
Java Script
Python
Selenium
Java | [
{
"code": null,
"e": 1628,
"s": 1062,
"text": "An Iterator is an interface in Java and we can traverse the elements of a list in a forward direction whereas a ListIterator is an interface that extends the Iterator interface and we can traverse the elements in both forward and backward directions. An Iterator can be used in these collection types like List, Set, and Queue whereas ListIterator can be used in List collection only. The important methods of Iterator interface are hasNext(), next() and remove() whereas important methods of ListIterator interface are add(), hasNext(), hasPrevious() and remove()."
},
{
"code": null,
"e": 1657,
"s": 1628,
"text": "public interface Iterator<E>"
},
{
"code": null,
"e": 2108,
"s": 1657,
"text": "import java.util.*;\npublic class IteratorTest {\n public static void main(String[] args) { \n List<String> listObject = new ArrayList<String>();\n listObject.add(\"India\");\n listObject.add(\"Australia\");\n listObject.add(\"England\");\n listObject.add(\"Bangladesh\");\n listObject.add(\"South Africa\");\n Iterator it = listObject.iterator();\n while (it.hasNext()) {\n System.out.println(it.next());\n }\n }\n}"
},
{
"code": null,
"e": 2156,
"s": 2108,
"text": "India\nAustralia\nEngland\nBangladesh\nSouth Africa"
},
{
"code": null,
"e": 2209,
"s": 2156,
"text": "public interface ListIterator<E> extends Iterator<E>"
},
{
"code": null,
"e": 2981,
"s": 2209,
"text": "import java.util.*;\npublic class ListIteratorTest {\n public static void main(String[] args) {\n List<String> listObject = new ArrayList<String>();\n listObject.add(\"Java\");\n listObject.add(\"Selenium\");\n listObject.add(\"Python\");\n listObject.add(\"Java Script\");\n listObject.add(\"Cloud Computing\");\n ListIterator it = listObject.listIterator();\n System.out.println(\"Iterating the elements in forward direction: \");\n while (it.hasNext()) {\n System.out.println(it.next());\n }\n System.out.println(\"--------------------------------------------\");\n System.out.println(\"Iterating the elements in backward direction: \");\n while (it.hasPrevious()) {\n System.out.println(it.previous());\n }\n }\n}"
},
{
"code": null,
"e": 3219,
"s": 2981,
"text": "Iterating the elementrs in forward direction:\nJava\nSelenium\nPython\nJava Script\nCloud Computing\n-----------------------------------------------\nIterating the elements in backward direction:\nCloud Computing\nJava Script\nPython\nSelenium\nJava"
}
] |
How to mount windows drives in Ubuntu | 23 Dec, 2018
Figure: Error occurred while accessing the windows drive
Following are the step wise instructions to access windows drives in Ubuntu (Any Version),
1. Open terminal and type sudo ntfsfix error mounting location as shown in above picture and press enter button.2. It will ask for system password, enter password and again press enter.3. It will take some seconds to process command and at the end shows the message like “NTFS partition was processed successfully.”4. Again click on windows drive, now you are allow to access clicked drive.
For Example:Step 1:
Type sudo ntfsfix /dev/sda3 and press enter as shown in below picture then it will ask for system password, enter password and again press enter.
Step 2:It will take some seconds to process command and at the end shows the message like “NTFS partition was processed successfully”, as shown in below picture.
linux-command
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Dec, 2018"
},
{
"code": null,
"e": 109,
"s": 52,
"text": "Figure: Error occurred while accessing the windows drive"
},
{
"code": null,
"e": 200,
"s": 109,
"text": "Following are the step wise instructions to access windows drives in Ubuntu (Any Version),"
},
{
"code": null,
"e": 591,
"s": 200,
"text": "1. Open terminal and type sudo ntfsfix error mounting location as shown in above picture and press enter button.2. It will ask for system password, enter password and again press enter.3. It will take some seconds to process command and at the end shows the message like “NTFS partition was processed successfully.”4. Again click on windows drive, now you are allow to access clicked drive."
},
{
"code": null,
"e": 611,
"s": 591,
"text": "For Example:Step 1:"
},
{
"code": null,
"e": 757,
"s": 611,
"text": "Type sudo ntfsfix /dev/sda3 and press enter as shown in below picture then it will ask for system password, enter password and again press enter."
},
{
"code": null,
"e": 919,
"s": 757,
"text": "Step 2:It will take some seconds to process command and at the end shows the message like “NTFS partition was processed successfully”, as shown in below picture."
},
{
"code": null,
"e": 933,
"s": 919,
"text": "linux-command"
},
{
"code": null,
"e": 942,
"s": 933,
"text": "TechTips"
}
] |
Check divisibility by 7 | 07 Jul, 2022
Given a number, check if it is divisible by 7. You are not allowed to use modulo operator, floating point arithmetic is also not allowed. A simple method is repeated subtraction. Following is another interesting method.Divisibility by 7 can be checked by a recursive method. A number of the form 10a + b is divisible by 7 if and only if a – 2b is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a small number. Example: the number 371: 37 – (2×1) = 37 – 2 = 35; 3 – (2 × 5) = 3 – 10 = -7; thus, since -7 is divisible by 7, 371 is divisible by 7. Following is the implementation of the above method
C++
C
Java
Python3
C#
PHP
Javascript
// A Program to check whether a number is divisible by 7#include <bits/stdc++.h>using namespace std; int isDivisibleBy7( int num ){ // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );} // Driver codeint main(){ int num = 616; if( isDivisibleBy7(num ) ) cout << "Divisible" ; else cout << "Not Divisible" ; return 0;} // This code is contributed by rathbhupendra
// A Program to check whether a number is divisible by 7#include <stdio.h> int isDivisibleBy7( int num ){ // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );} // Driver program to test above functionint main(){ int num = 616; if( isDivisibleBy7(num ) ) printf( "Divisible" ); else printf( "Not Divisible" ); return 0;}
// Java program to check whether a number is divisible by 7import java.io.*; class GFG{ // Function to check whether a number is divisible by 7 static boolean isDivisibleBy7(int num) { // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return true; if( num < 10 ) return false; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) ); } // Driver program public static void main (String[] args) { int num = 616; if(isDivisibleBy7(num)) System.out.println("Divisible"); else System.out.println("Not Divisible"); }} // Contributed by Pramod Kumar
# Python program to check whether a number is divisible by 7 # Function to check whether a number is divisible by 7def isDivisibleBy7(num) : # If number is negative, make it positive if num < 0 : return isDivisibleBy7( -num ) # Base cases if( num == 0 or num == 7 ) : return True if( num < 10 ) : return False # Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num // 10 - 2 * ( num - num // 10 * 10 ) ) # Driver programnum = 616if(isDivisibleBy7(num)) : print ("Divisible")else : print ("Not Divisible") # This code is contributed by Nikita Tiwari
// C# program to check whether a// number is divisible by 7using System; class GFG { // Function to check whether a // number is divisible by 7 static bool isDivisibleBy7(int num) { // If number is negative, // make it positive if( num < 0 ) return isDivisibleBy7(-num); // Base cases if( num == 0 || num == 7 ) return true; if( num < 10 ) return false; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7(num / 10 - 2 * ( num - num / 10 * 10 )); } // Driver Code public static void Main () { int num = 616; if(isDivisibleBy7(num)) Console.Write("Divisible"); else Console.Write("Not Divisible"); }} // This code is contributed by Nitin Mittal.
<?php// PHP Program to check whether// a number is divisible by 7 // Function to check whether a// number is divisible by 7function isDivisibleBy7( $num ){ // If number is negative, // make it positive if( $num < 0 ) return isDivisibleBy7( -$num ); // Base cases if( $num == 0 || $num == 7 ) return 1; if( $num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7($num / 10 - 2 * ($num - $num / 10 * 10 ) );} // Driver Code $num = 616; if( isDivisibleBy7($num )>=0 ) echo("Divisible"); else echo("Not Divisible"); // This code is contributed by vt_m.?>
<script> // js Program to check whether// a number is divisible by 7 // Function to check whether a// number is divisible by 7function isDivisibleBy7( num ){ // If number is negative, // make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7(num / 10 - 2 * (num - num / 10 * 10 ) );} // Driver Code let num = 616; if( isDivisibleBy7(num )>=0 ) document.write("Divisible"); else document.write("Not Divisible"); // This code is contributed by sravan kumar </script>
Divisible
Auxiliary Space: O(1)
How does this work? Let ‘b’ be the last digit of a number ‘n’ and let ‘a’ be the number we get when we split off ‘b’. The representation of the number may also be multiplied by any number relatively prime to the divisor without changing its divisibility. After observing that 7 divides 21, we can perform the following:
10.a + b
after multiplying by 2, this becomes
20.a + 2.b
and then
21.a - a + 2.b
Eliminating the multiple of 21 gives
-a + 2b
and multiplying by -1 gives
a - 2b
Method: To check given number is divisible by 7 or not by using modulo division operator “%”.
Python3
Javascript
# Python code# To check whether the given number is divisible by 7 or not #inputn=371# the above input can also be given as n=input() -> taking input from user# finding given number is divisible by 7 or notif int(n)%7==0: print("divisible")else: print("Not divisible") # this code is contributed by gangarajula laxmi
<script> // JavaScript code for the above approach // To check whether the given number is divisible by 7 or not //input let n = 371 // the above input can also be given as n=input() -> taking input from user // finding given number is divisible by 7 or not if (n % 7 == 0) document.write("divisible") else document.write("Not divisible") // This code is contributed by Potta Lokesh </script>
divisible
Method: Checking given number is divisible by 7 or not using modulo division.
C++
Java
C#
// C++ program to check if given number is divisible by 7 or// not using modulo division #include <iostream>using namespace std; int main() { // input number int num = 371; // checking if the given number is divisible by 7 or not // using modulo division operator if the output of num%7 // is equal to 0 then given number is divisible by 7 // otherwise not divisible by 7 if (num % 7 == 0) { cout << " divisible"; } else { cout << " not divisible"; } return 0;} // this code is contributed by gangarajula laxmi
// java program to check if given number is divisible by 7 or// not using modulo division import java.io.*; class GFG { public static void main (String[] args) { // input number int num=371; // checking if the given number is divisible by 7 or not // using modulo division operator if the output of num%7 // is equal to 0 then given number is divisible by 7 // otherwise not divisible by 7 if (num % 7 == 0) { System.out.println(" divisible"); } else { System.out.println(" not divisible"); } }} // this code is contributed by gangarajula laxmi
// C# program to check if given number is divisible by 7 or// not using modulo divisionusing System; class GFG { public static void Main(string[] args) { // input number int num = 371; // checking if the given number is divisible by 7 or // not // using modulo division operator if the output of // num%7 is equal to 0 then given number is // divisible by 7 otherwise not divisible by 7 if (num % 7 == 0) { Console.WriteLine(" divisible"); } else { Console.WriteLine(" not divisible"); } }} // This code is contributed by phasing17
There are other interesting methods to check divisibility by 7 and other numbers. See following Wiki page for details.References: http://en.wikipedia.org/wiki/Divisibility_rulePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
rathbhupendra
sravankumar8128
subhammahato348
amartyaghoshgfg
laxmigangarajula03
lokeshpotta20
phasing17
divisibility
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 740,
"s": 52,
"text": "Given a number, check if it is divisible by 7. You are not allowed to use modulo operator, floating point arithmetic is also not allowed. A simple method is repeated subtraction. Following is another interesting method.Divisibility by 7 can be checked by a recursive method. A number of the form 10a + b is divisible by 7 if and only if a – 2b is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a small number. Example: the number 371: 37 – (2×1) = 37 – 2 = 35; 3 – (2 × 5) = 3 – 10 = -7; thus, since -7 is divisible by 7, 371 is divisible by 7. Following is the implementation of the above method "
},
{
"code": null,
"e": 744,
"s": 740,
"text": "C++"
},
{
"code": null,
"e": 746,
"s": 744,
"text": "C"
},
{
"code": null,
"e": 751,
"s": 746,
"text": "Java"
},
{
"code": null,
"e": 759,
"s": 751,
"text": "Python3"
},
{
"code": null,
"e": 762,
"s": 759,
"text": "C#"
},
{
"code": null,
"e": 766,
"s": 762,
"text": "PHP"
},
{
"code": null,
"e": 777,
"s": 766,
"text": "Javascript"
},
{
"code": "// A Program to check whether a number is divisible by 7#include <bits/stdc++.h>using namespace std; int isDivisibleBy7( int num ){ // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );} // Driver codeint main(){ int num = 616; if( isDivisibleBy7(num ) ) cout << \"Divisible\" ; else cout << \"Not Divisible\" ; return 0;} // This code is contributed by rathbhupendra",
"e": 1438,
"s": 777,
"text": null
},
{
"code": "// A Program to check whether a number is divisible by 7#include <stdio.h> int isDivisibleBy7( int num ){ // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );} // Driver program to test above functionint main(){ int num = 616; if( isDivisibleBy7(num ) ) printf( \"Divisible\" ); else printf( \"Not Divisible\" ); return 0;}",
"e": 2045,
"s": 1438,
"text": null
},
{
"code": "// Java program to check whether a number is divisible by 7import java.io.*; class GFG{ // Function to check whether a number is divisible by 7 static boolean isDivisibleBy7(int num) { // If number is negative, make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return true; if( num < 10 ) return false; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) ); } // Driver program public static void main (String[] args) { int num = 616; if(isDivisibleBy7(num)) System.out.println(\"Divisible\"); else System.out.println(\"Not Divisible\"); }} // Contributed by Pramod Kumar",
"e": 2875,
"s": 2045,
"text": null
},
{
"code": "# Python program to check whether a number is divisible by 7 # Function to check whether a number is divisible by 7def isDivisibleBy7(num) : # If number is negative, make it positive if num < 0 : return isDivisibleBy7( -num ) # Base cases if( num == 0 or num == 7 ) : return True if( num < 10 ) : return False # Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7( num // 10 - 2 * ( num - num // 10 * 10 ) ) # Driver programnum = 616if(isDivisibleBy7(num)) : print (\"Divisible\")else : print (\"Not Divisible\") # This code is contributed by Nikita Tiwari",
"e": 3508,
"s": 2875,
"text": null
},
{
"code": "// C# program to check whether a// number is divisible by 7using System; class GFG { // Function to check whether a // number is divisible by 7 static bool isDivisibleBy7(int num) { // If number is negative, // make it positive if( num < 0 ) return isDivisibleBy7(-num); // Base cases if( num == 0 || num == 7 ) return true; if( num < 10 ) return false; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7(num / 10 - 2 * ( num - num / 10 * 10 )); } // Driver Code public static void Main () { int num = 616; if(isDivisibleBy7(num)) Console.Write(\"Divisible\"); else Console.Write(\"Not Divisible\"); }} // This code is contributed by Nitin Mittal.",
"e": 4372,
"s": 3508,
"text": null
},
{
"code": "<?php// PHP Program to check whether// a number is divisible by 7 // Function to check whether a// number is divisible by 7function isDivisibleBy7( $num ){ // If number is negative, // make it positive if( $num < 0 ) return isDivisibleBy7( -$num ); // Base cases if( $num == 0 || $num == 7 ) return 1; if( $num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7($num / 10 - 2 * ($num - $num / 10 * 10 ) );} // Driver Code $num = 616; if( isDivisibleBy7($num )>=0 ) echo(\"Divisible\"); else echo(\"Not Divisible\"); // This code is contributed by vt_m.?>",
"e": 5059,
"s": 4372,
"text": null
},
{
"code": "<script> // js Program to check whether// a number is divisible by 7 // Function to check whether a// number is divisible by 7function isDivisibleBy7( num ){ // If number is negative, // make it positive if( num < 0 ) return isDivisibleBy7( -num ); // Base cases if( num == 0 || num == 7 ) return 1; if( num < 10 ) return 0; // Recur for ( num / 10 - 2 * num % 10 ) return isDivisibleBy7(num / 10 - 2 * (num - num / 10 * 10 ) );} // Driver Code let num = 616; if( isDivisibleBy7(num )>=0 ) document.write(\"Divisible\"); else document.write(\"Not Divisible\"); // This code is contributed by sravan kumar </script>",
"e": 5774,
"s": 5059,
"text": null
},
{
"code": null,
"e": 5784,
"s": 5774,
"text": "Divisible"
},
{
"code": null,
"e": 5806,
"s": 5784,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6127,
"s": 5806,
"text": "How does this work? Let ‘b’ be the last digit of a number ‘n’ and let ‘a’ be the number we get when we split off ‘b’. The representation of the number may also be multiplied by any number relatively prime to the divisor without changing its divisibility. After observing that 7 divides 21, we can perform the following: "
},
{
"code": null,
"e": 6138,
"s": 6127,
"text": " 10.a + b "
},
{
"code": null,
"e": 6177,
"s": 6138,
"text": "after multiplying by 2, this becomes "
},
{
"code": null,
"e": 6190,
"s": 6177,
"text": " 20.a + 2.b "
},
{
"code": null,
"e": 6201,
"s": 6190,
"text": "and then "
},
{
"code": null,
"e": 6218,
"s": 6201,
"text": " 21.a - a + 2.b "
},
{
"code": null,
"e": 6257,
"s": 6218,
"text": "Eliminating the multiple of 21 gives "
},
{
"code": null,
"e": 6266,
"s": 6257,
"text": " -a + 2b"
},
{
"code": null,
"e": 6296,
"s": 6266,
"text": "and multiplying by -1 gives "
},
{
"code": null,
"e": 6304,
"s": 6296,
"text": " a - 2b"
},
{
"code": null,
"e": 6400,
"s": 6304,
"text": "Method: To check given number is divisible by 7 or not by using modulo division operator “%”. "
},
{
"code": null,
"e": 6408,
"s": 6400,
"text": "Python3"
},
{
"code": null,
"e": 6419,
"s": 6408,
"text": "Javascript"
},
{
"code": "# Python code# To check whether the given number is divisible by 7 or not #inputn=371# the above input can also be given as n=input() -> taking input from user# finding given number is divisible by 7 or notif int(n)%7==0: print(\"divisible\")else: print(\"Not divisible\") # this code is contributed by gangarajula laxmi",
"e": 6742,
"s": 6419,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // To check whether the given number is divisible by 7 or not //input let n = 371 // the above input can also be given as n=input() -> taking input from user // finding given number is divisible by 7 or not if (n % 7 == 0) document.write(\"divisible\") else document.write(\"Not divisible\") // This code is contributed by Potta Lokesh </script>",
"e": 7212,
"s": 6742,
"text": null
},
{
"code": null,
"e": 7222,
"s": 7212,
"text": "divisible"
},
{
"code": null,
"e": 7300,
"s": 7222,
"text": "Method: Checking given number is divisible by 7 or not using modulo division."
},
{
"code": null,
"e": 7304,
"s": 7300,
"text": "C++"
},
{
"code": null,
"e": 7309,
"s": 7304,
"text": "Java"
},
{
"code": null,
"e": 7312,
"s": 7309,
"text": "C#"
},
{
"code": "// C++ program to check if given number is divisible by 7 or// not using modulo division #include <iostream>using namespace std; int main() { // input number int num = 371; // checking if the given number is divisible by 7 or not // using modulo division operator if the output of num%7 // is equal to 0 then given number is divisible by 7 // otherwise not divisible by 7 if (num % 7 == 0) { cout << \" divisible\"; } else { cout << \" not divisible\"; } return 0;} // this code is contributed by gangarajula laxmi",
"e": 7873,
"s": 7312,
"text": null
},
{
"code": "// java program to check if given number is divisible by 7 or// not using modulo division import java.io.*; class GFG { public static void main (String[] args) { // input number int num=371; // checking if the given number is divisible by 7 or not // using modulo division operator if the output of num%7 // is equal to 0 then given number is divisible by 7 // otherwise not divisible by 7 if (num % 7 == 0) { System.out.println(\" divisible\"); } else { System.out.println(\" not divisible\"); } }} // this code is contributed by gangarajula laxmi",
"e": 8484,
"s": 7873,
"text": null
},
{
"code": "// C# program to check if given number is divisible by 7 or// not using modulo divisionusing System; class GFG { public static void Main(string[] args) { // input number int num = 371; // checking if the given number is divisible by 7 or // not // using modulo division operator if the output of // num%7 is equal to 0 then given number is // divisible by 7 otherwise not divisible by 7 if (num % 7 == 0) { Console.WriteLine(\" divisible\"); } else { Console.WriteLine(\" not divisible\"); } }} // This code is contributed by phasing17",
"e": 9063,
"s": 8484,
"text": null
},
{
"code": null,
"e": 9367,
"s": 9065,
"text": "There are other interesting methods to check divisibility by 7 and other numbers. See following Wiki page for details.References: http://en.wikipedia.org/wiki/Divisibility_rulePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 9380,
"s": 9367,
"text": "nitin mittal"
},
{
"code": null,
"e": 9385,
"s": 9380,
"text": "vt_m"
},
{
"code": null,
"e": 9399,
"s": 9385,
"text": "rathbhupendra"
},
{
"code": null,
"e": 9415,
"s": 9399,
"text": "sravankumar8128"
},
{
"code": null,
"e": 9431,
"s": 9415,
"text": "subhammahato348"
},
{
"code": null,
"e": 9447,
"s": 9431,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 9466,
"s": 9447,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 9480,
"s": 9466,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 9490,
"s": 9480,
"text": "phasing17"
},
{
"code": null,
"e": 9503,
"s": 9490,
"text": "divisibility"
},
{
"code": null,
"e": 9516,
"s": 9503,
"text": "Mathematical"
},
{
"code": null,
"e": 9535,
"s": 9516,
"text": "School Programming"
},
{
"code": null,
"e": 9548,
"s": 9535,
"text": "Mathematical"
}
] |
Print equal sum sets of array (Partition Problem) | Set 2 | 13 May, 2022
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples :
Input : arr = {5, 5, 1, 11}
Output : Set 1 = {5, 5, 1}, Set 2 = {11}
Sum of both the sets is 11 and equal.
Input : arr = {1, 5, 3}
Output : -1
No partitioning results in equal sum sets.
Prerequisite: Partition Problem Approach: In the previous post, a solution using recursion is discussed. In this post, a solution using Dynamic Programming is explained. The idea is to declare two sets set 1 and set 2. To recover the solution, traverse the boolean dp table backward starting from the final result dp[n][k], where n = number of elements and k = sum/2. Set 1 will consist of elements that contribute to sum k and other elements that do not contribute are added to set 2. Follow these steps at each position to recover the solution.
Check if dp[i-1][sum] is true or not. If it is true, then the current element does not contribute to sum k. Add this element to set 2. Update index i by i-1 and sum remains unchanged. If dp[i-1][sum] is false, then current element contribute to sum k. Add current element to set 1. Update index i by i-1 and sum by sum-arr[i-1].
Check if dp[i-1][sum] is true or not. If it is true, then the current element does not contribute to sum k. Add this element to set 2. Update index i by i-1 and sum remains unchanged.
If dp[i-1][sum] is false, then current element contribute to sum k. Add current element to set 1. Update index i by i-1 and sum by sum-arr[i-1].
Repeat the above steps until each index position is traversed.Implementation:
C++
Java
Python3
C#
Javascript
// CPP program to print equal sum sets of array.#include <bits/stdc++.h>using namespace std; // Function to print equal sum// sets of array.void printEqualSumSets(int arr[], int n){ int i, currSum; // Finding sum of array elements int sum = accumulate(arr, arr+n, 0); // Check sum is even or odd. If odd // then array cannot be partitioned. // Print -1 and return. if (sum & 1) { cout << "-1"; return; } // Divide sum by 2 to find // sum of two possible subsets. int k = sum >> 1; // Boolean DP table to store result // of states. // dp[i][j] = true if there is a // subset of elements in first i elements // of array that has sum equal to j. bool dp[n + 1][k + 1]; // If number of elements are zero, then // no sum can be obtained. for (i = 1; i <= k; i++) dp[0][i] = false; // Sum 0 can be obtained by not selecting // any element. for (i = 0; i <= n; i++) dp[i][0] = true; // Fill the DP table in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i][currSum] = dp[i - 1][currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i][currSum] = dp[i][currSum] | dp[i - 1][currSum - arr[i - 1]]; } } // Required sets set1 and set2. vector<int> set1, set2; // If partition is not possible print // -1 and return. if (!dp[n][k]) { cout << "-1\n"; return; } // Start from last element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does not // contribute to k, then it belongs // to set 2. if (dp[i - 1][currSum]) { i--; set2.push_back(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1][currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.push_back(arr[i]); } } // Print elements of both the sets. cout << "Set 1 elements: "; for (i = 0; i < set1.size(); i++) cout << set1[i] << " "; cout << "\nSet 2 elements: "; for (i = 0; i < set2.size(); i++) cout << set2[i] << " "; } // Driver program.int main(){ int arr[] = { 5, 5, 1, 11 }; int n = sizeof(arr) / sizeof(arr[0]); printEqualSumSets(arr, n); return 0;}
// Java program to print// equal sum sets of array.import java.io.*;import java.util.*; class GFG{ // Function to print equal // sum sets of array. static void printEqualSumSets(int []arr, int n) { int i, currSum, sum = 0; // Finding sum of array elements for (i = 0; i < arr.length; i++) sum += arr[i]; // Check sum is even or odd. // If odd then array cannot // be partitioned. Print -1 // and return. if ((sum & 1) == 1) { System.out.print("-1"); return; } // Divide sum by 2 to find // sum of two possible subsets. int k = sum >> 1; // Boolean DP table to store // result of states. // dp[i,j] = true if there is a // subset of elements in first i // elements of array that has sum // equal to j. boolean [][]dp = new boolean[n + 1][k + 1]; // If number of elements are zero, // then no sum can be obtained. for (i = 1; i <= k; i++) dp[0][i] = false; // Sum 0 can be obtained by // not selecting any element. for (i = 0; i <= n; i++) dp[i][0] = true; // Fill the DP table // in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i][currSum] = dp[i - 1][currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i][currSum] = dp[i][currSum] | dp[i - 1][currSum - arr[i - 1]]; } } // Required sets set1 and set2. List<Integer> set1 = new ArrayList<Integer>(); List<Integer> set2 = new ArrayList<Integer>(); // If partition is not possible // print -1 and return. if (!dp[n][k]) { System.out.print("-1\n"); return; } // Start from last // element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does // not contribute to k, then // it belongs to set 2. if (dp[i - 1][currSum]) { i--; set2.add(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1][currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.add(arr[i]); } } // Print elements of both the sets. System.out.print("Set 1 elements: "); for (i = 0; i < set1.size(); i++) System.out.print(set1.get(i) + " "); System.out.print("\nSet 2 elements: "); for (i = 0; i < set2.size(); i++) System.out.print(set2.get(i) + " "); } // Driver Code public static void main(String args[]) { int []arr = new int[]{ 5, 5, 1, 11 }; int n = arr.length; printEqualSumSets(arr, n); }} // This code is contributed by// Manish Shaw(manishshaw1)
# Python3 program to print equal sum# sets of array.import numpy as np # Function to print equal sum# sets of array.def printEqualSumSets(arr, n) : # Finding sum of array elements sum_array = sum(arr) # Check sum is even or odd. If odd # then array cannot be partitioned. # Print -1 and return. if (sum_array & 1) : print("-1") return # Divide sum by 2 to find # sum of two possible subsets. k = sum_array >> 1 # Boolean DP table to store result # of states. # dp[i][j] = true if there is a # subset of elements in first i elements # of array that has sum equal to j. dp = np.zeros((n + 1, k + 1)) # If number of elements are zero, then # no sum can be obtained. for i in range(1, k + 1) : dp[0][i] = False # Sum 0 can be obtained by not # selecting any element. for i in range(n + 1) : dp[i][0] = True # Fill the DP table in bottom up manner. for i in range(1, n + 1) : for currSum in range(1, k + 1) : # Excluding current element. dp[i][currSum] = dp[i - 1][currSum] # Including current element if (arr[i - 1] <= currSum) : dp[i][currSum] = (dp[i][currSum] or dp[i - 1][currSum - arr[i - 1]]) # Required sets set1 and set2. set1, set2 = [], [] # If partition is not possible print # -1 and return. if ( not dp[n][k]) : print("-1") return # Start from last element in dp table. i = n currSum = k while (i > 0 and currSum >= 0) : # If current element does not # contribute to k, then it belongs # to set 2. if (dp[i - 1][currSum]) : i -= 1 set2.append(arr[i]) # If current element contribute # to k then it belongs to set 1. elif (dp[i - 1][currSum - arr[i - 1]]) : i -= 1 currSum -= arr[i] set1.append(arr[i]) # Print elements of both the sets. print("Set 1 elements:", end = " ") for i in range(len(set1)) : print(set1[i], end = " ") print("\nSet 2 elements:", end = " ") for i in range(len(set2)) : print(set2[i], end = " ") # Driver Codeif __name__ == "__main__" : arr = [ 5, 5, 1, 11 ] n = len(arr) printEqualSumSets(arr, n) # This code is contributed by Ryuga
// C# program to print// equal sum sets of array.using System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to print equal // sum sets of array. static void printEqualSumSets(int []arr, int n) { int i, currSum, sum = 0; // Finding sum of array elements for (i = 0; i < arr.Length; i++) sum += arr[i]; // Check sum is even or odd. // If odd then array cannot // be partitioned. Print -1 // and return. if ((sum & 1) == 1) { Console.Write("-1"); return; } // Divide sum by 2 to find // sum of two possible subsets. int k = sum >> 1; // Boolean DP table to store // result of states. // dp[i,j] = true if there is a // subset of elements in first i // elements of array that has sum // equal to j. bool [,]dp = new bool[n + 1, k + 1]; // If number of elements are zero, // then no sum can be obtained. for (i = 1; i <= k; i++) dp[0, i] = false; // Sum 0 can be obtained by // not selecting any element. for (i = 0; i <= n; i++) dp[i, 0] = true; // Fill the DP table // in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i, currSum] = dp[i - 1, currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i, currSum] = dp[i, currSum] | dp[i - 1, currSum - arr[i - 1]]; } } // Required sets set1 and set2. List<int> set1 = new List<int>(); List<int> set2 = new List<int>(); // If partition is not possible // print -1 and return. if (!dp[n, k]) { Console.Write("-1\n"); return; } // Start from last // element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does // not contribute to k, then // it belongs to set 2. if (dp[i - 1, currSum]) { i--; set2.Add(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1, currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.Add(arr[i]); } } // Print elements of both the sets. Console.Write("Set 1 elements: "); for (i = 0; i < set1.Count; i++) Console.Write(set1[i] + " "); Console.Write("\nSet 2 elements: "); for (i = 0; i < set2.Count; i++) Console.Write(set2[i] + " "); } // Driver Code. static void Main() { int []arr = { 5, 5, 1, 11 }; int n = arr.Length; printEqualSumSets(arr, n); }}// This code is contributed by// Manish Shaw(manishshaw1)
<script> // Javascript program to print equal sum sets of array. // Function to print equal sum// sets of array.function printEqualSumSets(arr, n){ var i, currSum; // Finding sum of array elements var sum = 0; for(var i =0; i< arr.length; i++) { sum+=arr[i]; } // Check sum is even or odd. If odd // then array cannot be partitioned. // Print -1 and return. if (sum & 1) { document.write( "-1"); return; } // Divide sum by 2 to find // sum of two possible subsets. var k = sum >> 1; // Boolean DP table to store result // of states. // dp[i][j] = true if there is a // subset of elements in first i elements // of array that has sum equal to j. var dp = Array.from(Array(n+1), ()=> Array(k+1)); // If number of elements are zero, then // no sum can be obtained. for (i = 1; i <= k; i++) dp[0][i] = false; // Sum 0 can be obtained by not selecting // any element. for (i = 0; i <= n; i++) dp[i][0] = true; // Fill the DP table in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i][currSum] = dp[i - 1][currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i][currSum] = dp[i][currSum] | dp[i - 1][currSum - arr[i - 1]]; } } // Required sets set1 and set2. var set1 = [], set2=[]; // If partition is not possible print // -1 and return. if (!dp[n][k]) { document.write( "-1<br>"); return; } // Start from last element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does not // contribute to k, then it belongs // to set 2. if (dp[i - 1][currSum]) { i--; set2.push(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1][currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.push(arr[i]); } } // Print elements of both the sets. document.write( "Set 1 elements: "); for (i = 0; i < set1.length; i++) document.write( set1[i] + " "); document.write( "<br>Set 2 elements: "); for (i = 0; i < set2.length; i++) document.write( set2[i] + " "); } // Driver program.var arr = [ 5, 5, 1, 11 ];var n = arr.length;printEqualSumSets(arr, n); </script>
Set 1 elements: 1 5 5
Set 2 elements: 11
Time Complexity: O(n*k), where k = sum(arr) / 2 Auxiliary Space: O(n*k)
manishshaw1
ankthon
rrrtnx
sumitgumber28
subset
Arrays
Dynamic Programming
Arrays
Dynamic Programming
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 285,
"s": 52,
"text": "Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : "
},
{
"code": null,
"e": 472,
"s": 285,
"text": "Input : arr = {5, 5, 1, 11}\nOutput : Set 1 = {5, 5, 1}, Set 2 = {11}\nSum of both the sets is 11 and equal.\n\nInput : arr = {1, 5, 3}\nOutput : -1\nNo partitioning results in equal sum sets."
},
{
"code": null,
"e": 1023,
"s": 474,
"text": "Prerequisite: Partition Problem Approach: In the previous post, a solution using recursion is discussed. In this post, a solution using Dynamic Programming is explained. The idea is to declare two sets set 1 and set 2. To recover the solution, traverse the boolean dp table backward starting from the final result dp[n][k], where n = number of elements and k = sum/2. Set 1 will consist of elements that contribute to sum k and other elements that do not contribute are added to set 2. Follow these steps at each position to recover the solution. "
},
{
"code": null,
"e": 1355,
"s": 1023,
"text": "Check if dp[i-1][sum] is true or not. If it is true, then the current element does not contribute to sum k. Add this element to set 2. Update index i by i-1 and sum remains unchanged. If dp[i-1][sum] is false, then current element contribute to sum k. Add current element to set 1. Update index i by i-1 and sum by sum-arr[i-1]. "
},
{
"code": null,
"e": 1541,
"s": 1355,
"text": "Check if dp[i-1][sum] is true or not. If it is true, then the current element does not contribute to sum k. Add this element to set 2. Update index i by i-1 and sum remains unchanged. "
},
{
"code": null,
"e": 1688,
"s": 1541,
"text": "If dp[i-1][sum] is false, then current element contribute to sum k. Add current element to set 1. Update index i by i-1 and sum by sum-arr[i-1]. "
},
{
"code": null,
"e": 1768,
"s": 1688,
"text": "Repeat the above steps until each index position is traversed.Implementation: "
},
{
"code": null,
"e": 1772,
"s": 1768,
"text": "C++"
},
{
"code": null,
"e": 1777,
"s": 1772,
"text": "Java"
},
{
"code": null,
"e": 1785,
"s": 1777,
"text": "Python3"
},
{
"code": null,
"e": 1788,
"s": 1785,
"text": "C#"
},
{
"code": null,
"e": 1799,
"s": 1788,
"text": "Javascript"
},
{
"code": "// CPP program to print equal sum sets of array.#include <bits/stdc++.h>using namespace std; // Function to print equal sum// sets of array.void printEqualSumSets(int arr[], int n){ int i, currSum; // Finding sum of array elements int sum = accumulate(arr, arr+n, 0); // Check sum is even or odd. If odd // then array cannot be partitioned. // Print -1 and return. if (sum & 1) { cout << \"-1\"; return; } // Divide sum by 2 to find // sum of two possible subsets. int k = sum >> 1; // Boolean DP table to store result // of states. // dp[i][j] = true if there is a // subset of elements in first i elements // of array that has sum equal to j. bool dp[n + 1][k + 1]; // If number of elements are zero, then // no sum can be obtained. for (i = 1; i <= k; i++) dp[0][i] = false; // Sum 0 can be obtained by not selecting // any element. for (i = 0; i <= n; i++) dp[i][0] = true; // Fill the DP table in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i][currSum] = dp[i - 1][currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i][currSum] = dp[i][currSum] | dp[i - 1][currSum - arr[i - 1]]; } } // Required sets set1 and set2. vector<int> set1, set2; // If partition is not possible print // -1 and return. if (!dp[n][k]) { cout << \"-1\\n\"; return; } // Start from last element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does not // contribute to k, then it belongs // to set 2. if (dp[i - 1][currSum]) { i--; set2.push_back(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1][currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.push_back(arr[i]); } } // Print elements of both the sets. cout << \"Set 1 elements: \"; for (i = 0; i < set1.size(); i++) cout << set1[i] << \" \"; cout << \"\\nSet 2 elements: \"; for (i = 0; i < set2.size(); i++) cout << set2[i] << \" \"; } // Driver program.int main(){ int arr[] = { 5, 5, 1, 11 }; int n = sizeof(arr) / sizeof(arr[0]); printEqualSumSets(arr, n); return 0;}",
"e": 4300,
"s": 1799,
"text": null
},
{
"code": "// Java program to print// equal sum sets of array.import java.io.*;import java.util.*; class GFG{ // Function to print equal // sum sets of array. static void printEqualSumSets(int []arr, int n) { int i, currSum, sum = 0; // Finding sum of array elements for (i = 0; i < arr.length; i++) sum += arr[i]; // Check sum is even or odd. // If odd then array cannot // be partitioned. Print -1 // and return. if ((sum & 1) == 1) { System.out.print(\"-1\"); return; } // Divide sum by 2 to find // sum of two possible subsets. int k = sum >> 1; // Boolean DP table to store // result of states. // dp[i,j] = true if there is a // subset of elements in first i // elements of array that has sum // equal to j. boolean [][]dp = new boolean[n + 1][k + 1]; // If number of elements are zero, // then no sum can be obtained. for (i = 1; i <= k; i++) dp[0][i] = false; // Sum 0 can be obtained by // not selecting any element. for (i = 0; i <= n; i++) dp[i][0] = true; // Fill the DP table // in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i][currSum] = dp[i - 1][currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i][currSum] = dp[i][currSum] | dp[i - 1][currSum - arr[i - 1]]; } } // Required sets set1 and set2. List<Integer> set1 = new ArrayList<Integer>(); List<Integer> set2 = new ArrayList<Integer>(); // If partition is not possible // print -1 and return. if (!dp[n][k]) { System.out.print(\"-1\\n\"); return; } // Start from last // element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does // not contribute to k, then // it belongs to set 2. if (dp[i - 1][currSum]) { i--; set2.add(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1][currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.add(arr[i]); } } // Print elements of both the sets. System.out.print(\"Set 1 elements: \"); for (i = 0; i < set1.size(); i++) System.out.print(set1.get(i) + \" \"); System.out.print(\"\\nSet 2 elements: \"); for (i = 0; i < set2.size(); i++) System.out.print(set2.get(i) + \" \"); } // Driver Code public static void main(String args[]) { int []arr = new int[]{ 5, 5, 1, 11 }; int n = arr.length; printEqualSumSets(arr, n); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 7651,
"s": 4300,
"text": null
},
{
"code": "# Python3 program to print equal sum# sets of array.import numpy as np # Function to print equal sum# sets of array.def printEqualSumSets(arr, n) : # Finding sum of array elements sum_array = sum(arr) # Check sum is even or odd. If odd # then array cannot be partitioned. # Print -1 and return. if (sum_array & 1) : print(\"-1\") return # Divide sum by 2 to find # sum of two possible subsets. k = sum_array >> 1 # Boolean DP table to store result # of states. # dp[i][j] = true if there is a # subset of elements in first i elements # of array that has sum equal to j. dp = np.zeros((n + 1, k + 1)) # If number of elements are zero, then # no sum can be obtained. for i in range(1, k + 1) : dp[0][i] = False # Sum 0 can be obtained by not # selecting any element. for i in range(n + 1) : dp[i][0] = True # Fill the DP table in bottom up manner. for i in range(1, n + 1) : for currSum in range(1, k + 1) : # Excluding current element. dp[i][currSum] = dp[i - 1][currSum] # Including current element if (arr[i - 1] <= currSum) : dp[i][currSum] = (dp[i][currSum] or dp[i - 1][currSum - arr[i - 1]]) # Required sets set1 and set2. set1, set2 = [], [] # If partition is not possible print # -1 and return. if ( not dp[n][k]) : print(\"-1\") return # Start from last element in dp table. i = n currSum = k while (i > 0 and currSum >= 0) : # If current element does not # contribute to k, then it belongs # to set 2. if (dp[i - 1][currSum]) : i -= 1 set2.append(arr[i]) # If current element contribute # to k then it belongs to set 1. elif (dp[i - 1][currSum - arr[i - 1]]) : i -= 1 currSum -= arr[i] set1.append(arr[i]) # Print elements of both the sets. print(\"Set 1 elements:\", end = \" \") for i in range(len(set1)) : print(set1[i], end = \" \") print(\"\\nSet 2 elements:\", end = \" \") for i in range(len(set2)) : print(set2[i], end = \" \") # Driver Codeif __name__ == \"__main__\" : arr = [ 5, 5, 1, 11 ] n = len(arr) printEqualSumSets(arr, n) # This code is contributed by Ryuga",
"e": 10034,
"s": 7651,
"text": null
},
{
"code": "// C# program to print// equal sum sets of array.using System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to print equal // sum sets of array. static void printEqualSumSets(int []arr, int n) { int i, currSum, sum = 0; // Finding sum of array elements for (i = 0; i < arr.Length; i++) sum += arr[i]; // Check sum is even or odd. // If odd then array cannot // be partitioned. Print -1 // and return. if ((sum & 1) == 1) { Console.Write(\"-1\"); return; } // Divide sum by 2 to find // sum of two possible subsets. int k = sum >> 1; // Boolean DP table to store // result of states. // dp[i,j] = true if there is a // subset of elements in first i // elements of array that has sum // equal to j. bool [,]dp = new bool[n + 1, k + 1]; // If number of elements are zero, // then no sum can be obtained. for (i = 1; i <= k; i++) dp[0, i] = false; // Sum 0 can be obtained by // not selecting any element. for (i = 0; i <= n; i++) dp[i, 0] = true; // Fill the DP table // in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i, currSum] = dp[i - 1, currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i, currSum] = dp[i, currSum] | dp[i - 1, currSum - arr[i - 1]]; } } // Required sets set1 and set2. List<int> set1 = new List<int>(); List<int> set2 = new List<int>(); // If partition is not possible // print -1 and return. if (!dp[n, k]) { Console.Write(\"-1\\n\"); return; } // Start from last // element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does // not contribute to k, then // it belongs to set 2. if (dp[i - 1, currSum]) { i--; set2.Add(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1, currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.Add(arr[i]); } } // Print elements of both the sets. Console.Write(\"Set 1 elements: \"); for (i = 0; i < set1.Count; i++) Console.Write(set1[i] + \" \"); Console.Write(\"\\nSet 2 elements: \"); for (i = 0; i < set2.Count; i++) Console.Write(set2[i] + \" \"); } // Driver Code. static void Main() { int []arr = { 5, 5, 1, 11 }; int n = arr.Length; printEqualSumSets(arr, n); }}// This code is contributed by// Manish Shaw(manishshaw1)",
"e": 13289,
"s": 10034,
"text": null
},
{
"code": "<script> // Javascript program to print equal sum sets of array. // Function to print equal sum// sets of array.function printEqualSumSets(arr, n){ var i, currSum; // Finding sum of array elements var sum = 0; for(var i =0; i< arr.length; i++) { sum+=arr[i]; } // Check sum is even or odd. If odd // then array cannot be partitioned. // Print -1 and return. if (sum & 1) { document.write( \"-1\"); return; } // Divide sum by 2 to find // sum of two possible subsets. var k = sum >> 1; // Boolean DP table to store result // of states. // dp[i][j] = true if there is a // subset of elements in first i elements // of array that has sum equal to j. var dp = Array.from(Array(n+1), ()=> Array(k+1)); // If number of elements are zero, then // no sum can be obtained. for (i = 1; i <= k; i++) dp[0][i] = false; // Sum 0 can be obtained by not selecting // any element. for (i = 0; i <= n; i++) dp[i][0] = true; // Fill the DP table in bottom up manner. for (i = 1; i <= n; i++) { for (currSum = 1; currSum <= k; currSum++) { // Excluding current element. dp[i][currSum] = dp[i - 1][currSum]; // Including current element if (arr[i - 1] <= currSum) dp[i][currSum] = dp[i][currSum] | dp[i - 1][currSum - arr[i - 1]]; } } // Required sets set1 and set2. var set1 = [], set2=[]; // If partition is not possible print // -1 and return. if (!dp[n][k]) { document.write( \"-1<br>\"); return; } // Start from last element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0) { // If current element does not // contribute to k, then it belongs // to set 2. if (dp[i - 1][currSum]) { i--; set2.push(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1][currSum - arr[i - 1]]) { i--; currSum -= arr[i]; set1.push(arr[i]); } } // Print elements of both the sets. document.write( \"Set 1 elements: \"); for (i = 0; i < set1.length; i++) document.write( set1[i] + \" \"); document.write( \"<br>Set 2 elements: \"); for (i = 0; i < set2.length; i++) document.write( set2[i] + \" \"); } // Driver program.var arr = [ 5, 5, 1, 11 ];var n = arr.length;printEqualSumSets(arr, n); </script>",
"e": 15832,
"s": 13289,
"text": null
},
{
"code": null,
"e": 15874,
"s": 15832,
"text": "Set 1 elements: 1 5 5 \nSet 2 elements: 11"
},
{
"code": null,
"e": 15949,
"s": 15876,
"text": "Time Complexity: O(n*k), where k = sum(arr) / 2 Auxiliary Space: O(n*k) "
},
{
"code": null,
"e": 15961,
"s": 15949,
"text": "manishshaw1"
},
{
"code": null,
"e": 15969,
"s": 15961,
"text": "ankthon"
},
{
"code": null,
"e": 15976,
"s": 15969,
"text": "rrrtnx"
},
{
"code": null,
"e": 15990,
"s": 15976,
"text": "sumitgumber28"
},
{
"code": null,
"e": 15997,
"s": 15990,
"text": "subset"
},
{
"code": null,
"e": 16004,
"s": 15997,
"text": "Arrays"
},
{
"code": null,
"e": 16024,
"s": 16004,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 16031,
"s": 16024,
"text": "Arrays"
},
{
"code": null,
"e": 16051,
"s": 16031,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 16058,
"s": 16051,
"text": "subset"
}
] |
Matplotlib.pyplot.show() in Python | 11 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
Sample Code –
# sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show()
Output:
The show() function in pyplot module of matplotlib library is used to display all figures.
Syntax:
matplotlib.pyplot.show(*args, **kw)
Parameters: This method accepts only one parameter which is discussed below:
block : This parameter is used to override the blocking behavior described above.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.show() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()x = np.arange(20) / 50y = (x + 0.1)*2 val1 = [True, False] * 10val2 = [False, True] * 10 plt.errorbar(x, y, xerr = 0.1, xlolims = True, label ='Line 1') y = (x + 0.3)*3 plt.errorbar(x + 0.6, y, xerr = 0.1, xuplims = val1, xlolims = val2, label ='Line 2') y = (x + 0.6)*4plt.errorbar(x + 1.2, y, xerr = 0.1, xuplims = True, label ='Line 3') plt.legend() fig.suptitle('matplotlib.pyplot.show() Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 10, 500)y = np.sin(x**2)+np.cos(x) fig, ax = plt.subplots() ax.plot(x, y, label ='Line 1') ax.plot(x, y - 0.6, label ='Line 2') ax.legend() fig.suptitle('matplotlib.pyplot.show() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Apr, 2020"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 237,
"s": 223,
"text": "Sample Code –"
},
{
"code": "# sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() ",
"e": 336,
"s": 237,
"text": null
},
{
"code": null,
"e": 344,
"s": 336,
"text": "Output:"
},
{
"code": null,
"e": 435,
"s": 344,
"text": "The show() function in pyplot module of matplotlib library is used to display all figures."
},
{
"code": null,
"e": 443,
"s": 435,
"text": "Syntax:"
},
{
"code": null,
"e": 480,
"s": 443,
"text": "matplotlib.pyplot.show(*args, **kw)\n"
},
{
"code": null,
"e": 557,
"s": 480,
"text": "Parameters: This method accepts only one parameter which is discussed below:"
},
{
"code": null,
"e": 639,
"s": 557,
"text": "block : This parameter is used to override the blocking behavior described above."
},
{
"code": null,
"e": 687,
"s": 639,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 773,
"s": 687,
"text": "Below examples illustrate the matplotlib.pyplot.show() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 785,
"s": 773,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()x = np.arange(20) / 50y = (x + 0.1)*2 val1 = [True, False] * 10val2 = [False, True] * 10 plt.errorbar(x, y, xerr = 0.1, xlolims = True, label ='Line 1') y = (x + 0.3)*3 plt.errorbar(x + 0.6, y, xerr = 0.1, xuplims = val1, xlolims = val2, label ='Line 2') y = (x + 0.6)*4plt.errorbar(x + 1.2, y, xerr = 0.1, xuplims = True, label ='Line 3') plt.legend() fig.suptitle('matplotlib.pyplot.show() Example')plt.show()",
"e": 1437,
"s": 785,
"text": null
},
{
"code": null,
"e": 1445,
"s": 1437,
"text": "Output:"
},
{
"code": null,
"e": 1457,
"s": 1445,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 10, 500)y = np.sin(x**2)+np.cos(x) fig, ax = plt.subplots() ax.plot(x, y, label ='Line 1') ax.plot(x, y - 0.6, label ='Line 2') ax.legend() fig.suptitle('matplotlib.pyplot.show() Example')plt.show()",
"e": 1770,
"s": 1457,
"text": null
},
{
"code": null,
"e": 1778,
"s": 1770,
"text": "Output:"
},
{
"code": null,
"e": 1796,
"s": 1778,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1803,
"s": 1796,
"text": "Python"
}
] |
GATE | GATE CS 2013 | Question 33 | 11 Oct, 2021
Consider the DFA given.
Which of the following are FALSE?
1. Complement of L(A) is context-free.
2. L(A) = L((11*0+0)(0 + 1)*0*1*)
3. For the language accepted by A, A is the minimal DFA.
4. A accepts all strings over {0, 1} of length at least 2.
(A) 1 and 3 only(B) 2 and 4 only(C) 2 and 3 only(D) 3 and 4 onlyAnswer: (D)Explanation: 1 is true. L(A) is regular, its complement would also be regular. A regular language is also context free.
2 is true.
3 is false, the DFA can be minimized to two states. Where the second state is final state and we reach second state after a 0.
4 is clearly false as the DFA accepts a single 0.
GATE PYQ's on Finite Automata with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.6K subscribersGATE PYQ's on Finite Automata with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSEWatch 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:0032:02 / 44:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pHUoDvqVSag" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 76,
"s": 52,
"text": "Consider the DFA given."
},
{
"code": null,
"e": 110,
"s": 76,
"text": "Which of the following are FALSE?"
},
{
"code": null,
"e": 300,
"s": 110,
"text": "1. Complement of L(A) is context-free.\n2. L(A) = L((11*0+0)(0 + 1)*0*1*)\n3. For the language accepted by A, A is the minimal DFA.\n4. A accepts all strings over {0, 1} of length at least 2. "
},
{
"code": null,
"e": 495,
"s": 300,
"text": "(A) 1 and 3 only(B) 2 and 4 only(C) 2 and 3 only(D) 3 and 4 onlyAnswer: (D)Explanation: 1 is true. L(A) is regular, its complement would also be regular. A regular language is also context free."
},
{
"code": null,
"e": 506,
"s": 495,
"text": "2 is true."
},
{
"code": null,
"e": 633,
"s": 506,
"text": "3 is false, the DFA can be minimized to two states. Where the second state is final state and we reach second state after a 0."
},
{
"code": null,
"e": 683,
"s": 633,
"text": "4 is clearly false as the DFA accepts a single 0."
},
{
"code": null,
"e": 1681,
"s": 683,
"text": "GATE PYQ's on Finite Automata with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.6K subscribersGATE PYQ's on Finite Automata with Praddyumn Shukla | GeeksforGeeks GATE | GATE CSEWatch 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:0032:02 / 44:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=pHUoDvqVSag\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 1694,
"s": 1681,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 1712,
"s": 1694,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 1717,
"s": 1712,
"text": "GATE"
}
] |
How to find the column and row indices of values in a matrix using which function in R? | To find the row and column indices of values in a matrix, we cannot simply use which function because it returns the index based on sequence of the numbers in the matrix. For example, if we have a matrix M as below −
1 2 3
4 1 6
7 8 1
Now if we try to find the index using which(M==1) then it will return 1 5 9
Because 1 is placed at 1, 5 and 9.
Hence, we need to use arr.ind = TRUE so that the matrix can be read as an array by which function.
Consider the below matrix −
Live Demo
> M<-matrix(sample(1:10,100,replace=TRUE),nrow=10)
> M
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 9 5 4 5 2 7 6 7 1 1
[2,] 2 6 5 4 2 4 6 4 4 8
[3,] 10 4 9 10 8 4 4 4 5 5
[4,] 8 2 5 10 4 1 3 10 5 8
[5,] 10 1 8 9 10 10 3 8 6 10
[6,] 4 3 4 8 8 4 9 1 9 7
[7,] 5 8 1 5 5 9 9 10 8 7
[8,] 9 9 9 5 5 9 7 2 5 2
[9,] 5 6 5 6 8 9 9 10 1 9
[10,] 7 1 1 6 8 9 5 1 2 4
Finding the index for 1 to 10 values in the matrix M −
> which(M==1,arr.ind=TRUE)
row col
[1,] 5 2
[2,] 10 2
[3,] 7 3
[4,] 10 3
[5,] 4 6
[6,] 6 8
[7,] 10 8
[8,] 1 9
[9,] 9 9
[10,] 1 10
> which(M==2,arr.ind=TRUE)
row col
[1,] 2 1
[2,] 4 2
[3,] 1 5
[4,] 2 5
[5,] 8 8
[6,] 10 9
[7,] 8 10
> which(M==3,arr.ind=TRUE)
row col
[1,] 6 2
[2,] 4 7
[3,] 5 7
> which(M==4,arr.ind=TRUE)
row col
[1,] 6 1
[2,] 3 2
[3,] 1 3
[4,] 6 3
[5,] 2 4
[6,] 4 5
[7,] 2 6
[8,] 3 6
[9,] 6 6
[10,] 3 7
[11,] 2 8
[12,] 3 8
[13,] 2 9
[14,] 10 10
> which(M==5,arr.ind=TRUE)
row col
[1,] 7 1
[2,] 9 1
[3,] 1 2
[4,] 2 3
[5,] 4 3
[6,] 9 3
[7,] 1 4
[8,] 7 4
[9,] 8 4
[10,] 7 5
[11,] 8 5
[12,] 10 7
[13,] 3 9
[14,] 4 9
[15,] 8 9
[16,] 3 10
> which(M==6,arr.ind=TRUE)
row col
[1,] 2 2
[2,] 9 2
[3,] 9 4
[4,] 10 4
[5,] 1 7
[6,] 2 7
[7,] 5 9
> which(M==7,arr.ind=TRUE)
row col
[1,] 10 1
[2,] 1 6
[3,] 8 7
[4,] 1 8
[5,] 6 10
[6,] 7 10
> which(M==8,arr.ind=TRUE)
row col
[1,] 4 1
[2,] 7 2
[3,] 5 3
[4,] 6 4
[5,] 3 5
[6,] 6 5
[7,] 9 5
[8,] 10 5
[9,] 5 8
[10,] 7 9
[11,] 2 10
[12,] 4 10
> which(M==9,arr.ind=TRUE)
row col
[1,] 1 1
[2,] 8 1
[3,] 8 2
[4,] 3 3
[5,] 8 3
[6,] 5 4
[7,] 7 6
[8,] 8 6
[9,] 9 6
[10,] 10 6
[11,] 6 7
[12,] 7 7
[13,] 9 7
[14,] 6 9
[15,] 9 10
> which(M==10,arr.ind=TRUE)
row col
[1,] 3 1
[2,] 5 1
[3,] 3 4
[4,] 4 4
[5,] 5 5
[6,] 5 6
[7,] 4 8
[8,] 7 8
[9,] 9 8
[10,] 5 10 | [
{
"code": null,
"e": 1279,
"s": 1062,
"text": "To find the row and column indices of values in a matrix, we cannot simply use which function because it returns the index based on sequence of the numbers in the matrix. For example, if we have a matrix M as below −"
},
{
"code": null,
"e": 1297,
"s": 1279,
"text": "1 2 3\n4 1 6\n7 8 1"
},
{
"code": null,
"e": 1373,
"s": 1297,
"text": "Now if we try to find the index using which(M==1) then it will return 1 5 9"
},
{
"code": null,
"e": 1408,
"s": 1373,
"text": "Because 1 is placed at 1, 5 and 9."
},
{
"code": null,
"e": 1507,
"s": 1408,
"text": "Hence, we need to use arr.ind = TRUE so that the matrix can be read as an array by which function."
},
{
"code": null,
"e": 1535,
"s": 1507,
"text": "Consider the below matrix −"
},
{
"code": null,
"e": 1546,
"s": 1535,
"text": " Live Demo"
},
{
"code": null,
"e": 1601,
"s": 1546,
"text": "> M<-matrix(sample(1:10,100,replace=TRUE),nrow=10)\n> M"
},
{
"code": null,
"e": 1913,
"s": 1601,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 9 5 4 5 2 7 6 7 1 1\n[2,] 2 6 5 4 2 4 6 4 4 8\n[3,] 10 4 9 10 8 4 4 4 5 5\n[4,] 8 2 5 10 4 1 3 10 5 8\n[5,] 10 1 8 9 10 10 3 8 6 10\n[6,] 4 3 4 8 8 4 9 1 9 7\n[7,] 5 8 1 5 5 9 9 10 8 7\n[8,] 9 9 9 5 5 9 7 2 5 2\n[9,] 5 6 5 6 8 9 9 10 1 9\n[10,] 7 1 1 6 8 9 5 1 2 4"
},
{
"code": null,
"e": 1968,
"s": 1913,
"text": "Finding the index for 1 to 10 values in the matrix M −"
},
{
"code": null,
"e": 1995,
"s": 1968,
"text": "> which(M==1,arr.ind=TRUE)"
},
{
"code": null,
"e": 2098,
"s": 1995,
"text": "row col\n[1,] 5 2\n[2,] 10 2\n[3,] 7 3\n[4,] 10 3\n[5,] 4 6\n[6,] 6 8\n[7,] 10 8\n[8,] 1 9\n[9,] 9 9\n[10,] 1 10"
},
{
"code": null,
"e": 2125,
"s": 2098,
"text": "> which(M==2,arr.ind=TRUE)"
},
{
"code": null,
"e": 2198,
"s": 2125,
"text": "row col\n[1,] 2 1\n[2,] 4 2\n[3,] 1 5\n[4,] 2 5\n[5,] 8 8\n[6,] 10 9\n[7,] 8 10"
},
{
"code": null,
"e": 2225,
"s": 2198,
"text": "> which(M==3,arr.ind=TRUE)"
},
{
"code": null,
"e": 2260,
"s": 2225,
"text": "row col\n[1,] 6 2\n[2,] 4 7\n[3,] 5 7"
},
{
"code": null,
"e": 2287,
"s": 2260,
"text": "> which(M==4,arr.ind=TRUE)"
},
{
"code": null,
"e": 2428,
"s": 2287,
"text": "row col\n[1,] 6 1\n[2,] 3 2\n[3,] 1 3\n[4,] 6 3\n[5,] 2 4\n[6,] 4 5\n[7,] 2 6\n[8,] 3 6\n[9,] 6 6\n[10,] 3 7\n[11,] 2 8\n[12,] 3 8\n[13,] 2 9\n[14,] 10 10"
},
{
"code": null,
"e": 2455,
"s": 2428,
"text": "> which(M==5,arr.ind=TRUE)"
},
{
"code": null,
"e": 2616,
"s": 2455,
"text": "row col\n[1,] 7 1\n[2,] 9 1\n[3,] 1 2\n[4,] 2 3\n[5,] 4 3\n[6,] 9 3\n[7,] 1 4\n[8,] 7 4\n[9,] 8 4\n[10,] 7 5\n[11,] 8 5\n[12,] 10 7\n[13,] 3 9\n[14,] 4 9\n[15,] 8 9\n[16,] 3 10"
},
{
"code": null,
"e": 2643,
"s": 2616,
"text": "> which(M==6,arr.ind=TRUE)"
},
{
"code": null,
"e": 2715,
"s": 2643,
"text": "row col\n[1,] 2 2\n[2,] 9 2\n[3,] 9 4\n[4,] 10 4\n[5,] 1 7\n[6,] 2 7\n[7,] 5 9"
},
{
"code": null,
"e": 2742,
"s": 2715,
"text": "> which(M==7,arr.ind=TRUE)"
},
{
"code": null,
"e": 2807,
"s": 2742,
"text": "row col\n[1,] 10 1\n[2,] 1 6\n[3,] 8 7\n[4,] 1 8\n[5,] 6 10\n[6,] 7 10"
},
{
"code": null,
"e": 2834,
"s": 2807,
"text": "> which(M==8,arr.ind=TRUE)"
},
{
"code": null,
"e": 2956,
"s": 2834,
"text": "row col\n[1,] 4 1\n[2,] 7 2\n[3,] 5 3\n[4,] 6 4\n[5,] 3 5\n[6,] 6 5\n[7,] 9 5\n[8,] 10 5\n[9,] 5 8\n[10,] 7 9\n[11,] 2 10\n[12,] 4 10"
},
{
"code": null,
"e": 2983,
"s": 2956,
"text": "> which(M==9,arr.ind=TRUE)"
},
{
"code": null,
"e": 3134,
"s": 2983,
"text": "row col\n[1,] 1 1\n[2,] 8 1\n[3,] 8 2\n[4,] 3 3\n[5,] 8 3\n[6,] 5 4\n[7,] 7 6\n[8,] 8 6\n[9,] 9 6\n[10,] 10 6\n[11,] 6 7\n[12,] 7 7\n[13,] 9 7\n[14,] 6 9\n[15,] 9 10"
},
{
"code": null,
"e": 3162,
"s": 3134,
"text": "> which(M==10,arr.ind=TRUE)"
},
{
"code": null,
"e": 3262,
"s": 3162,
"text": "row col\n[1,] 3 1\n[2,] 5 1\n[3,] 3 4\n[4,] 4 4\n[5,] 5 5\n[6,] 5 6\n[7,] 4 8\n[8,] 7 8\n[9,] 9 8\n[10,] 5 10"
}
] |
Angular Material 7 - Sort Header | The <mat-sort-header> and matSort, an Angular Directives, are used to add sorting capability to a table header.
In this chapter, we will showcase the configuration required to show a Sort Header using Angular Material.
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSortModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatSortModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified HTML host file app.component.html.
<table matSort (matSortChange) = "sortFood($event)">
<tr>
<th mat-sort-header = "name">Dessert (100g)</th>
<th mat-sort-header = "calories">Calories</th>
<th mat-sort-header = "fat">Fat (g)</th>
<th mat-sort-header = "carbs">Carbs (g)</th>
<th mat-sort-header = "protein">Protein (g)</th>
</tr>
<tr *ngFor = "let food of sortedFood">
<td>{{food.name}}</td>
<td>{{food.calories}}</td>
<td>{{food.fat}}</td>
<td>{{food.carbs}}</td>
<td>{{food.protein}}</td>
</tr>
</table>
Following is the content of the modified ts file app.component.ts.
import {Component, Injectable} from '@angular/core';
import {Sort} from '@angular/material';
export interface Food {
calories: number;
carbs: number;
fat: number;
name: string;
protein: number;
}
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
foods: Food[] = [
{name: 'Yogurt', calories: 159, fat: 6, carbs: 24, protein: 4},
{name: 'Sandwich', calories: 237, fat: 9, carbs: 37, protein: 4},
{name: 'Eclairs', calories: 262, fat: 16, carbs: 24, protein: 6},
{name: 'Cupcakes', calories: 305, fat: 4, carbs: 67, protein: 4},
{name: 'Gingerbreads', calories: 356, fat: 16, carbs: 49, protein: 4},
];
sortedFood: Food[];
constructor() {
this.sortedFood = this.foods.slice();
}
sortFood(sort: Sort) {
const data = this.foods.slice();
if (!sort.active || sort.direction === '') {
this.sortedFood = data;
return;
}
this.sortedFood = data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
case 'name': return compare(a.name, b.name, isAsc);
case 'calories': return compare(a.calories, b.calories, isAsc);
case 'fat': return compare(a.fat, b.fat, isAsc);
case 'carbs': return compare(a.carbs, b.carbs, isAsc);
case 'protein': return compare(a.protein, b.protein, isAsc);
default: return 0;
}
});
}
}
function compare(a: number | string, b: number | string, isAsc: boolean) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
Verify the result.
Here, we've created a table. Added matSort and handles its matSortChange event.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2868,
"s": 2755,
"text": "The <mat-sort-header> and matSort, an Angular Directives, are used to add sorting capability to a table header."
},
{
"code": null,
"e": 2975,
"s": 2868,
"text": "In this chapter, we will showcase the configuration required to show a Sort Header using Angular Material."
},
{
"code": null,
"e": 3049,
"s": 2975,
"text": "Following is the content of the modified module descriptor app.module.ts."
},
{
"code": null,
"e": 3660,
"s": 3049,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {BrowserAnimationsModule} from '@angular/platform-browser/animations';\nimport {MatSortModule} from '@angular/material'\nimport {FormsModule, ReactiveFormsModule} from '@angular/forms';\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n MatSortModule,\n FormsModule,\n ReactiveFormsModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3736,
"s": 3660,
"text": "Following is the content of the modified HTML host file app.component.html."
},
{
"code": null,
"e": 4279,
"s": 3736,
"text": "<table matSort (matSortChange) = \"sortFood($event)\">\n <tr>\n <th mat-sort-header = \"name\">Dessert (100g)</th>\n <th mat-sort-header = \"calories\">Calories</th>\n <th mat-sort-header = \"fat\">Fat (g)</th>\n <th mat-sort-header = \"carbs\">Carbs (g)</th>\n <th mat-sort-header = \"protein\">Protein (g)</th>\n </tr>\n <tr *ngFor = \"let food of sortedFood\">\n <td>{{food.name}}</td>\n <td>{{food.calories}}</td>\n <td>{{food.fat}}</td>\n <td>{{food.carbs}}</td>\n <td>{{food.protein}}</td>\n </tr>\n</table>"
},
{
"code": null,
"e": 4346,
"s": 4279,
"text": "Following is the content of the modified ts file app.component.ts."
},
{
"code": null,
"e": 6008,
"s": 4346,
"text": "import {Component, Injectable} from '@angular/core';\nimport {Sort} from '@angular/material';\nexport interface Food {\n calories: number;\n carbs: number;\n fat: number;\n name: string;\n protein: number;\n}\n@Component({\n selector: 'app-root',\n templateUrl: 'app.component.html',\n styleUrls: ['app.component.css']\n})\nexport class AppComponent { \n foods: Food[] = [\n {name: 'Yogurt', calories: 159, fat: 6, carbs: 24, protein: 4},\n {name: 'Sandwich', calories: 237, fat: 9, carbs: 37, protein: 4},\n {name: 'Eclairs', calories: 262, fat: 16, carbs: 24, protein: 6},\n {name: 'Cupcakes', calories: 305, fat: 4, carbs: 67, protein: 4},\n {name: 'Gingerbreads', calories: 356, fat: 16, carbs: 49, protein: 4},\n ];\n sortedFood: Food[];\n constructor() {\n this.sortedFood = this.foods.slice();\n }\n sortFood(sort: Sort) {\n const data = this.foods.slice();\n if (!sort.active || sort.direction === '') {\n this.sortedFood = data;\n return;\n }\n this.sortedFood = data.sort((a, b) => {\n const isAsc = sort.direction === 'asc';\n switch (sort.active) {\n case 'name': return compare(a.name, b.name, isAsc);\n case 'calories': return compare(a.calories, b.calories, isAsc);\n case 'fat': return compare(a.fat, b.fat, isAsc);\n case 'carbs': return compare(a.carbs, b.carbs, isAsc);\n case 'protein': return compare(a.protein, b.protein, isAsc);\n default: return 0;\n } \n });\n }\n}\nfunction compare(a: number | string, b: number | string, isAsc: boolean) {\n return (a < b ? -1 : 1) * (isAsc ? 1 : -1);\n}"
},
{
"code": null,
"e": 6027,
"s": 6008,
"text": "Verify the result."
},
{
"code": null,
"e": 6107,
"s": 6027,
"text": "Here, we've created a table. Added matSort and handles its matSortChange event."
},
{
"code": null,
"e": 6142,
"s": 6107,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6156,
"s": 6142,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6191,
"s": 6156,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6205,
"s": 6191,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6240,
"s": 6205,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6260,
"s": 6240,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6295,
"s": 6260,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6312,
"s": 6295,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6345,
"s": 6312,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6357,
"s": 6345,
"text": " Senol Atac"
},
{
"code": null,
"e": 6392,
"s": 6357,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6404,
"s": 6392,
"text": " Senol Atac"
},
{
"code": null,
"e": 6411,
"s": 6404,
"text": " Print"
},
{
"code": null,
"e": 6422,
"s": 6411,
"text": " Add Notes"
}
] |
Difference between vi Editor and cat Command - GeeksforGeeks | 22 Sep, 2020
Both vi editor and cat command are used to input contents in a file.
1. vi Editor :vi editor stands for the visual editor which is an intelligent editing tool in UNIX Operating System used for reading, creating files, editing them, and more. It is the default editing tool in UNIX.
Command to open a particular file :
vi filename
It has three modes :
Command Mode : The vi editor always opens in this mode. It is where all the commands are accepted.Insert/Input Mode : The file is opened in the input mode and the contents of the file are written or edited here.Execution Mode : The execution mode is invoked by the ‘:’ command from the command mode. Then the commands are read into the command mode.
Command Mode : The vi editor always opens in this mode. It is where all the commands are accepted.
Insert/Input Mode : The file is opened in the input mode and the contents of the file are written or edited here.
Execution Mode : The execution mode is invoked by the ‘:’ command from the command mode. Then the commands are read into the command mode.
The way to access each mode from one another has been explained in the image below.
Way to access each mode from one another
2. cat Command :The cat command stands for concatenate. It is also used to create new files, read and update already existing files. They are also used for joining multiple files together or copying a file’s content to another one.
Examples of cat Command :
To create and add some content to a file.cat > newfile
This is a new file that is not empty.
cat > newfile
This is a new file that is not empty.
To read or display the contents of an existing file.cat newfile
cat newfile
To merge two files into a new one.cat file1 file2 >> file3There are a lot of other commands using cat. However, there are certain limitations to both of their usage.
cat file1 file2 >> file3
There are a lot of other commands using cat. However, there are certain limitations to both of their usage.
Difference between vi Editor and cat Command :
Difference Between
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Differences and Applications of List, Tuple, Set and Dictionary in Python
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
TCP Server-Client implementation in C | [
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n22 Sep, 2020"
},
{
"code": null,
"e": 24927,
"s": 24858,
"text": "Both vi editor and cat command are used to input contents in a file."
},
{
"code": null,
"e": 25140,
"s": 24927,
"text": "1. vi Editor :vi editor stands for the visual editor which is an intelligent editing tool in UNIX Operating System used for reading, creating files, editing them, and more. It is the default editing tool in UNIX."
},
{
"code": null,
"e": 25176,
"s": 25140,
"text": "Command to open a particular file :"
},
{
"code": null,
"e": 25188,
"s": 25176,
"text": "vi filename"
},
{
"code": null,
"e": 25209,
"s": 25188,
"text": "It has three modes :"
},
{
"code": null,
"e": 25559,
"s": 25209,
"text": "Command Mode : The vi editor always opens in this mode. It is where all the commands are accepted.Insert/Input Mode : The file is opened in the input mode and the contents of the file are written or edited here.Execution Mode : The execution mode is invoked by the ‘:’ command from the command mode. Then the commands are read into the command mode."
},
{
"code": null,
"e": 25658,
"s": 25559,
"text": "Command Mode : The vi editor always opens in this mode. It is where all the commands are accepted."
},
{
"code": null,
"e": 25772,
"s": 25658,
"text": "Insert/Input Mode : The file is opened in the input mode and the contents of the file are written or edited here."
},
{
"code": null,
"e": 25911,
"s": 25772,
"text": "Execution Mode : The execution mode is invoked by the ‘:’ command from the command mode. Then the commands are read into the command mode."
},
{
"code": null,
"e": 25995,
"s": 25911,
"text": "The way to access each mode from one another has been explained in the image below."
},
{
"code": null,
"e": 26036,
"s": 25995,
"text": "Way to access each mode from one another"
},
{
"code": null,
"e": 26268,
"s": 26036,
"text": "2. cat Command :The cat command stands for concatenate. It is also used to create new files, read and update already existing files. They are also used for joining multiple files together or copying a file’s content to another one."
},
{
"code": null,
"e": 26294,
"s": 26268,
"text": "Examples of cat Command :"
},
{
"code": null,
"e": 26387,
"s": 26294,
"text": "To create and add some content to a file.cat > newfile\nThis is a new file that is not empty."
},
{
"code": null,
"e": 26439,
"s": 26387,
"text": "cat > newfile\nThis is a new file that is not empty."
},
{
"code": null,
"e": 26503,
"s": 26439,
"text": "To read or display the contents of an existing file.cat newfile"
},
{
"code": null,
"e": 26515,
"s": 26503,
"text": "cat newfile"
},
{
"code": null,
"e": 26681,
"s": 26515,
"text": "To merge two files into a new one.cat file1 file2 >> file3There are a lot of other commands using cat. However, there are certain limitations to both of their usage."
},
{
"code": null,
"e": 26706,
"s": 26681,
"text": "cat file1 file2 >> file3"
},
{
"code": null,
"e": 26814,
"s": 26706,
"text": "There are a lot of other commands using cat. However, there are certain limitations to both of their usage."
},
{
"code": null,
"e": 26861,
"s": 26814,
"text": "Difference between vi Editor and cat Command :"
},
{
"code": null,
"e": 26880,
"s": 26861,
"text": "Difference Between"
},
{
"code": null,
"e": 26891,
"s": 26880,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26989,
"s": 26891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27050,
"s": 26989,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27118,
"s": 27050,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27173,
"s": 27118,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27231,
"s": 27173,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27305,
"s": 27231,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 27345,
"s": 27305,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 27385,
"s": 27345,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 27412,
"s": 27385,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 27447,
"s": 27412,
"text": "cut command in Linux with examples"
}
] |
Data Structures and Algorithms | Set 6 - GeeksforGeeks | 27 Mar, 2017
Following questions have been asked in GATE CS exam.
1. The usual Θ(n^2) implementation of Insertion Sort to sort an array uses linear search to identify the position where an element is to be inserted into the already sorted part of the array. If, instead, we use binary search to identify the position, the worst case running time will (GATE CS 2003)(a) remain Θ(n^2)(b) become Θ(n(log n)^2)(c) become Θ(n log n)(d) become Θ(n)
Answer (a)If we use binary search then there will be ⌈ Log2(n!) ⌉ comparisons in the worst case, which is Θ(n log n) ( If you want to know how ⌈ Log2(n!) ⌉ can be equal to Θ(n log n)), then see this for proof). But the algorithm as a whole will still have a running time of Θ(n^2) on average because of the series of swaps required for each insertion.
Reference:http://en.wikipedia.org/wiki/Insertion_sort
2. The tightest lower bound on the number of comparisons, in the worst case, for comparison-based sorting is of the order ofa) nb) n^2c) nlognd) n(log^2)n
Answer (c)The number of comparisons that a comparison sort algorithm requires increases in proportion to nlog(n), where n is the number of elements to sort. This bound is asymptotically tight:
Given a list of distinct numbers (we can assume this because this is a worst-case analysis), there are n factorial permutations exactly one of which is the list in sorted order. The sort algorithm must gain enough information from the comparisons to identify the correct permutations. If the algorithm always completes after at most f(n) steps, it cannot distinguish more than 2^f(n) cases because the keys are distinct and each comparison has only two possible outcomes. Therefore,
2^f(n) >= n!, or equivalently f(n) > Log2(n!).
References:http://en.wikipedia.org/wiki/Comparison_sorthttp://www.cs.cmu.edu/afs/cs.cmu.edu/academic/class/15451-s07/www/lecture_notes/lect0130.pdf
3. The problem 3-SAT and 2-SAT area) both in Pb) both NP completec) NP-complete and in P respectivelyd) undecidable and NP-complete respectively
Answer (c)The Boolean satisfiability problem (SAT) is a decision problem, whose instance is a Boolean expression written using only AND, OR, NOT, variables, and parentheses. The problem is: given the expression, is there some assignment of TRUE and FALSE values to the variables that will make the entire expression true? A formula of propositional logic is said to be satisfiable if logical values can be assigned to its variables in a way that makes the formula true.
3-SAT and 2-SAT are special cases of k-satisfiability (k-SAT) or simply satisfiability (SAT), when each clause contains exactly k = 3 and k = 2 literals respectively.
2-SAT is P while 3-SAT is NP Complete. (See this for explanation)
References:http://en.wikipedia.org/wiki/Boolean_satisfiability_problem
4. Consider the following graphAmong the following sequencesI) a b e g h fII) a b f e h gIII) a b f h g eIV) a f g h b eWhich are depth first traversals of the above graph? (GATE CS 2003)a) I, II and IV onlyb) I and IV onlyc) II, III and IV onlyd) I, III and IV only
Answer (d)
Please write comments if you find any of the above answers/explanations incorrect.
GATE-CS-2003
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Difference between Process and Thread
Semaphores in Process Synchronization
Computer Networks | Set 1
Computer Networks | Set 2
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Database Management Systems | Set 1 | [
{
"code": null,
"e": 24320,
"s": 24292,
"text": "\n27 Mar, 2017"
},
{
"code": null,
"e": 24373,
"s": 24320,
"text": "Following questions have been asked in GATE CS exam."
},
{
"code": null,
"e": 24750,
"s": 24373,
"text": "1. The usual Θ(n^2) implementation of Insertion Sort to sort an array uses linear search to identify the position where an element is to be inserted into the already sorted part of the array. If, instead, we use binary search to identify the position, the worst case running time will (GATE CS 2003)(a) remain Θ(n^2)(b) become Θ(n(log n)^2)(c) become Θ(n log n)(d) become Θ(n)"
},
{
"code": null,
"e": 25102,
"s": 24750,
"text": "Answer (a)If we use binary search then there will be ⌈ Log2(n!) ⌉ comparisons in the worst case, which is Θ(n log n) ( If you want to know how ⌈ Log2(n!) ⌉ can be equal to Θ(n log n)), then see this for proof). But the algorithm as a whole will still have a running time of Θ(n^2) on average because of the series of swaps required for each insertion."
},
{
"code": null,
"e": 25156,
"s": 25102,
"text": "Reference:http://en.wikipedia.org/wiki/Insertion_sort"
},
{
"code": null,
"e": 25311,
"s": 25156,
"text": "2. The tightest lower bound on the number of comparisons, in the worst case, for comparison-based sorting is of the order ofa) nb) n^2c) nlognd) n(log^2)n"
},
{
"code": null,
"e": 25504,
"s": 25311,
"text": "Answer (c)The number of comparisons that a comparison sort algorithm requires increases in proportion to nlog(n), where n is the number of elements to sort. This bound is asymptotically tight:"
},
{
"code": null,
"e": 25987,
"s": 25504,
"text": "Given a list of distinct numbers (we can assume this because this is a worst-case analysis), there are n factorial permutations exactly one of which is the list in sorted order. The sort algorithm must gain enough information from the comparisons to identify the correct permutations. If the algorithm always completes after at most f(n) steps, it cannot distinguish more than 2^f(n) cases because the keys are distinct and each comparison has only two possible outcomes. Therefore,"
},
{
"code": null,
"e": 26041,
"s": 25987,
"text": "\n 2^f(n) >= n!, or equivalently f(n) > Log2(n!). \n"
},
{
"code": null,
"e": 26189,
"s": 26041,
"text": "References:http://en.wikipedia.org/wiki/Comparison_sorthttp://www.cs.cmu.edu/afs/cs.cmu.edu/academic/class/15451-s07/www/lecture_notes/lect0130.pdf"
},
{
"code": null,
"e": 26334,
"s": 26189,
"text": "3. The problem 3-SAT and 2-SAT area) both in Pb) both NP completec) NP-complete and in P respectivelyd) undecidable and NP-complete respectively"
},
{
"code": null,
"e": 26804,
"s": 26334,
"text": "Answer (c)The Boolean satisfiability problem (SAT) is a decision problem, whose instance is a Boolean expression written using only AND, OR, NOT, variables, and parentheses. The problem is: given the expression, is there some assignment of TRUE and FALSE values to the variables that will make the entire expression true? A formula of propositional logic is said to be satisfiable if logical values can be assigned to its variables in a way that makes the formula true."
},
{
"code": null,
"e": 26971,
"s": 26804,
"text": "3-SAT and 2-SAT are special cases of k-satisfiability (k-SAT) or simply satisfiability (SAT), when each clause contains exactly k = 3 and k = 2 literals respectively."
},
{
"code": null,
"e": 27037,
"s": 26971,
"text": "2-SAT is P while 3-SAT is NP Complete. (See this for explanation)"
},
{
"code": null,
"e": 27108,
"s": 27037,
"text": "References:http://en.wikipedia.org/wiki/Boolean_satisfiability_problem"
},
{
"code": null,
"e": 27375,
"s": 27108,
"text": "4. Consider the following graphAmong the following sequencesI) a b e g h fII) a b f e h gIII) a b f h g eIV) a f g h b eWhich are depth first traversals of the above graph? (GATE CS 2003)a) I, II and IV onlyb) I and IV onlyc) II, III and IV onlyd) I, III and IV only"
},
{
"code": null,
"e": 27386,
"s": 27375,
"text": "Answer (d)"
},
{
"code": null,
"e": 27469,
"s": 27386,
"text": "Please write comments if you find any of the above answers/explanations incorrect."
},
{
"code": null,
"e": 27482,
"s": 27469,
"text": "GATE-CS-2003"
},
{
"code": null,
"e": 27500,
"s": 27482,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 27508,
"s": 27500,
"text": "GATE CS"
},
{
"code": null,
"e": 27512,
"s": 27508,
"text": "MCQ"
},
{
"code": null,
"e": 27610,
"s": 27512,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27659,
"s": 27610,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 27691,
"s": 27659,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27730,
"s": 27691,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 27768,
"s": 27730,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 27806,
"s": 27768,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 27832,
"s": 27806,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 27858,
"s": 27832,
"text": "Computer Networks | Set 2"
},
{
"code": null,
"e": 27905,
"s": 27858,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 27931,
"s": 27905,
"text": "Operating Systems | Set 1"
}
] |
HTML <dl> Tag | The dl element in HTML is used to define description list. In HTML5, the <dl> is used to define a description list, whereas the <dl> in HTML4 defined definition list.
Let us now see an example to implement the <dl> tag −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Sports</h2>
<dl>
<dt>Football</dt>
<dd>It is played by 250 million players in over 200 countries.</dd>
<dt>Cricket</dt>
<dd>It is a bat-and-ball game played between two teams of eleven players on a field.</dd>
<dt>Hockey</dt>
<dd>There are many types of hockey such as bandy, field hockey, and ice hockey.</dd>
<dt>Golf</dt>
<dd>It is a club-and-ball sport in which players use various clubs to hit balls into a series of holes on a course in as few strokes as possible.</dd>
</dl>
</body>
</html>
In the above example, we have set the <dl> to set the description list −
<dl>
<dt>Football</dt>
<dd>It is played by 250 million players in over 200 countries.</dd>
<dt>Cricket</dt>
<dd>It is a bat-and-ball game played between two teams of eleven players on a field.</dd>
<dt>Hockey</dt>
<dd>There are many types of hockey such as bandy, field hockey, and ice hockey.</dd>
<dt>Golf</dt>
<dd>It is a club-and-ball sport in which players use various clubs to hit balls into a series of holes on a course in as few strokes as possible.</dd>
</dl>
The <dt> element above defines a term in the definition list, whereas the <dd> also defines a term, but you can add links, images, line breaks inside the <dd>. | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "The dl element in HTML is used to define description list. In HTML5, the <dl> is used to define a description list, whereas the <dl> in HTML4 defined definition list."
},
{
"code": null,
"e": 1283,
"s": 1229,
"text": "Let us now see an example to implement the <dl> tag −"
},
{
"code": null,
"e": 1294,
"s": 1283,
"text": " Live Demo"
},
{
"code": null,
"e": 1862,
"s": 1294,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Sports</h2>\n<dl>\n <dt>Football</dt>\n <dd>It is played by 250 million players in over 200 countries.</dd>\n <dt>Cricket</dt>\n <dd>It is a bat-and-ball game played between two teams of eleven players on a field.</dd>\n <dt>Hockey</dt>\n <dd>There are many types of hockey such as bandy, field hockey, and ice hockey.</dd>\n <dt>Golf</dt>\n <dd>It is a club-and-ball sport in which players use various clubs to hit balls into a series of holes on a course in as few strokes as possible.</dd>\n</dl>\n</body>\n</html>"
},
{
"code": null,
"e": 1935,
"s": 1862,
"text": "In the above example, we have set the <dl> to set the description list −"
},
{
"code": null,
"e": 2441,
"s": 1935,
"text": "<dl>\n <dt>Football</dt>\n <dd>It is played by 250 million players in over 200 countries.</dd>\n <dt>Cricket</dt>\n <dd>It is a bat-and-ball game played between two teams of eleven players on a field.</dd>\n <dt>Hockey</dt>\n <dd>There are many types of hockey such as bandy, field hockey, and ice hockey.</dd>\n <dt>Golf</dt>\n <dd>It is a club-and-ball sport in which players use various clubs to hit balls into a series of holes on a course in as few strokes as possible.</dd>\n</dl>"
},
{
"code": null,
"e": 2601,
"s": 2441,
"text": "The <dt> element above defines a term in the definition list, whereas the <dd> also defines a term, but you can add links, images, line breaks inside the <dd>."
}
] |
SAP Web Dynpro - URL of an Application | In a Web Dynpro application, the URL is automatically generated. You can find the URL of an application in the Properties tab. The URL structure can be of two types −
SAP namespace −
SAP namespace −
<schema>://<host>.<domain>.<extension>:<port>/sap/bc/webdynpro/<namespace>/<application name>
Custom namespace −
<schema>://<host>.<domain>.<extension>:<port>/abc/klm/xyz/<namespace>/webdynpro/<application name>
<schema>://<host>.<domain>.<extension>:<port>/namespace>/webdynpro/<application name>
where,
<schema> − Defines the protocol to access application http/https
<host> − Defines the name of the application server
<domain><extension> − Defines several hosts under a common name
<port> − It can be omitted if the standard port 80 (http) or 443 (https) is used
You should specify Fully Qualified Domain Name (FQDN) in Web Dynpro application URL.
Application 1 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/myFirstApp/
Application 2 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/ mySecondApp/
To check fully qualified domain name, go to Web Dynpro explorer in the ABAP development environment use T-code − SE80 and select the Web Dynpro application from the navigation tree for your Web Dynpro component/interface and check the URL in the administration data. You also need to check the path details in the field URL. It should contain the full domain and host name.
Full Domain name should be used for the following reasons −
You need a domain to set cookies.
You should use FQDN for certificate and SSL protocol in https mode.
For portal integration, domain relation code is used.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2346,
"s": 2179,
"text": "In a Web Dynpro application, the URL is automatically generated. You can find the URL of an application in the Properties tab. The URL structure can be of two types −"
},
{
"code": null,
"e": 2362,
"s": 2346,
"text": "SAP namespace −"
},
{
"code": null,
"e": 2378,
"s": 2362,
"text": "SAP namespace −"
},
{
"code": null,
"e": 2473,
"s": 2378,
"text": "<schema>://<host>.<domain>.<extension>:<port>/sap/bc/webdynpro/<namespace>/<application name>\n"
},
{
"code": null,
"e": 2492,
"s": 2473,
"text": "Custom namespace −"
},
{
"code": null,
"e": 2678,
"s": 2492,
"text": "<schema>://<host>.<domain>.<extension>:<port>/abc/klm/xyz/<namespace>/webdynpro/<application name>\n<schema>://<host>.<domain>.<extension>:<port>/namespace>/webdynpro/<application name>\n"
},
{
"code": null,
"e": 2685,
"s": 2678,
"text": "where,"
},
{
"code": null,
"e": 2750,
"s": 2685,
"text": "<schema> − Defines the protocol to access application http/https"
},
{
"code": null,
"e": 2802,
"s": 2750,
"text": "<host> − Defines the name of the application server"
},
{
"code": null,
"e": 2866,
"s": 2802,
"text": "<domain><extension> − Defines several hosts under a common name"
},
{
"code": null,
"e": 2947,
"s": 2866,
"text": "<port> − It can be omitted if the standard port 80 (http) or 443 (https) is used"
},
{
"code": null,
"e": 3032,
"s": 2947,
"text": "You should specify Fully Qualified Domain Name (FQDN) in Web Dynpro application URL."
},
{
"code": null,
"e": 3104,
"s": 3032,
"text": "Application 1 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/myFirstApp/"
},
{
"code": null,
"e": 3178,
"s": 3104,
"text": "Application 2 http://xyz.sap.corp:1080/sap/bc/webdynpro/sap/ mySecondApp/"
},
{
"code": null,
"e": 3552,
"s": 3178,
"text": "To check fully qualified domain name, go to Web Dynpro explorer in the ABAP development environment use T-code − SE80 and select the Web Dynpro application from the navigation tree for your Web Dynpro component/interface and check the URL in the administration data. You also need to check the path details in the field URL. It should contain the full domain and host name."
},
{
"code": null,
"e": 3612,
"s": 3552,
"text": "Full Domain name should be used for the following reasons −"
},
{
"code": null,
"e": 3646,
"s": 3612,
"text": "You need a domain to set cookies."
},
{
"code": null,
"e": 3714,
"s": 3646,
"text": "You should use FQDN for certificate and SSL protocol in https mode."
},
{
"code": null,
"e": 3768,
"s": 3714,
"text": "For portal integration, domain relation code is used."
},
{
"code": null,
"e": 3801,
"s": 3768,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3815,
"s": 3801,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 3848,
"s": 3815,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3860,
"s": 3848,
"text": " Neha Gupta"
},
{
"code": null,
"e": 3895,
"s": 3860,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3910,
"s": 3895,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 3943,
"s": 3910,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3958,
"s": 3943,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 3993,
"s": 3958,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4005,
"s": 3993,
"text": " Neha Malik"
},
{
"code": null,
"e": 4040,
"s": 4005,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4052,
"s": 4040,
"text": " Neha Malik"
},
{
"code": null,
"e": 4059,
"s": 4052,
"text": " Print"
},
{
"code": null,
"e": 4070,
"s": 4059,
"text": " Add Notes"
}
] |
CICS - STARTBR | STARTBR is known as start browse. The STARTBR command gets the process started. It tells the CICS from where to start reading the file.
The FILE and RIDFLD parameters are the same as in a READ command.
The FILE and RIDFLD parameters are the same as in a READ command.
The options allowed are GTEQ and EQUAL.
The options allowed are GTEQ and EQUAL.
UPDATE is not allowed and file browsing is strictly a read-only operation.
UPDATE is not allowed and file browsing is strictly a read-only operation.
Following is the syntax of STARTBR command −
EXEC CICS STARTBR
FILE ('name')
RIDFLD (data-value)
KEYLENGTH(data-value)
GTEQ/EQUAL/GENERIC
END-EXEC.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2062,
"s": 1926,
"text": "STARTBR is known as start browse. The STARTBR command gets the process started. It tells the CICS from where to start reading the file."
},
{
"code": null,
"e": 2128,
"s": 2062,
"text": "The FILE and RIDFLD parameters are the same as in a READ command."
},
{
"code": null,
"e": 2194,
"s": 2128,
"text": "The FILE and RIDFLD parameters are the same as in a READ command."
},
{
"code": null,
"e": 2234,
"s": 2194,
"text": "The options allowed are GTEQ and EQUAL."
},
{
"code": null,
"e": 2274,
"s": 2234,
"text": "The options allowed are GTEQ and EQUAL."
},
{
"code": null,
"e": 2349,
"s": 2274,
"text": "UPDATE is not allowed and file browsing is strictly a read-only operation."
},
{
"code": null,
"e": 2424,
"s": 2349,
"text": "UPDATE is not allowed and file browsing is strictly a read-only operation."
},
{
"code": null,
"e": 2469,
"s": 2424,
"text": "Following is the syntax of STARTBR command −"
},
{
"code": null,
"e": 2585,
"s": 2469,
"text": "EXEC CICS STARTBR\n FILE ('name')\n RIDFLD (data-value)\n KEYLENGTH(data-value)\n GTEQ/EQUAL/GENERIC\nEND-EXEC.\n"
},
{
"code": null,
"e": 2592,
"s": 2585,
"text": " Print"
},
{
"code": null,
"e": 2603,
"s": 2592,
"text": " Add Notes"
}
] |
Creating custom Loss functions using TensorFlow 2 | by Arjun Sarkar | Towards Data Science | A neural network learns to map a set of inputs to a set of outputs from training data. It does so by using some form of optimization algorithm such as gradient descent, stochastic gradient descent, AdaGrad, AdaDelta or some recent algorithms such as Adam, Nadam or RMSProp. The ‘gradient’ in gradient descent refers to error gradient. After each iteration the network compares its predicted output to the real outputs, and then calculates the ‘error’. Typically, with neural networks, we seek to minimize the error. As such, the objective function used to minimize the error is often referred to as a cost function or a loss function and the value calculated by the ‘loss function’ is referred to as simply ‘loss’. Typical loss functions used in various problems –
a. Mean Squared Error
b. Mean Squared Logarithmic Error
c. Binary Crossentropy
d. Categorical Crossentropy
e. Sparse Categorical Crossentropy
In Tensorflow, these loss functions are already included, and we can just call them as shown below.
Loss function as a string
Loss function as a string
model.compile (loss = ‘binary_crossentropy’, optimizer = ‘adam’, metrics = [‘accuracy’])
or,
2. Loss function as an object
from tensorflow.keras.losses import mean_squared_error
model.compile(loss = mean_squared_error, optimizer=’sgd’)
The advantage of calling a loss function as an object is that we can pass parameters alongside the loss function, such as threshold.
from tensorflow.keras.losses import mean_squared_error
model.compile (loss=mean_squared_error(param=value), optimizer = ‘sgd’)
For creating loss using function, we need to first name the loss function, and it will accept two parameters, y_true (true label/output) and y_pred (predicted label/output).
def loss_function(y_true, y_pred):
***some calculation***
return loss
Loss function name — my_rmse
Aim is to return the root mean square error between target (y_true) and prediction (y_pred).
Formula of RMSE:
error: the difference between the true label and predicted label.
sqr_error: the square of the error.
mean_sqr_error: the mean of the square of the error
sqrt_mean_sqr_error: the square root of the mean of the square of the error (the root mean squared error).
import tensorflow as tfimport numpy as npfrom tensorflow import kerasfrom tensorflow.keras import backend as K#defining the loss functiondef my_rmse(y_true, y_pred): #difference between true label and predicted label error = y_true-y_pred #square of the error sqr_error = K.square(error) #mean of the square of the error mean_sqr_error = K.mean(sqr_error) #square root of the mean of the square of the error sqrt_mean_sqr_error = K.sqrt(mean_sqr_error) #return the error return sqrt_mean_sqr_error#applying the loss functionmodel.compile (optimizer = 'sgd', loss = my_rmse)
Formula of Huber Loss:
Here,
δ is the threshold,
a is the error ( we will calculate a , difference between label and prediction )
So, when |a| ≤δ, loss = 1/2*(a)2
and when, |a|>δ, loss = δ(|a| — (1/2)*δ)
Code:
import tensorflow as tfdef my_huber_loss(y_true, y_pred): threshold = 1 error = y_true - y_pred is_small_error = tf.abs(error) <= threshold small_error_loss = tf.square(error) / 2 big_error_loss = threshold * (tf.abs(error) - (0.5 * threshold))return tf.where(is_small_error, small_error_loss, big_error_loss)
Explanation:
First we define a function — my huber loss, which takes in y_true and y_pred
Next we set the threshold = 1.
Next we calculate the error a = y_true-y_pred
Next we check if the absolute value of the error is less than or equal to the threshold. is_small_error returns a boolean (True or False).
We know that, when, |a| ≤δ, loss = 1/2*(a)2, so we calculate the small_error_loss as the square of the error divided by 2.
Else, when, |a| >δ, then loss is equal to δ(|a| — (1/2)*δ). We calculate this in big_error_loss.
Finally, in the return statement, we first check if is_small_error is true or false, if it is true, the function returns the small_error_loss, or else it returns the big_error_loss. This is done using tf.where.
We can then compile the model using the code below,
model.compile(optimizer='sgd', loss=my_huber_loss)
In the previous code, we always use threshold as 1.
But what if, we want to tune the hyperparameter (threshold) and add a new threshold value during compilation. Then we have to use fuction wrapping, that is, wrapping the loss function around another external function. We need a wrapper function as any loss functions can accept only y_true and y_pred values by default, and we can not add any other parameters to the original loss function.
This is what the wrapper function code looks like:
import tensorflow as tf#wrapper function which accepts the threshold parameterdef my_huber_loss_with_threshold(threshold): def my_huber_loss(y_true, y_pred): error = y_true - y_pred is_small_error = tf.abs(error) <= threshold small_error_loss = tf.square(error) / 2 big_error_loss = threshold * (tf.abs(error) - (0.5 * threshold)) return tf.where(is_small_error, small_error_loss, big_error_loss) return my_huber_loss
In this case, the threshold value is not hardcoded. Rather we can pass the threshold value during model compilation.
model.compile(optimizer='sgd', loss=my_huber_loss_with_threshold(threshold=1.5))
import tensorflow as tffrom tensorflow.keras.losses import Lossclass MyHuberLoss(Loss): #inherit parent class #class attribute threshold = 1 #initialize instance attributes def __init__(self, threshold): super().__init__() self.threshold = threshold #compute loss def call(self, y_true, y_pred): error = y_true - y_pred is_small_error = tf.abs(error) <= self.threshold small_error_loss = tf.square(error) / 2 big_error_loss = self.threshold * (tf.abs(error) - (0.5 * self.threshold)) return tf.where(is_small_error, small_error_loss, big_error_loss)
MyHuberLoss is the class name. After the class name, we inherit the parent class ‘Loss’ from tensorflow.keras.losses. So MyHuberLoss inherits as Loss. This allows us to use MyHuberLoss as a loss function.
__init__ initialises the object from the class.
call function that gets executed when an object is instantiated from the class
The init function gets the threshold and the call function gets the y_true and y_pred parameters that we sell previously. So we will declare threshold as a class variable, which allows us to give it an initial value.
Within __init__ function we set threshold to self.threshold.
In call function, all threshold class variable will then be referred by self.threshold.
Here is how we can use this loss function in model.compile.
model.compile(optimizer='sgd', loss=MyHuberLoss(threshold=1.9))
Siamese networks compare if two images are similar or not. Contrastive loss is the loss function used in siamese networks.
In the formula above,
Y_true is the tensor of details about image similarities. They are one if the images are similar and they are zero if they’re not.
D is the tensor of Euclidean distances between the pairs of images.
Margin is a constant that we can use to enforce a minimum distance between them in order to consider them similar or different.
If Y_true =1, the first part of the equation becomes D2, and the second part becomes zero. So, the D2 term has more weight when Y_true is close to 1.
If Y_true = 0, then the first part of the equation becomes zero, and the second part yields some result. This gives much more weight to the max term and less weight to the D squared term, so the max term dominates the calculation of the loss.
def contrastive_loss_with_margin(margin): def contrastive_loss(y_true, y_pred): square_pred = K.square(y_pred) margin_square = K.square(K.maximum(margin - y_pred, 0)) return K.mean(y_true * square_pred + (1 - y_true) * margin_square) return contrastive_loss
Any loss functions not available in Tensorflow can be created using functions, wrapper functions or by using classes in a similar way. | [
{
"code": null,
"e": 937,
"s": 172,
"text": "A neural network learns to map a set of inputs to a set of outputs from training data. It does so by using some form of optimization algorithm such as gradient descent, stochastic gradient descent, AdaGrad, AdaDelta or some recent algorithms such as Adam, Nadam or RMSProp. The ‘gradient’ in gradient descent refers to error gradient. After each iteration the network compares its predicted output to the real outputs, and then calculates the ‘error’. Typically, with neural networks, we seek to minimize the error. As such, the objective function used to minimize the error is often referred to as a cost function or a loss function and the value calculated by the ‘loss function’ is referred to as simply ‘loss’. Typical loss functions used in various problems –"
},
{
"code": null,
"e": 959,
"s": 937,
"text": "a. Mean Squared Error"
},
{
"code": null,
"e": 993,
"s": 959,
"text": "b. Mean Squared Logarithmic Error"
},
{
"code": null,
"e": 1016,
"s": 993,
"text": "c. Binary Crossentropy"
},
{
"code": null,
"e": 1044,
"s": 1016,
"text": "d. Categorical Crossentropy"
},
{
"code": null,
"e": 1079,
"s": 1044,
"text": "e. Sparse Categorical Crossentropy"
},
{
"code": null,
"e": 1179,
"s": 1079,
"text": "In Tensorflow, these loss functions are already included, and we can just call them as shown below."
},
{
"code": null,
"e": 1205,
"s": 1179,
"text": "Loss function as a string"
},
{
"code": null,
"e": 1231,
"s": 1205,
"text": "Loss function as a string"
},
{
"code": null,
"e": 1320,
"s": 1231,
"text": "model.compile (loss = ‘binary_crossentropy’, optimizer = ‘adam’, metrics = [‘accuracy’])"
},
{
"code": null,
"e": 1324,
"s": 1320,
"text": "or,"
},
{
"code": null,
"e": 1354,
"s": 1324,
"text": "2. Loss function as an object"
},
{
"code": null,
"e": 1409,
"s": 1354,
"text": "from tensorflow.keras.losses import mean_squared_error"
},
{
"code": null,
"e": 1467,
"s": 1409,
"text": "model.compile(loss = mean_squared_error, optimizer=’sgd’)"
},
{
"code": null,
"e": 1600,
"s": 1467,
"text": "The advantage of calling a loss function as an object is that we can pass parameters alongside the loss function, such as threshold."
},
{
"code": null,
"e": 1655,
"s": 1600,
"text": "from tensorflow.keras.losses import mean_squared_error"
},
{
"code": null,
"e": 1727,
"s": 1655,
"text": "model.compile (loss=mean_squared_error(param=value), optimizer = ‘sgd’)"
},
{
"code": null,
"e": 1901,
"s": 1727,
"text": "For creating loss using function, we need to first name the loss function, and it will accept two parameters, y_true (true label/output) and y_pred (predicted label/output)."
},
{
"code": null,
"e": 1936,
"s": 1901,
"text": "def loss_function(y_true, y_pred):"
},
{
"code": null,
"e": 1959,
"s": 1936,
"text": "***some calculation***"
},
{
"code": null,
"e": 1971,
"s": 1959,
"text": "return loss"
},
{
"code": null,
"e": 2000,
"s": 1971,
"text": "Loss function name — my_rmse"
},
{
"code": null,
"e": 2093,
"s": 2000,
"text": "Aim is to return the root mean square error between target (y_true) and prediction (y_pred)."
},
{
"code": null,
"e": 2110,
"s": 2093,
"text": "Formula of RMSE:"
},
{
"code": null,
"e": 2176,
"s": 2110,
"text": "error: the difference between the true label and predicted label."
},
{
"code": null,
"e": 2212,
"s": 2176,
"text": "sqr_error: the square of the error."
},
{
"code": null,
"e": 2264,
"s": 2212,
"text": "mean_sqr_error: the mean of the square of the error"
},
{
"code": null,
"e": 2371,
"s": 2264,
"text": "sqrt_mean_sqr_error: the square root of the mean of the square of the error (the root mean squared error)."
},
{
"code": null,
"e": 2979,
"s": 2371,
"text": "import tensorflow as tfimport numpy as npfrom tensorflow import kerasfrom tensorflow.keras import backend as K#defining the loss functiondef my_rmse(y_true, y_pred): #difference between true label and predicted label error = y_true-y_pred #square of the error sqr_error = K.square(error) #mean of the square of the error mean_sqr_error = K.mean(sqr_error) #square root of the mean of the square of the error sqrt_mean_sqr_error = K.sqrt(mean_sqr_error) #return the error return sqrt_mean_sqr_error#applying the loss functionmodel.compile (optimizer = 'sgd', loss = my_rmse)"
},
{
"code": null,
"e": 3002,
"s": 2979,
"text": "Formula of Huber Loss:"
},
{
"code": null,
"e": 3008,
"s": 3002,
"text": "Here,"
},
{
"code": null,
"e": 3028,
"s": 3008,
"text": "δ is the threshold,"
},
{
"code": null,
"e": 3109,
"s": 3028,
"text": "a is the error ( we will calculate a , difference between label and prediction )"
},
{
"code": null,
"e": 3142,
"s": 3109,
"text": "So, when |a| ≤δ, loss = 1/2*(a)2"
},
{
"code": null,
"e": 3183,
"s": 3142,
"text": "and when, |a|>δ, loss = δ(|a| — (1/2)*δ)"
},
{
"code": null,
"e": 3189,
"s": 3183,
"text": "Code:"
},
{
"code": null,
"e": 3539,
"s": 3189,
"text": "import tensorflow as tfdef my_huber_loss(y_true, y_pred): threshold = 1 error = y_true - y_pred is_small_error = tf.abs(error) <= threshold small_error_loss = tf.square(error) / 2 big_error_loss = threshold * (tf.abs(error) - (0.5 * threshold))return tf.where(is_small_error, small_error_loss, big_error_loss)"
},
{
"code": null,
"e": 3552,
"s": 3539,
"text": "Explanation:"
},
{
"code": null,
"e": 3629,
"s": 3552,
"text": "First we define a function — my huber loss, which takes in y_true and y_pred"
},
{
"code": null,
"e": 3660,
"s": 3629,
"text": "Next we set the threshold = 1."
},
{
"code": null,
"e": 3706,
"s": 3660,
"text": "Next we calculate the error a = y_true-y_pred"
},
{
"code": null,
"e": 3845,
"s": 3706,
"text": "Next we check if the absolute value of the error is less than or equal to the threshold. is_small_error returns a boolean (True or False)."
},
{
"code": null,
"e": 3968,
"s": 3845,
"text": "We know that, when, |a| ≤δ, loss = 1/2*(a)2, so we calculate the small_error_loss as the square of the error divided by 2."
},
{
"code": null,
"e": 4065,
"s": 3968,
"text": "Else, when, |a| >δ, then loss is equal to δ(|a| — (1/2)*δ). We calculate this in big_error_loss."
},
{
"code": null,
"e": 4276,
"s": 4065,
"text": "Finally, in the return statement, we first check if is_small_error is true or false, if it is true, the function returns the small_error_loss, or else it returns the big_error_loss. This is done using tf.where."
},
{
"code": null,
"e": 4328,
"s": 4276,
"text": "We can then compile the model using the code below,"
},
{
"code": null,
"e": 4379,
"s": 4328,
"text": "model.compile(optimizer='sgd', loss=my_huber_loss)"
},
{
"code": null,
"e": 4431,
"s": 4379,
"text": "In the previous code, we always use threshold as 1."
},
{
"code": null,
"e": 4822,
"s": 4431,
"text": "But what if, we want to tune the hyperparameter (threshold) and add a new threshold value during compilation. Then we have to use fuction wrapping, that is, wrapping the loss function around another external function. We need a wrapper function as any loss functions can accept only y_true and y_pred values by default, and we can not add any other parameters to the original loss function."
},
{
"code": null,
"e": 4873,
"s": 4822,
"text": "This is what the wrapper function code looks like:"
},
{
"code": null,
"e": 5346,
"s": 4873,
"text": "import tensorflow as tf#wrapper function which accepts the threshold parameterdef my_huber_loss_with_threshold(threshold): def my_huber_loss(y_true, y_pred): error = y_true - y_pred is_small_error = tf.abs(error) <= threshold small_error_loss = tf.square(error) / 2 big_error_loss = threshold * (tf.abs(error) - (0.5 * threshold)) return tf.where(is_small_error, small_error_loss, big_error_loss) return my_huber_loss"
},
{
"code": null,
"e": 5463,
"s": 5346,
"text": "In this case, the threshold value is not hardcoded. Rather we can pass the threshold value during model compilation."
},
{
"code": null,
"e": 5544,
"s": 5463,
"text": "model.compile(optimizer='sgd', loss=my_huber_loss_with_threshold(threshold=1.5))"
},
{
"code": null,
"e": 6165,
"s": 5544,
"text": "import tensorflow as tffrom tensorflow.keras.losses import Lossclass MyHuberLoss(Loss): #inherit parent class #class attribute threshold = 1 #initialize instance attributes def __init__(self, threshold): super().__init__() self.threshold = threshold #compute loss def call(self, y_true, y_pred): error = y_true - y_pred is_small_error = tf.abs(error) <= self.threshold small_error_loss = tf.square(error) / 2 big_error_loss = self.threshold * (tf.abs(error) - (0.5 * self.threshold)) return tf.where(is_small_error, small_error_loss, big_error_loss)"
},
{
"code": null,
"e": 6370,
"s": 6165,
"text": "MyHuberLoss is the class name. After the class name, we inherit the parent class ‘Loss’ from tensorflow.keras.losses. So MyHuberLoss inherits as Loss. This allows us to use MyHuberLoss as a loss function."
},
{
"code": null,
"e": 6418,
"s": 6370,
"text": "__init__ initialises the object from the class."
},
{
"code": null,
"e": 6497,
"s": 6418,
"text": "call function that gets executed when an object is instantiated from the class"
},
{
"code": null,
"e": 6714,
"s": 6497,
"text": "The init function gets the threshold and the call function gets the y_true and y_pred parameters that we sell previously. So we will declare threshold as a class variable, which allows us to give it an initial value."
},
{
"code": null,
"e": 6775,
"s": 6714,
"text": "Within __init__ function we set threshold to self.threshold."
},
{
"code": null,
"e": 6863,
"s": 6775,
"text": "In call function, all threshold class variable will then be referred by self.threshold."
},
{
"code": null,
"e": 6923,
"s": 6863,
"text": "Here is how we can use this loss function in model.compile."
},
{
"code": null,
"e": 6987,
"s": 6923,
"text": "model.compile(optimizer='sgd', loss=MyHuberLoss(threshold=1.9))"
},
{
"code": null,
"e": 7110,
"s": 6987,
"text": "Siamese networks compare if two images are similar or not. Contrastive loss is the loss function used in siamese networks."
},
{
"code": null,
"e": 7132,
"s": 7110,
"text": "In the formula above,"
},
{
"code": null,
"e": 7263,
"s": 7132,
"text": "Y_true is the tensor of details about image similarities. They are one if the images are similar and they are zero if they’re not."
},
{
"code": null,
"e": 7331,
"s": 7263,
"text": "D is the tensor of Euclidean distances between the pairs of images."
},
{
"code": null,
"e": 7459,
"s": 7331,
"text": "Margin is a constant that we can use to enforce a minimum distance between them in order to consider them similar or different."
},
{
"code": null,
"e": 7609,
"s": 7459,
"text": "If Y_true =1, the first part of the equation becomes D2, and the second part becomes zero. So, the D2 term has more weight when Y_true is close to 1."
},
{
"code": null,
"e": 7852,
"s": 7609,
"text": "If Y_true = 0, then the first part of the equation becomes zero, and the second part yields some result. This gives much more weight to the max term and less weight to the D squared term, so the max term dominates the calculation of the loss."
},
{
"code": null,
"e": 8145,
"s": 7852,
"text": "def contrastive_loss_with_margin(margin): def contrastive_loss(y_true, y_pred): square_pred = K.square(y_pred) margin_square = K.square(K.maximum(margin - y_pred, 0)) return K.mean(y_true * square_pred + (1 - y_true) * margin_square) return contrastive_loss"
}
] |
HTML5 - email | It accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in [email protected] format.
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Enter email : <input type = "email" name = "newinput" />
<input type = "submit" value = "submit" />
</form>
</body>
</html>
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": 2814,
"s": 2608,
"text": "It accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in [email protected] format."
},
{
"code": null,
"e": 3059,
"s": 2814,
"text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Enter email : <input type = \"email\" name = \"newinput\" />\n <input type = \"submit\" value = \"submit\" />\n </form>\n\n </body>\n</html>"
},
{
"code": null,
"e": 3092,
"s": 3059,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3106,
"s": 3092,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3141,
"s": 3106,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3155,
"s": 3141,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3190,
"s": 3155,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3207,
"s": 3190,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3242,
"s": 3207,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3273,
"s": 3242,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3306,
"s": 3273,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3337,
"s": 3306,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3372,
"s": 3337,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3403,
"s": 3372,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3410,
"s": 3403,
"text": " Print"
},
{
"code": null,
"e": 3421,
"s": 3410,
"text": " Add Notes"
}
] |
Assembly - SCAS Instruction | The SCAS instruction is used for searching a particular character or set of characters in a string. The data item to be searched should be in AL (for SCASB), AX (for SCASW) or EAX (for SCASD) registers. The string to be searched should be in memory and pointed by the ES:DI (or EDI) register.
Look at the following program to understand the concept −
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov ecx,len
mov edi,my_string
mov al , 'e'
cld
repne scasb
je found ; when found
; If not not then the following code
mov eax,4
mov ebx,1
mov ecx,msg_notfound
mov edx,len_notfound
int 80h
jmp exit
found:
mov eax,4
mov ebx,1
mov ecx,msg_found
mov edx,len_found
int 80h
exit:
mov eax,1
mov ebx,0
int 80h
section .data
my_string db 'hello world', 0
len equ $-my_string
msg_found db 'found!', 0xa
len_found equ $-msg_found
msg_notfound db 'not found!'
len_notfound equ $-msg_notfound
When the above code is compiled and executed, it produces the following result −
found!
46 Lectures
2 hours
Frahaan Hussain
23 Lectures
12 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2378,
"s": 2085,
"text": "The SCAS instruction is used for searching a particular character or set of characters in a string. The data item to be searched should be in AL (for SCASB), AX (for SCASW) or EAX (for SCASD) registers. The string to be searched should be in memory and pointed by the ES:DI (or EDI) register."
},
{
"code": null,
"e": 2436,
"s": 2378,
"text": "Look at the following program to understand the concept −"
},
{
"code": null,
"e": 3116,
"s": 2436,
"text": "section .text\n global _start ;must be declared for using gcc\n\t\n_start:\t ;tell linker entry point\n\n mov ecx,len\n mov edi,my_string\n mov al , 'e'\n cld\n repne scasb\n je found ; when found\n ; If not not then the following code\n\t\n mov eax,4\n mov ebx,1\n mov ecx,msg_notfound\n mov edx,len_notfound\n int 80h\n jmp exit\n\t\nfound:\n mov eax,4\n mov ebx,1\n mov ecx,msg_found\n mov edx,len_found\n int 80h\n\t\nexit:\n mov eax,1\n mov ebx,0\n int 80h\n\t\nsection .data\nmy_string db 'hello world', 0\nlen equ $-my_string \n\nmsg_found db 'found!', 0xa\nlen_found equ $-msg_found\n\nmsg_notfound db 'not found!'\nlen_notfound equ $-msg_notfound "
},
{
"code": null,
"e": 3197,
"s": 3116,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3205,
"s": 3197,
"text": "found!\n"
},
{
"code": null,
"e": 3238,
"s": 3205,
"text": "\n 46 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3255,
"s": 3238,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3289,
"s": 3255,
"text": "\n 23 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3297,
"s": 3289,
"text": " Uplatz"
},
{
"code": null,
"e": 3304,
"s": 3297,
"text": " Print"
},
{
"code": null,
"e": 3315,
"s": 3304,
"text": " Add Notes"
}
] |
Writing Google Sheets Data to MySQL using Python | by Nathan Rasmussen | Towards Data Science | In data jobs, we often use different methods of writing and analyzing data. Google sheets is a great way to collaboratively enter and share data. For larger datasets, Google sheets becomes painfully slow to work with, and one way around that is to create a new worksheet when there are too many rows. One project my team is working on creates 3000 rows a week, which isn’t much data by most standards, but it gets bogged down after a few weeks. Team members started archiving worksheets, which made it very difficult to do any aggregation on the data. I decided it was a better idea to write all our data to a MySQL table, which also allows other teams to join our data to other tables they are working with. I will walk you through the process of doing this using Python. For this project, I will be using Jupyter Notebook, Python 3.7.1, and MySQL Workbench 8.0 on a Windows machine.
I created a small dataset for this project using Google sheets. I included two worksheets, the first looks like:
Notice that I have intentionally left two cells blank in Column 2. This will be for an example later. The second worksheet (a second tab at the bottom) looks like:
The first thing we need to do is access the Google developers console using this link. Create a new project by clicking on the “CREATE PROJECT” link at the top of the page:
Name the project something relevant, as shown below.
Next, we need to create a service account for the project. Click on the navigation menu at the top left of the page (3 horizontal lines, often called a hamburger), and select “Service Accounts”:
You will need to select your project from the top of the page (a) and then hit “CREATE SERVICE ACCOUNT” (b).
Give the service account a meaningful name and click “CREATE”. Next we will set the service account permissions role to owner and click “CONTINUE”. On the next page we will skip the “grant users access to this service account” section, and move on to the “Create key” section below. This will open up a side bar that allows us to select a key type. Select “JSON” and hit “CREATE”. This will save the JSON file to your computer, and we will be using this file to grab some information out of.
Open the JSON file using something like Notepad++. Find the line which contains “Client email”, and copy the entire email address (between the quotes) to your clipboard. Next, go back to your Google sheet which contains the data you want to write to a MySQL table. Click on the green button labeled “Share” in the upper right of the spreadsheet. Paste the email address from the JSON file into the field and click “Send”. This will allow our Python program to access this Google sheet.
Now that everything is set up, we can move on to Python! For this tutorial, I am using Jupyter Notebook and Python 3.7.1. If you do not have Python installed on your machine, you will need to do so. Jupyter Notebook comes with Anaconda, which is a great package for Python. You can launch Jupyter Notebook by typing into the search bar (in Windows, on the taskbar) “Jupyter Notebook”, or you can launch the Anaconda prompt, and once the prompt is open, type “Jupyter Notebook” without the quotes, but we will need the Anaconda prompt later so I suggest using the first method described.
Jupyter Notebook will launch in your browser. You will be directed to your working directory. You can navigate to a different folder, but for now we will create a new notebook by clicking “New” in the upper right of the page and selecting a Python 3 notebook:
Let’s rename the notebook to “GoogleSheetsToMySQL” by clicking on the notebook name (Untitled) at the top of the page. Next, we need to move the JSON file we downloaded to our working directory. I believe the default directory is under “C://users//your_username”.
Before we can start coding, we will need to install a few modules. To install the modules we need, open the Anaconda prompt (you can find this in the Windows search bar on the taskbar). In the Anaconda prompt, you will need to install the following modules. Use pip by typing the following commands and hitting enter after each:
pip install gspreadpip install oauth2clientpip install mysql-connector
pip install gspread
pip install oauth2client
pip install mysql-connector
I have these already installed, as shown by the output of the command prompt (when attempting to install gspread):
Since we will be accessing a MySQL database, it is important not to expose our login credentials in our code. We will create a Python file (.py) and store these credentials there. We can then import them into our Jupyter Notebook script easily. The quickest way to create your .py file is with Notepad++. I used PyCharm for this, but use whichever IDE you prefer. Open your IDE and create a file called “MySQLCredentials.py”. In this file, we just need to type 4 lines and save it to our working directory. We need:
user = (your username)password = (your password)host = (hostname)database = (database schema you will be using)
Save the file and drop it into your working directory.
Now, back to your notebook. We need to import the modules we will be using by entering into our first cell the following:
# import librariesimport gspreadimport MySQLCredentials as mcimport mysql.connectorfrom oauth2client.service_account import ServiceAccountCredentials
Run the cell and if you don’t get any errors, great! Next we need to initialize some variables to use with gspread:
# initialize variables for gspreadscope = [‘https://spreadsheets.google.com/feeds',‘https://www.googleapis.com/auth/drive']creds = ServiceAccountCredentials.from_json_keyfile_name(‘GoogleSheetsToMySQL.json’, scope)client = gspread.authorize(creds)
If you named your JSON file something different, just make sure the name is correct in the code above. Now we need to define a method which will pull data from the Google sheet:
# define method to pull data from spreadsheetdef GetSpreadsheetData(sheetName, worksheetIndex): sheet = client.open(sheetName).get_worksheet(worksheetIndex) return sheet.get_all_values()[1:]
We are defining a method with two parameters. We need to tell it what sheet name we are referencing, and the worksheet index. The worksheet index refers to which sheet tab we are referencing. The first tab has an index of 0, the second tab has an index of 1, and so on. We won’t need these values until we call the method, so we will get back to that shortly. The return type for this method is a list, and it will return all values on that sheet. We then slice the list using [1:] which will remove the first element of the list. Since the Google sheet has a header with column names, this will drop that so we only pull the data from the sheet.
Before we move on, let’s check that this method can grab data from our sheet.
In a new cell in the notebook, enter
data = GetSpreadsheetData(‘GoogleSheetData’, 0)
You might get an error saying you need to enable the Drive API. It will provide a link which you can click on to enable the Drive API. Now rerun the cell and make sure you don’t get any errors. I had to run it a few times to enable 2 separate APIs and had to wait a minute before it ran without giving me an error. You should not need to do this again. OK, now check that you have the data you expect. You can check the first row of the list, as well as the length of the list (in this case, how many rows of data):
print(data[0])print(len(data))
which should return
[‘1’, ‘a’, ‘2019–01–01 1:00:00’]10
Now we need to set up a method to write this data to MySQL. Using a try-except-finally block will be useful here. There are several blocks of comments, indicated by having # in front of them, which are only for clarification:
# define method to write list of data to MySQL tabledef WriteToMySQLTable(sql_data, tableName):# we are using a try/except block (also called a try/catch block in other languages) which is good for error handling. It will “try” to execute anything in the “try” block, and if there is an error, it will report the error in the “except” block. Regardless of any errors, the “finally” block will always be executed. try:# Here we include the connection credentials for MySQL. We create a connection object that we pass the credentials to, and notice that we can specify the database which is ‘sys’ in the MySQLCredentials.py file because I’m using since I’m using the default database in MySQL Workbench 8.0. connection = mysql.connector.connect( user = mc.user, password = mc.password, host = mc.host, database = mc.database )# This command will drop the table, and we could just have the table name hardcoded into the string, but instead I am using the name of the table passed into the method. {} is a placeholder for what we want to pass into this string, and using .format(blah) we can pass the string name from the variable passed into the method here. sql_drop = “ DROP TABLE IF EXISTS {} “.format(tableName)# Now we will create the table, and the triple quotes are used so that when we go to the next line of code, we remain in a string. Otherwise it will terminate the string at the end of the line, and we want ALL of this to be one giant string. When injecting data into VALUES, we use the placeholder %s for each column of data we have. sql_create_table = “””CREATE TABLE {}( Column1 INT(11), Column2 VARCHAR(30), Column3 DATETIME, PRIMARY KEY (Column1) )”””.format(tableName) sql_insert_statement = “””INSERT INTO {}( Column1, Column2, Column3 ) VALUES ( %s,%s,%s )”””.format(tableName)# Here we create a cursor, which we will use to execute the MySQL statements above. After each statement is executed, a message will be printed to the console if the execution was successful. cursor = connection.cursor() cursor.execute(sql_drop) print(‘Table {} has been dropped’.format(tableName)) cursor.execute(sql_create_table) print(‘Table {} has been created’.format(tableName))# We need to write each row of data to the table, so we use a for loop that will insert each row of data one at a time for i in sql_data: cursor.execute(sql_insert_statement, i)# Now we execute the commit statement, and print to the console that the table was updated successfully connection.commit() print(“Table {} successfully updated.”.format(tableName))# Errors are handled in the except block, and we will get the information printed to the console if there is an error except mysql.connector.Error as error : connection.rollback() print(“Error: {}. Table {} not updated!”.format(error, tableName))# We need to close the cursor and the connection, and this needs to be done regardless of what happened above. finally: cursor.execute(‘SELECT COUNT(*) FROM {}’.format(tableName)) rowCount = cursor.fetchone()[0] print(tableName, ‘row count:’, rowCount) if connection.is_connected(): cursor.close() connection.close() print(“MySQL connection is closed.”)
To test this, let’s run the following command (you will have needed to run the GetSpreadsheetData() method or you will not have “data” defined.
WriteToMySQLTable(data, ‘MyData’)
The output should be:
Table MyData has been dropped Table MyData has been created Table MyData successfully updated. MyData row count: 10 MySQL connection is closed.
Checking the data in MySQL Workbench looks successful, but there is one issue that needs to be addressed. Here is the table in MySQL Workbench:
Notice that we have 2 possible issues. The very last row is all NULL, which we most likely do not expect this row to be included. But more importantly, the missing values in Column2 are NOT NULL! This is because Python is reading the sheet data and sees a blank value, which is most likely interpreted as an empty string. We probably do not want empty strings here and expect NULL values instead. So let’s write a method to cleanup the empty string values and write them as NULL values.
def PreserveNULLValues(listName): print(‘Preserving NULL values...’) for x in range(len(listName)): for y in range(len(listName[x])): if listName[x][y] == ‘’: listName[x][y] = None print(‘NULL values preserved.’)
What this does is check for empty string values (‘’) and replace them with the Python keyword “None”, which will be written to MySQL as a NULL value. Let’s check this:
data = GetSpreadsheetData(‘GoogleSheetData’, 0)PreserveNULLValues(data)WriteToMySQLTable(data, ‘MyData’)
Let’s check in MySQL Workbench to see what this looks like:
Much better! I don’t normally get a NULL row at the end, but we can drop this if we need to.
Now let’s say we wanted to update the table with our second worksheet, with worksheet index = 1. This time we don’t want to drop the table, we just want to insert into it. We can define a new method called UpdateMySQLTable. We are going to use the same method described above (WriteToMySQLTable) except we will delete the following lines of code:
sql_drop = ...sql_create_table = ...
Run this method with the new worksheet index:
data = GetSpreadsheetData(‘GoogleSheetData’, 1)PreserveNULLValues(data)UpdateMySQLTable(data, ‘MyData’)
And you will now have a table with 20 rows, 10 from each sheet. Here is what the resulting table looks like in MySQL Workbench:
Just make sure that the column names and orders match, otherwise you will have to arrange them so that they do. For my team’s data, sometimes we will write in a new column if our methodology changes, and I will go back and insert empty columns into the older tabs and re-import all the data. Now you can take advantage of having a database in MySQL with the functionality of Google sheets! Here is what my code looks like in Jupyter Notebook. Happy coding! | [
{
"code": null,
"e": 1057,
"s": 172,
"text": "In data jobs, we often use different methods of writing and analyzing data. Google sheets is a great way to collaboratively enter and share data. For larger datasets, Google sheets becomes painfully slow to work with, and one way around that is to create a new worksheet when there are too many rows. One project my team is working on creates 3000 rows a week, which isn’t much data by most standards, but it gets bogged down after a few weeks. Team members started archiving worksheets, which made it very difficult to do any aggregation on the data. I decided it was a better idea to write all our data to a MySQL table, which also allows other teams to join our data to other tables they are working with. I will walk you through the process of doing this using Python. For this project, I will be using Jupyter Notebook, Python 3.7.1, and MySQL Workbench 8.0 on a Windows machine."
},
{
"code": null,
"e": 1170,
"s": 1057,
"text": "I created a small dataset for this project using Google sheets. I included two worksheets, the first looks like:"
},
{
"code": null,
"e": 1334,
"s": 1170,
"text": "Notice that I have intentionally left two cells blank in Column 2. This will be for an example later. The second worksheet (a second tab at the bottom) looks like:"
},
{
"code": null,
"e": 1507,
"s": 1334,
"text": "The first thing we need to do is access the Google developers console using this link. Create a new project by clicking on the “CREATE PROJECT” link at the top of the page:"
},
{
"code": null,
"e": 1560,
"s": 1507,
"text": "Name the project something relevant, as shown below."
},
{
"code": null,
"e": 1755,
"s": 1560,
"text": "Next, we need to create a service account for the project. Click on the navigation menu at the top left of the page (3 horizontal lines, often called a hamburger), and select “Service Accounts”:"
},
{
"code": null,
"e": 1864,
"s": 1755,
"text": "You will need to select your project from the top of the page (a) and then hit “CREATE SERVICE ACCOUNT” (b)."
},
{
"code": null,
"e": 2356,
"s": 1864,
"text": "Give the service account a meaningful name and click “CREATE”. Next we will set the service account permissions role to owner and click “CONTINUE”. On the next page we will skip the “grant users access to this service account” section, and move on to the “Create key” section below. This will open up a side bar that allows us to select a key type. Select “JSON” and hit “CREATE”. This will save the JSON file to your computer, and we will be using this file to grab some information out of."
},
{
"code": null,
"e": 2842,
"s": 2356,
"text": "Open the JSON file using something like Notepad++. Find the line which contains “Client email”, and copy the entire email address (between the quotes) to your clipboard. Next, go back to your Google sheet which contains the data you want to write to a MySQL table. Click on the green button labeled “Share” in the upper right of the spreadsheet. Paste the email address from the JSON file into the field and click “Send”. This will allow our Python program to access this Google sheet."
},
{
"code": null,
"e": 3429,
"s": 2842,
"text": "Now that everything is set up, we can move on to Python! For this tutorial, I am using Jupyter Notebook and Python 3.7.1. If you do not have Python installed on your machine, you will need to do so. Jupyter Notebook comes with Anaconda, which is a great package for Python. You can launch Jupyter Notebook by typing into the search bar (in Windows, on the taskbar) “Jupyter Notebook”, or you can launch the Anaconda prompt, and once the prompt is open, type “Jupyter Notebook” without the quotes, but we will need the Anaconda prompt later so I suggest using the first method described."
},
{
"code": null,
"e": 3689,
"s": 3429,
"text": "Jupyter Notebook will launch in your browser. You will be directed to your working directory. You can navigate to a different folder, but for now we will create a new notebook by clicking “New” in the upper right of the page and selecting a Python 3 notebook:"
},
{
"code": null,
"e": 3953,
"s": 3689,
"text": "Let’s rename the notebook to “GoogleSheetsToMySQL” by clicking on the notebook name (Untitled) at the top of the page. Next, we need to move the JSON file we downloaded to our working directory. I believe the default directory is under “C://users//your_username”."
},
{
"code": null,
"e": 4282,
"s": 3953,
"text": "Before we can start coding, we will need to install a few modules. To install the modules we need, open the Anaconda prompt (you can find this in the Windows search bar on the taskbar). In the Anaconda prompt, you will need to install the following modules. Use pip by typing the following commands and hitting enter after each:"
},
{
"code": null,
"e": 4353,
"s": 4282,
"text": "pip install gspreadpip install oauth2clientpip install mysql-connector"
},
{
"code": null,
"e": 4373,
"s": 4353,
"text": "pip install gspread"
},
{
"code": null,
"e": 4398,
"s": 4373,
"text": "pip install oauth2client"
},
{
"code": null,
"e": 4426,
"s": 4398,
"text": "pip install mysql-connector"
},
{
"code": null,
"e": 4541,
"s": 4426,
"text": "I have these already installed, as shown by the output of the command prompt (when attempting to install gspread):"
},
{
"code": null,
"e": 5057,
"s": 4541,
"text": "Since we will be accessing a MySQL database, it is important not to expose our login credentials in our code. We will create a Python file (.py) and store these credentials there. We can then import them into our Jupyter Notebook script easily. The quickest way to create your .py file is with Notepad++. I used PyCharm for this, but use whichever IDE you prefer. Open your IDE and create a file called “MySQLCredentials.py”. In this file, we just need to type 4 lines and save it to our working directory. We need:"
},
{
"code": null,
"e": 5169,
"s": 5057,
"text": "user = (your username)password = (your password)host = (hostname)database = (database schema you will be using)"
},
{
"code": null,
"e": 5224,
"s": 5169,
"text": "Save the file and drop it into your working directory."
},
{
"code": null,
"e": 5346,
"s": 5224,
"text": "Now, back to your notebook. We need to import the modules we will be using by entering into our first cell the following:"
},
{
"code": null,
"e": 5496,
"s": 5346,
"text": "# import librariesimport gspreadimport MySQLCredentials as mcimport mysql.connectorfrom oauth2client.service_account import ServiceAccountCredentials"
},
{
"code": null,
"e": 5612,
"s": 5496,
"text": "Run the cell and if you don’t get any errors, great! Next we need to initialize some variables to use with gspread:"
},
{
"code": null,
"e": 5860,
"s": 5612,
"text": "# initialize variables for gspreadscope = [‘https://spreadsheets.google.com/feeds',‘https://www.googleapis.com/auth/drive']creds = ServiceAccountCredentials.from_json_keyfile_name(‘GoogleSheetsToMySQL.json’, scope)client = gspread.authorize(creds)"
},
{
"code": null,
"e": 6038,
"s": 5860,
"text": "If you named your JSON file something different, just make sure the name is correct in the code above. Now we need to define a method which will pull data from the Google sheet:"
},
{
"code": null,
"e": 6235,
"s": 6038,
"text": "# define method to pull data from spreadsheetdef GetSpreadsheetData(sheetName, worksheetIndex): sheet = client.open(sheetName).get_worksheet(worksheetIndex) return sheet.get_all_values()[1:]"
},
{
"code": null,
"e": 6882,
"s": 6235,
"text": "We are defining a method with two parameters. We need to tell it what sheet name we are referencing, and the worksheet index. The worksheet index refers to which sheet tab we are referencing. The first tab has an index of 0, the second tab has an index of 1, and so on. We won’t need these values until we call the method, so we will get back to that shortly. The return type for this method is a list, and it will return all values on that sheet. We then slice the list using [1:] which will remove the first element of the list. Since the Google sheet has a header with column names, this will drop that so we only pull the data from the sheet."
},
{
"code": null,
"e": 6960,
"s": 6882,
"text": "Before we move on, let’s check that this method can grab data from our sheet."
},
{
"code": null,
"e": 6997,
"s": 6960,
"text": "In a new cell in the notebook, enter"
},
{
"code": null,
"e": 7045,
"s": 6997,
"text": "data = GetSpreadsheetData(‘GoogleSheetData’, 0)"
},
{
"code": null,
"e": 7561,
"s": 7045,
"text": "You might get an error saying you need to enable the Drive API. It will provide a link which you can click on to enable the Drive API. Now rerun the cell and make sure you don’t get any errors. I had to run it a few times to enable 2 separate APIs and had to wait a minute before it ran without giving me an error. You should not need to do this again. OK, now check that you have the data you expect. You can check the first row of the list, as well as the length of the list (in this case, how many rows of data):"
},
{
"code": null,
"e": 7592,
"s": 7561,
"text": "print(data[0])print(len(data))"
},
{
"code": null,
"e": 7612,
"s": 7592,
"text": "which should return"
},
{
"code": null,
"e": 7647,
"s": 7612,
"text": "[‘1’, ‘a’, ‘2019–01–01 1:00:00’]10"
},
{
"code": null,
"e": 7873,
"s": 7647,
"text": "Now we need to set up a method to write this data to MySQL. Using a try-except-finally block will be useful here. There are several blocks of comments, indicated by having # in front of them, which are only for clarification:"
},
{
"code": null,
"e": 11327,
"s": 7873,
"text": "# define method to write list of data to MySQL tabledef WriteToMySQLTable(sql_data, tableName):# we are using a try/except block (also called a try/catch block in other languages) which is good for error handling. It will “try” to execute anything in the “try” block, and if there is an error, it will report the error in the “except” block. Regardless of any errors, the “finally” block will always be executed. try:# Here we include the connection credentials for MySQL. We create a connection object that we pass the credentials to, and notice that we can specify the database which is ‘sys’ in the MySQLCredentials.py file because I’m using since I’m using the default database in MySQL Workbench 8.0. connection = mysql.connector.connect( user = mc.user, password = mc.password, host = mc.host, database = mc.database )# This command will drop the table, and we could just have the table name hardcoded into the string, but instead I am using the name of the table passed into the method. {} is a placeholder for what we want to pass into this string, and using .format(blah) we can pass the string name from the variable passed into the method here. sql_drop = “ DROP TABLE IF EXISTS {} “.format(tableName)# Now we will create the table, and the triple quotes are used so that when we go to the next line of code, we remain in a string. Otherwise it will terminate the string at the end of the line, and we want ALL of this to be one giant string. When injecting data into VALUES, we use the placeholder %s for each column of data we have. sql_create_table = “””CREATE TABLE {}( Column1 INT(11), Column2 VARCHAR(30), Column3 DATETIME, PRIMARY KEY (Column1) )”””.format(tableName) sql_insert_statement = “””INSERT INTO {}( Column1, Column2, Column3 ) VALUES ( %s,%s,%s )”””.format(tableName)# Here we create a cursor, which we will use to execute the MySQL statements above. After each statement is executed, a message will be printed to the console if the execution was successful. cursor = connection.cursor() cursor.execute(sql_drop) print(‘Table {} has been dropped’.format(tableName)) cursor.execute(sql_create_table) print(‘Table {} has been created’.format(tableName))# We need to write each row of data to the table, so we use a for loop that will insert each row of data one at a time for i in sql_data: cursor.execute(sql_insert_statement, i)# Now we execute the commit statement, and print to the console that the table was updated successfully connection.commit() print(“Table {} successfully updated.”.format(tableName))# Errors are handled in the except block, and we will get the information printed to the console if there is an error except mysql.connector.Error as error : connection.rollback() print(“Error: {}. Table {} not updated!”.format(error, tableName))# We need to close the cursor and the connection, and this needs to be done regardless of what happened above. finally: cursor.execute(‘SELECT COUNT(*) FROM {}’.format(tableName)) rowCount = cursor.fetchone()[0] print(tableName, ‘row count:’, rowCount) if connection.is_connected(): cursor.close() connection.close() print(“MySQL connection is closed.”)"
},
{
"code": null,
"e": 11471,
"s": 11327,
"text": "To test this, let’s run the following command (you will have needed to run the GetSpreadsheetData() method or you will not have “data” defined."
},
{
"code": null,
"e": 11505,
"s": 11471,
"text": "WriteToMySQLTable(data, ‘MyData’)"
},
{
"code": null,
"e": 11527,
"s": 11505,
"text": "The output should be:"
},
{
"code": null,
"e": 11671,
"s": 11527,
"text": "Table MyData has been dropped Table MyData has been created Table MyData successfully updated. MyData row count: 10 MySQL connection is closed."
},
{
"code": null,
"e": 11815,
"s": 11671,
"text": "Checking the data in MySQL Workbench looks successful, but there is one issue that needs to be addressed. Here is the table in MySQL Workbench:"
},
{
"code": null,
"e": 12302,
"s": 11815,
"text": "Notice that we have 2 possible issues. The very last row is all NULL, which we most likely do not expect this row to be included. But more importantly, the missing values in Column2 are NOT NULL! This is because Python is reading the sheet data and sees a blank value, which is most likely interpreted as an empty string. We probably do not want empty strings here and expect NULL values instead. So let’s write a method to cleanup the empty string values and write them as NULL values."
},
{
"code": null,
"e": 12557,
"s": 12302,
"text": "def PreserveNULLValues(listName): print(‘Preserving NULL values...’) for x in range(len(listName)): for y in range(len(listName[x])): if listName[x][y] == ‘’: listName[x][y] = None print(‘NULL values preserved.’)"
},
{
"code": null,
"e": 12725,
"s": 12557,
"text": "What this does is check for empty string values (‘’) and replace them with the Python keyword “None”, which will be written to MySQL as a NULL value. Let’s check this:"
},
{
"code": null,
"e": 12830,
"s": 12725,
"text": "data = GetSpreadsheetData(‘GoogleSheetData’, 0)PreserveNULLValues(data)WriteToMySQLTable(data, ‘MyData’)"
},
{
"code": null,
"e": 12890,
"s": 12830,
"text": "Let’s check in MySQL Workbench to see what this looks like:"
},
{
"code": null,
"e": 12983,
"s": 12890,
"text": "Much better! I don’t normally get a NULL row at the end, but we can drop this if we need to."
},
{
"code": null,
"e": 13330,
"s": 12983,
"text": "Now let’s say we wanted to update the table with our second worksheet, with worksheet index = 1. This time we don’t want to drop the table, we just want to insert into it. We can define a new method called UpdateMySQLTable. We are going to use the same method described above (WriteToMySQLTable) except we will delete the following lines of code:"
},
{
"code": null,
"e": 13367,
"s": 13330,
"text": "sql_drop = ...sql_create_table = ..."
},
{
"code": null,
"e": 13413,
"s": 13367,
"text": "Run this method with the new worksheet index:"
},
{
"code": null,
"e": 13517,
"s": 13413,
"text": "data = GetSpreadsheetData(‘GoogleSheetData’, 1)PreserveNULLValues(data)UpdateMySQLTable(data, ‘MyData’)"
},
{
"code": null,
"e": 13645,
"s": 13517,
"text": "And you will now have a table with 20 rows, 10 from each sheet. Here is what the resulting table looks like in MySQL Workbench:"
}
] |
Unfolding AlphaFold. DeepMind AlphaFold Algorithm Explained... | by Naser Tamimi | Towards Data Science | On Monday, November 30th, 2020, the world received good news FINALLY. As you know, I am not talking about vaccine, but about a technology which eventually can lead to thousands of vaccines and treatments. This is a breakthrough not only for life sciences and biology but also for data science and artificial intelligence. Every data scientist should know about it and gets inspired by the impact that this technology could have in our life.
On Monday, DeepMind announced that in a major scientific breakthrough, the latest version of AlphaFold had been recognized as a solution to one of biology’s grand challenges — the “protein folding problem.”
In this article, I am going to explain the DeepMind team approach to the problem in layman’s language. I hope it encourages professional data scientists to attack more similar problems in life sciences and improve the quality of life for all human kinds.
Proteins carry out all the functions necessary for life. During transcription, the DNA serves as a template to form RNA. The resulting RNA is a single-stranded copy of the gene, which next must be translated into a protein molecule [read more]. Decoding DNA, RNA, and proteins can open unlimited doors to treat and cure diseases at their most basic level. DNA is a double-stranded, helical molecule composed of nucleotides known as A, C, G, and T. RNA is a single-stranded molecule composed of nucleotides known as A, C, G, and U. Although both DNA and RNA are important, the only way for them to control cell functionality is through proteins. Without proteins, they are like codes that have never been run.
Proteins are long chains or sequences of amino acids. Depending on the order of these 21 amino acids (ARNDCEQGHILKMFPSTUWYV), we can have different types of protein with different 3D structures (a unique sequence ==> a unique 3D structure). The 3D structure of the protein mainly determines its functionality. That is the reason why many researchers in life sciences and biology (sometimes called structural biologists) are interested in studying the structure of proteins and the relationship between amino acids sequence in a protein and its 3D structure.
Until now, the best way to obtain the 3D structure of a protein was through X-ray crystallography. It takes about a year and costs about $120,000 to obtain the structure of a single protein through X-ray crystallography [source]. On average, a protein is composed of 300 amino acids (residues). Therefore, at least, we have around 21299 (the first residue is fixed) possible proteins that each of them folds in a unique way and therefore has a unique functionality or application. Some of these proteins can cure the most complicated diseases, but we are unable to find them with time-consuming and expensive techniques such as X-ray crystallography. Besides X-ray crystallography, there is no straightforward and accurate solution to find the 3D structure of a protein from its sequence. In other words, there is no analytical solution available to predict the 3D structure of a protein from its sequence. There are some approximate solutions, but their accuracy is well below the acceptable range. That’s why the problem of protein folding is a 50-year old problem. This is such an important problem that every 2 years since 1994, top research teams around the world gather to showcase their prediction models in a competition called CASP (Critical Assessment of Protein Structure Prediction) [link].
The last CASP competition, known as CASP14, was held in November 2020, and the DeepMind team could present a stunning solution, called AlphaFold. This solution achieved a level of accuracy that is almost equivalent to the experimentally determined structures.
The DeepMind team has not published any paper about their new AlphaFold algorithm and its CASP14 approach yet. But in 2019, they published a full paper and released the full code for the previous AlphaFold (that won CASP13 in 2018). In this article, I call the initial 2018 version “AlphaFold” and I call the new 2020 version “AlphaFold2”. We expect these two algorithms will be very similar; therefore, I try to explain what was in the original AlphaFold algorithm and how they solved this problem back in 2018. After that, I compare their 2020 solution with the old one using a short blog that they recently published.
AlphaFold solves the problem in two steps. The first step involves a deep learning predictive modeling (convolutional neural network), and the second step is applying gradient descent optimization.
As I mentioned, the first step is predictive modeling using deep learning (deep convolutional neural networks). The goal of this step is to convert the protein sequence to two important matrices: distance distribution matrix and torsion angle matrix.
With having these two matrices, we can go to the second step, which is optimization (using an iterative gradient descent method). The goal of the second step is to translate these two matrices (distance distribution matrix and torsion angle matrix) into a 3D structure.
Now that you have a general (but probably not clear) idea about their approach let’s take a look at some details.
At this step, like any other machine learning problem, we need input data and target. The goal is to train a model that inputs the data and output the target with acceptable accuracy or error.
What is our input data here? For this problem, our input data are protein sequences. For example, something like (but much longer):
MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLS
It is called a protein sequence. As you know, in machine learning, the most successful predictive models are usually the ones that have good feature engineering. Feature engineering is the process of converting raw data (in this case, raw sequences) into more meaningful data. Feature engineering needs in field knowledge and a good understanding of the science behind the problem. In this case, the feature engineering was done mostly using MSA (multiple sequence alignment) techniques. Imagine you have a long chain of amino acids, and parts of this chain are similar to some parts of other known proteins. Using alignment, we can identify those similar subsets make a feature profile for that section of our sequence. This is a simple explanation of MSA feature engineering. The team did this kind of feature engineering for 31,247 proteins from Protein Data Bank (PDB) [link] and split them into the train and test sets (29,427 and 1,820 proteins, respectively). In addition, they calculated the distance and torsion angles between each pair of protein residues (i.e., amino acids). It will be the target for the predictive model. Now that we have our MSA features (as input) and distogram matrices as a target, we need a model to train and test on them. For this purpose DeepMind team decided to use a Deep Res-Net model (a deep convolutional neural network model). Here is a summary of neural network hyperparameters that they used.
Neural network hyperparameters>> 7 groups of 4 blocks with 256 channels, cycling through dilations 1, 2, 4, 8.>> 48 groups of 4 blocks with 128 channels, cycling through dilations 1, 2, 4, 8.>> Optimization: synchronized stochastic gradient descent>> Batch size: batch of 4 crops on each of 8 GPU workers.0.85 dropout keep probability.>> Nonlinearity: ELU.>> Learning rate: 0.06.>> Auxiliary loss weights: secondary structure: 0.005; accessible surface area: 0.001. These auxiliary losses were cut by a factor 10 after 100 000 steps.>> Learning rate decayed by 50% at 150,000, 200,000, 250,000 and 350,000 steps.>> Training time: about 5 days for 600,000 steps.
Step one outputs are two matrices that show the distance and torsion angles between different parts (or residues) of a protein. To have a 3D structure, we must translate these two matrices into a 3D structure. For example, we must show where inside this protein sequence we have a helix, strand, or any kind of torsion. The process of converting the distogram matrices into 3D structures is done with an iterative gradient descent method. To achieve this goal, the algorithm starts with a smooth 3D structure model updates the structure until the distogram (matrix of distances between different parts of a protein) of the predicted structure gets as close as possible to the distogram (or output) from the deep learning part. This is how the DeepMind team won the 2018 CASP13 competition. But how did they win the 2020 (CASP14) competition? Let’s see if we can find an answer to that.
Obviously, the DeepMind team achieved a breakthrough solution to this problem using their new algorithm. It suggests that the new algorithm must be more advanced than the previous one in different aspects. Unfortunately, we don’t know too much about their new approach, except a short blog post with the following flowchart.
Apparently, the DeepMind team did two important updates in their new approach. First, instead of taking two steps approach, they are solving the problem end to end. This end-to-end solution is based on an attention-based neural network method instead of a simple deep learning model. Attention-based neural networks became popular in 2015 after their encouraging results in natural language processing (NLP) applications. They are not only getting popular for NLP purposes, but also for computer vision purposes as well. DeepMind took advantage of this new deep learning approach in their model and could achieve this historic breakthrough.
I will keep you updated if they publish papers or codes regarding their new algorithm. Please follow me for updates. | [
{
"code": null,
"e": 612,
"s": 171,
"text": "On Monday, November 30th, 2020, the world received good news FINALLY. As you know, I am not talking about vaccine, but about a technology which eventually can lead to thousands of vaccines and treatments. This is a breakthrough not only for life sciences and biology but also for data science and artificial intelligence. Every data scientist should know about it and gets inspired by the impact that this technology could have in our life."
},
{
"code": null,
"e": 819,
"s": 612,
"text": "On Monday, DeepMind announced that in a major scientific breakthrough, the latest version of AlphaFold had been recognized as a solution to one of biology’s grand challenges — the “protein folding problem.”"
},
{
"code": null,
"e": 1074,
"s": 819,
"text": "In this article, I am going to explain the DeepMind team approach to the problem in layman’s language. I hope it encourages professional data scientists to attack more similar problems in life sciences and improve the quality of life for all human kinds."
},
{
"code": null,
"e": 1783,
"s": 1074,
"text": "Proteins carry out all the functions necessary for life. During transcription, the DNA serves as a template to form RNA. The resulting RNA is a single-stranded copy of the gene, which next must be translated into a protein molecule [read more]. Decoding DNA, RNA, and proteins can open unlimited doors to treat and cure diseases at their most basic level. DNA is a double-stranded, helical molecule composed of nucleotides known as A, C, G, and T. RNA is a single-stranded molecule composed of nucleotides known as A, C, G, and U. Although both DNA and RNA are important, the only way for them to control cell functionality is through proteins. Without proteins, they are like codes that have never been run."
},
{
"code": null,
"e": 2341,
"s": 1783,
"text": "Proteins are long chains or sequences of amino acids. Depending on the order of these 21 amino acids (ARNDCEQGHILKMFPSTUWYV), we can have different types of protein with different 3D structures (a unique sequence ==> a unique 3D structure). The 3D structure of the protein mainly determines its functionality. That is the reason why many researchers in life sciences and biology (sometimes called structural biologists) are interested in studying the structure of proteins and the relationship between amino acids sequence in a protein and its 3D structure."
},
{
"code": null,
"e": 3644,
"s": 2341,
"text": "Until now, the best way to obtain the 3D structure of a protein was through X-ray crystallography. It takes about a year and costs about $120,000 to obtain the structure of a single protein through X-ray crystallography [source]. On average, a protein is composed of 300 amino acids (residues). Therefore, at least, we have around 21299 (the first residue is fixed) possible proteins that each of them folds in a unique way and therefore has a unique functionality or application. Some of these proteins can cure the most complicated diseases, but we are unable to find them with time-consuming and expensive techniques such as X-ray crystallography. Besides X-ray crystallography, there is no straightforward and accurate solution to find the 3D structure of a protein from its sequence. In other words, there is no analytical solution available to predict the 3D structure of a protein from its sequence. There are some approximate solutions, but their accuracy is well below the acceptable range. That’s why the problem of protein folding is a 50-year old problem. This is such an important problem that every 2 years since 1994, top research teams around the world gather to showcase their prediction models in a competition called CASP (Critical Assessment of Protein Structure Prediction) [link]."
},
{
"code": null,
"e": 3904,
"s": 3644,
"text": "The last CASP competition, known as CASP14, was held in November 2020, and the DeepMind team could present a stunning solution, called AlphaFold. This solution achieved a level of accuracy that is almost equivalent to the experimentally determined structures."
},
{
"code": null,
"e": 4525,
"s": 3904,
"text": "The DeepMind team has not published any paper about their new AlphaFold algorithm and its CASP14 approach yet. But in 2019, they published a full paper and released the full code for the previous AlphaFold (that won CASP13 in 2018). In this article, I call the initial 2018 version “AlphaFold” and I call the new 2020 version “AlphaFold2”. We expect these two algorithms will be very similar; therefore, I try to explain what was in the original AlphaFold algorithm and how they solved this problem back in 2018. After that, I compare their 2020 solution with the old one using a short blog that they recently published."
},
{
"code": null,
"e": 4723,
"s": 4525,
"text": "AlphaFold solves the problem in two steps. The first step involves a deep learning predictive modeling (convolutional neural network), and the second step is applying gradient descent optimization."
},
{
"code": null,
"e": 4974,
"s": 4723,
"text": "As I mentioned, the first step is predictive modeling using deep learning (deep convolutional neural networks). The goal of this step is to convert the protein sequence to two important matrices: distance distribution matrix and torsion angle matrix."
},
{
"code": null,
"e": 5244,
"s": 4974,
"text": "With having these two matrices, we can go to the second step, which is optimization (using an iterative gradient descent method). The goal of the second step is to translate these two matrices (distance distribution matrix and torsion angle matrix) into a 3D structure."
},
{
"code": null,
"e": 5358,
"s": 5244,
"text": "Now that you have a general (but probably not clear) idea about their approach let’s take a look at some details."
},
{
"code": null,
"e": 5551,
"s": 5358,
"text": "At this step, like any other machine learning problem, we need input data and target. The goal is to train a model that inputs the data and output the target with acceptable accuracy or error."
},
{
"code": null,
"e": 5683,
"s": 5551,
"text": "What is our input data here? For this problem, our input data are protein sequences. For example, something like (but much longer):"
},
{
"code": null,
"e": 5734,
"s": 5683,
"text": "MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLS"
},
{
"code": null,
"e": 7173,
"s": 5734,
"text": "It is called a protein sequence. As you know, in machine learning, the most successful predictive models are usually the ones that have good feature engineering. Feature engineering is the process of converting raw data (in this case, raw sequences) into more meaningful data. Feature engineering needs in field knowledge and a good understanding of the science behind the problem. In this case, the feature engineering was done mostly using MSA (multiple sequence alignment) techniques. Imagine you have a long chain of amino acids, and parts of this chain are similar to some parts of other known proteins. Using alignment, we can identify those similar subsets make a feature profile for that section of our sequence. This is a simple explanation of MSA feature engineering. The team did this kind of feature engineering for 31,247 proteins from Protein Data Bank (PDB) [link] and split them into the train and test sets (29,427 and 1,820 proteins, respectively). In addition, they calculated the distance and torsion angles between each pair of protein residues (i.e., amino acids). It will be the target for the predictive model. Now that we have our MSA features (as input) and distogram matrices as a target, we need a model to train and test on them. For this purpose DeepMind team decided to use a Deep Res-Net model (a deep convolutional neural network model). Here is a summary of neural network hyperparameters that they used."
},
{
"code": null,
"e": 7835,
"s": 7173,
"text": "Neural network hyperparameters>> 7 groups of 4 blocks with 256 channels, cycling through dilations 1, 2, 4, 8.>> 48 groups of 4 blocks with 128 channels, cycling through dilations 1, 2, 4, 8.>> Optimization: synchronized stochastic gradient descent>> Batch size: batch of 4 crops on each of 8 GPU workers.0.85 dropout keep probability.>> Nonlinearity: ELU.>> Learning rate: 0.06.>> Auxiliary loss weights: secondary structure: 0.005; accessible surface area: 0.001. These auxiliary losses were cut by a factor 10 after 100 000 steps.>> Learning rate decayed by 50% at 150,000, 200,000, 250,000 and 350,000 steps.>> Training time: about 5 days for 600,000 steps."
},
{
"code": null,
"e": 8721,
"s": 7835,
"text": "Step one outputs are two matrices that show the distance and torsion angles between different parts (or residues) of a protein. To have a 3D structure, we must translate these two matrices into a 3D structure. For example, we must show where inside this protein sequence we have a helix, strand, or any kind of torsion. The process of converting the distogram matrices into 3D structures is done with an iterative gradient descent method. To achieve this goal, the algorithm starts with a smooth 3D structure model updates the structure until the distogram (matrix of distances between different parts of a protein) of the predicted structure gets as close as possible to the distogram (or output) from the deep learning part. This is how the DeepMind team won the 2018 CASP13 competition. But how did they win the 2020 (CASP14) competition? Let’s see if we can find an answer to that."
},
{
"code": null,
"e": 9046,
"s": 8721,
"text": "Obviously, the DeepMind team achieved a breakthrough solution to this problem using their new algorithm. It suggests that the new algorithm must be more advanced than the previous one in different aspects. Unfortunately, we don’t know too much about their new approach, except a short blog post with the following flowchart."
},
{
"code": null,
"e": 9687,
"s": 9046,
"text": "Apparently, the DeepMind team did two important updates in their new approach. First, instead of taking two steps approach, they are solving the problem end to end. This end-to-end solution is based on an attention-based neural network method instead of a simple deep learning model. Attention-based neural networks became popular in 2015 after their encouraging results in natural language processing (NLP) applications. They are not only getting popular for NLP purposes, but also for computer vision purposes as well. DeepMind took advantage of this new deep learning approach in their model and could achieve this historic breakthrough."
}
] |
C Language | Set 1 - GeeksforGeeks | 07 Oct, 2021
Following questions have been asked in GATE CS exam.
1. Consider the following three C functions :
[PI] int * g (void) { int x = 10; return (&x); } [P2] int * g (void) { int * px; *px = 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px = 10; return px; }
Which of the above three functions are likely to cause problems with pointers? (GATE 2001)(a) Only P3(b) Only P1 and P3(c) Only P1 and P2(d) P1, P2 and P3
Answer: (c)Eplaination: In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid.In P2, pointer variable px is being assigned a value without allocating memory to it.P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, it’s existence will remain in memory even after return of g() as it is on heap.
2. The value of j at the end of the execution of the following C program. (GATE CS 2000)
int incr (int i){ static int count = 0; count = count + i; return (count);}main (){ int i,j; for (i = 0; i <=4; i++) j = incr(i);}
(a) 10(b) 4(c) 6(d) 7
Answer (a)Eplaination: count is static variable in incr(). Statement static int count = 0 will assign count to 0 only in first call. Other calls to this function will take the old values of count.Count will become 0 after the call incr(0)Count will become 1 after the call incr(1)Count will become 3 after the call incr(2)Count will become 6 after the call incr(3)Count will become 10 after the call incr(4)
3. Consider the following C declaration
struct { short s [5]; union { float y; long z; }u; } t;
Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignmentconsiderations, is (GATE CS 2000)(a) 22 bytes(b) 14 bytes(c) 18 bytes(d) 10 bytes
Answer: (c)Explanation: Short array s[5] will take 10 bytes as size of short is 2 bytes. Since u is a union, memory allocated to u will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8).
4. The number of tokens in the following C statement.
printf("i = %d, &i = %x", i, &i);
is (GATE 2000)(a) 3(b) 26(c) 10(d) 21
Answer (c)Explanation:In a C source program, the basic element recognized by the compiler is the “token.” A token is source-program text that the compiler does not break down into component elements.There are 6 types of C tokens : identifiers, keywords, constants, operators, string literals and other separators. There are total 10 tokens in the above printf statement.
5. The following C declarations
struct node { int i; float j; }; struct node *s[10] ;
define s to be (GATE CS 2000)
(a) An array, each element of which is a pointer to a structure of type node(b) A structure of 2 fields, each field being a pointer to an array of 10 elements(c) A structure of 3 fields: an integer, a float, and an array of 10 elements(d) An array, each element of which is a structure of type node.
Answer: (a)
pradipbankar0097
GATE-CS-2000
GATE-CS-2001
GATE-CS-C-Language
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Semaphores in Process Synchronization
Caesar Cipher in Cryptography
Difference between Process and Thread
Inter Process Communication (IPC)
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2
Database Management Systems | Set 1 | [
{
"code": null,
"e": 23958,
"s": 23930,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24011,
"s": 23958,
"text": "Following questions have been asked in GATE CS exam."
},
{
"code": null,
"e": 24057,
"s": 24011,
"text": "1. Consider the following three C functions :"
},
{
"code": "[PI] int * g (void) { int x = 10; return (&x); } [P2] int * g (void) { int * px; *px = 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px = 10; return px; } ",
"e": 24271,
"s": 24057,
"text": null
},
{
"code": null,
"e": 24426,
"s": 24271,
"text": "Which of the above three functions are likely to cause problems with pointers? (GATE 2001)(a) Only P3(b) Only P1 and P3(c) Only P1 and P2(d) P1, P2 and P3"
},
{
"code": null,
"e": 24902,
"s": 24426,
"text": "Answer: (c)Eplaination: In P1, pointer variable x is a local variable to g(), and g() returns pointer to this variable. x may vanish after g() has returned as x exists on stack. So, &x may become invalid.In P2, pointer variable px is being assigned a value without allocating memory to it.P3 works perfectly fine. Memory is allocated to pointer variable px using malloc(). So, px exists on heap, it’s existence will remain in memory even after return of g() as it is on heap."
},
{
"code": null,
"e": 24991,
"s": 24902,
"text": "2. The value of j at the end of the execution of the following C program. (GATE CS 2000)"
},
{
"code": "int incr (int i){ static int count = 0; count = count + i; return (count);}main (){ int i,j; for (i = 0; i <=4; i++) j = incr(i);}",
"e": 25137,
"s": 24991,
"text": null
},
{
"code": null,
"e": 25159,
"s": 25137,
"text": "(a) 10(b) 4(c) 6(d) 7"
},
{
"code": null,
"e": 25567,
"s": 25159,
"text": "Answer (a)Eplaination: count is static variable in incr(). Statement static int count = 0 will assign count to 0 only in first call. Other calls to this function will take the old values of count.Count will become 0 after the call incr(0)Count will become 1 after the call incr(1)Count will become 3 after the call incr(2)Count will become 6 after the call incr(3)Count will become 10 after the call incr(4)"
},
{
"code": null,
"e": 25607,
"s": 25567,
"text": "3. Consider the following C declaration"
},
{
"code": "struct { short s [5]; union { float y; long z; }u; } t; ",
"e": 25693,
"s": 25607,
"text": null
},
{
"code": null,
"e": 25937,
"s": 25693,
"text": "Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignmentconsiderations, is (GATE CS 2000)(a) 22 bytes(b) 14 bytes(c) 18 bytes(d) 10 bytes"
},
{
"code": null,
"e": 26163,
"s": 25937,
"text": "Answer: (c)Explanation: Short array s[5] will take 10 bytes as size of short is 2 bytes. Since u is a union, memory allocated to u will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8)."
},
{
"code": null,
"e": 26217,
"s": 26163,
"text": "4. The number of tokens in the following C statement."
},
{
"code": "printf(\"i = %d, &i = %x\", i, &i);",
"e": 26251,
"s": 26217,
"text": null
},
{
"code": null,
"e": 26289,
"s": 26251,
"text": "is (GATE 2000)(a) 3(b) 26(c) 10(d) 21"
},
{
"code": null,
"e": 26660,
"s": 26289,
"text": "Answer (c)Explanation:In a C source program, the basic element recognized by the compiler is the “token.” A token is source-program text that the compiler does not break down into component elements.There are 6 types of C tokens : identifiers, keywords, constants, operators, string literals and other separators. There are total 10 tokens in the above printf statement."
},
{
"code": null,
"e": 26692,
"s": 26660,
"text": "5. The following C declarations"
},
{
"code": "struct node { int i; float j; }; struct node *s[10] ; ",
"e": 26753,
"s": 26692,
"text": null
},
{
"code": null,
"e": 26783,
"s": 26753,
"text": "define s to be (GATE CS 2000)"
},
{
"code": null,
"e": 27083,
"s": 26783,
"text": "(a) An array, each element of which is a pointer to a structure of type node(b) A structure of 2 fields, each field being a pointer to an array of 10 elements(c) A structure of 3 fields: an integer, a float, and an array of 10 elements(d) An array, each element of which is a structure of type node."
},
{
"code": null,
"e": 27095,
"s": 27083,
"text": "Answer: (a)"
},
{
"code": null,
"e": 27112,
"s": 27095,
"text": "pradipbankar0097"
},
{
"code": null,
"e": 27125,
"s": 27112,
"text": "GATE-CS-2000"
},
{
"code": null,
"e": 27138,
"s": 27125,
"text": "GATE-CS-2001"
},
{
"code": null,
"e": 27157,
"s": 27138,
"text": "GATE-CS-C-Language"
},
{
"code": null,
"e": 27165,
"s": 27157,
"text": "GATE CS"
},
{
"code": null,
"e": 27169,
"s": 27165,
"text": "MCQ"
},
{
"code": null,
"e": 27267,
"s": 27169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27299,
"s": 27267,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27337,
"s": 27299,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 27367,
"s": 27337,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 27405,
"s": 27367,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 27439,
"s": 27405,
"text": "Inter Process Communication (IPC)"
},
{
"code": null,
"e": 27486,
"s": 27439,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 27512,
"s": 27486,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 27538,
"s": 27512,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 27564,
"s": 27538,
"text": "Computer Networks | Set 2"
}
] |
ASP.NET MVC - Databases | In all ASP.NET MVC applications created in this tutorial we have been passing hard-coded data from the Controllers to the View templates. But, in order to build a real Web application, you might want to use a real database. In this chapter, we will see how to use a database engine in order to store and retrieve the data needed for your application.
To store and retrieve data, we will use a .NET Framework data-access technology known as the Entity Framework to define and work with Models.
The Entity Framework (EF) supports Code First technique, which allows you to create model objects by writing simple classes and then the database will be created on the fly from your classes, which enables a very clean and rapid development workflow.
Let’s take a look at a simple example in which we will add support for Entity framework in our example.
Step 1 − To install the Entity Framework, right-click on your project and select NuGet Package Manager → Manage NuGet Packages for Solution...
It will open the NuGet Package Manager. Search for Entity framework in the search box.
Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog.
Click Ok to continue.
Click the ‘I Accept’ button to start installation.
Once the Entity Framework is installed you will see the message in out window as seen in the above screenshot.
We need to add another class to the Employee Model, which will communicate with Entity Framework to retrieve and save the data using the following code.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVCSimpleApp.Models{
public class Employee{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
public class EmpDBContext : DbContext{
public EmpDBContext()
{ }
public DbSet<Employee> Employees { get; set; }
}
}
As seen above, EmpDBContext is derived from an EF class known as DbContext. In this class, we have one property with the name DbSet, which basically represents the entity you want to query and save.
We need to specify the connection string under <configuration> tag for our database in the Web.config file.
<connectionStrings>
<add name = "EmpDBContext" connectionString = "Data
Source = (LocalDb)\v14.0;AttachDbFilename = |DataDirectory|\EmpDB.mdf;Initial
Catalog = EmployeeDB;Integrated Security = SSPI;"
providerName = "System.Data.SqlClient"/>
</connectionStrings>
You don't actually need to add the EmpDBContext connection string. If you don't specify a connection string, Entity Framework will create localDB database in the user’s directory with the fully qualified name of the DbContext class. For this demo, we will not add the connection string to make things simple.
Now we need to update the EmployeeController.cs file so that we can actually save and retrieve data from the database instead of using hardcoded data.
First we add create a private EmpDBContext class object and then update the Index, Create and Edit action methods as shown in the following code.
using MVCSimpleApp.Models;
using System.Linq;
using System.Web.Mvc;
namespace MVCSimpleApp.Controllers {
public class EmployeeController : Controller{
private EmpDBContext db = new EmpDBContext();
// GET: Employee
public ActionResult Index(){
var employees = from e in db.Employees
orderby e.ID
select e;
return View(employees);
}
// GET: Employee/Create
public ActionResult Create(){
return View();
}
// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee emp){
try{
db.Employees.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}catch{
return View();
}
}
// GET: Employee/Edit/5
public ActionResult Edit(int id){
var employee = db.Employees.Single(m => m.ID == id);
return View(employee);
}
// POST: Employee/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection){
try{
var employee = db.Employees.Single(m => m.ID == id);
if (TryUpdateModel(employee)){
//To Do:- database code
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}catch{
return View();
}
}
}
}
Then we run this application with the following URL http://localhost:63004/Employee. You will see the following output.
As you can see that there is no data on the view, this is because we have not added any records in our database, which is created by Visual Studio.
Let’s go to the SQL Server Object Explorer, you will see the database is created with the same name as we have in our DBContext class.
Let’s expand this database and you will see that it has one table which contains all the fields we have in our Employee model class.
To see the data in this table, right-click on the Employees table and select View Data.
You will see that we have no records at the moment.
Let’s add some records in the database directly as shown in the following screenshot.
Refresh the browser and you will see that data is now updated to the view from the database.
Let’s add one record from the browser by clicking the ‘Create New’ link. It will display the Create view.
Let’s add some data in the following field.
Click on the Create button and it will update the Index view as well add this new record to the database.
Now let’s go the SQL Server Object Explorer and refresh the database. Right-click on the Employees table and select the View data menu option. You will see that the record is added in the database.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2620,
"s": 2269,
"text": "In all ASP.NET MVC applications created in this tutorial we have been passing hard-coded data from the Controllers to the View templates. But, in order to build a real Web application, you might want to use a real database. In this chapter, we will see how to use a database engine in order to store and retrieve the data needed for your application."
},
{
"code": null,
"e": 2762,
"s": 2620,
"text": "To store and retrieve data, we will use a .NET Framework data-access technology known as the Entity Framework to define and work with Models."
},
{
"code": null,
"e": 3013,
"s": 2762,
"text": "The Entity Framework (EF) supports Code First technique, which allows you to create model objects by writing simple classes and then the database will be created on the fly from your classes, which enables a very clean and rapid development workflow."
},
{
"code": null,
"e": 3117,
"s": 3013,
"text": "Let’s take a look at a simple example in which we will add support for Entity framework in our example."
},
{
"code": null,
"e": 3260,
"s": 3117,
"text": "Step 1 − To install the Entity Framework, right-click on your project and select NuGet Package Manager → Manage NuGet Packages for Solution..."
},
{
"code": null,
"e": 3347,
"s": 3260,
"text": "It will open the NuGet Package Manager. Search for Entity framework in the search box."
},
{
"code": null,
"e": 3436,
"s": 3347,
"text": "Select the Entity Framework and click ‘Install’ button. It will open the Preview dialog."
},
{
"code": null,
"e": 3458,
"s": 3436,
"text": "Click Ok to continue."
},
{
"code": null,
"e": 3509,
"s": 3458,
"text": "Click the ‘I Accept’ button to start installation."
},
{
"code": null,
"e": 3620,
"s": 3509,
"text": "Once the Entity Framework is installed you will see the message in out window as seen in the above screenshot."
},
{
"code": null,
"e": 3773,
"s": 3620,
"text": "We need to add another class to the Employee Model, which will communicate with Entity Framework to retrieve and save the data using the following code."
},
{
"code": null,
"e": 4246,
"s": 3773,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Data.Entity;\nusing System.Linq;\n\nusing System.Web;\n\nnamespace MVCSimpleApp.Models{\n public class Employee{\n public int ID { get; set; }\n public string Name { get; set; }\n public DateTime JoiningDate { get; set; }\n public int Age { get; set; }\n }\n\t\n public class EmpDBContext : DbContext{\n public EmpDBContext()\n { }\n public DbSet<Employee> Employees { get; set; }\n }\n}"
},
{
"code": null,
"e": 4445,
"s": 4246,
"text": "As seen above, EmpDBContext is derived from an EF class known as DbContext. In this class, we have one property with the name DbSet, which basically represents the entity you want to query and save."
},
{
"code": null,
"e": 4553,
"s": 4445,
"text": "We need to specify the connection string under <configuration> tag for our database in the Web.config file."
},
{
"code": null,
"e": 4827,
"s": 4553,
"text": "<connectionStrings>\n <add name = \"EmpDBContext\" connectionString = \"Data\n Source = (LocalDb)\\v14.0;AttachDbFilename = |DataDirectory|\\EmpDB.mdf;Initial\n Catalog = EmployeeDB;Integrated Security = SSPI;\"\n providerName = \"System.Data.SqlClient\"/>\n</connectionStrings>"
},
{
"code": null,
"e": 5136,
"s": 4827,
"text": "You don't actually need to add the EmpDBContext connection string. If you don't specify a connection string, Entity Framework will create localDB database in the user’s directory with the fully qualified name of the DbContext class. For this demo, we will not add the connection string to make things simple."
},
{
"code": null,
"e": 5287,
"s": 5136,
"text": "Now we need to update the EmployeeController.cs file so that we can actually save and retrieve data from the database instead of using hardcoded data."
},
{
"code": null,
"e": 5433,
"s": 5287,
"text": "First we add create a private EmpDBContext class object and then update the Index, Create and Edit action methods as shown in the following code."
},
{
"code": null,
"e": 6874,
"s": 5433,
"text": "using MVCSimpleApp.Models;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace MVCSimpleApp.Controllers {\n public class EmployeeController : Controller{\n private EmpDBContext db = new EmpDBContext();\n // GET: Employee\n\t\t\n public ActionResult Index(){\n var employees = from e in db.Employees\n orderby e.ID\n select e;\n return View(employees);\n }\n\t\t\n // GET: Employee/Create\n public ActionResult Create(){\n return View();\n }\n\t\t\n // POST: Employee/Create\n [HttpPost]\n public ActionResult Create(Employee emp){\n try{\n db.Employees.Add(emp);\n db.SaveChanges();\n return RedirectToAction(\"Index\");\n }catch{\n return View();\n }\n }\n\t\t\n // GET: Employee/Edit/5\n public ActionResult Edit(int id){\n var employee = db.Employees.Single(m => m.ID == id);\n return View(employee);\n }\n\t\t\n // POST: Employee/Edit/5\n [HttpPost]\n public ActionResult Edit(int id, FormCollection collection){\n try{\n var employee = db.Employees.Single(m => m.ID == id);\n if (TryUpdateModel(employee)){\n //To Do:- database code\n db.SaveChanges();\n return RedirectToAction(\"Index\");\n }\n return View(employee);\n }catch{\n return View();\n }\n }\n }\n}"
},
{
"code": null,
"e": 6994,
"s": 6874,
"text": "Then we run this application with the following URL http://localhost:63004/Employee. You will see the following output."
},
{
"code": null,
"e": 7142,
"s": 6994,
"text": "As you can see that there is no data on the view, this is because we have not added any records in our database, which is created by Visual Studio."
},
{
"code": null,
"e": 7277,
"s": 7142,
"text": "Let’s go to the SQL Server Object Explorer, you will see the database is created with the same name as we have in our DBContext class."
},
{
"code": null,
"e": 7410,
"s": 7277,
"text": "Let’s expand this database and you will see that it has one table which contains all the fields we have in our Employee model class."
},
{
"code": null,
"e": 7498,
"s": 7410,
"text": "To see the data in this table, right-click on the Employees table and select View Data."
},
{
"code": null,
"e": 7550,
"s": 7498,
"text": "You will see that we have no records at the moment."
},
{
"code": null,
"e": 7636,
"s": 7550,
"text": "Let’s add some records in the database directly as shown in the following screenshot."
},
{
"code": null,
"e": 7729,
"s": 7636,
"text": "Refresh the browser and you will see that data is now updated to the view from the database."
},
{
"code": null,
"e": 7835,
"s": 7729,
"text": "Let’s add one record from the browser by clicking the ‘Create New’ link. It will display the Create view."
},
{
"code": null,
"e": 7879,
"s": 7835,
"text": "Let’s add some data in the following field."
},
{
"code": null,
"e": 7985,
"s": 7879,
"text": "Click on the Create button and it will update the Index view as well add this new record to the database."
},
{
"code": null,
"e": 8183,
"s": 7985,
"text": "Now let’s go the SQL Server Object Explorer and refresh the database. Right-click on the Employees table and select the View data menu option. You will see that the record is added in the database."
},
{
"code": null,
"e": 8218,
"s": 8183,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8232,
"s": 8218,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8267,
"s": 8232,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8290,
"s": 8267,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 8324,
"s": 8290,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 8344,
"s": 8324,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 8379,
"s": 8344,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8396,
"s": 8379,
"text": " University Code"
},
{
"code": null,
"e": 8431,
"s": 8396,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8448,
"s": 8431,
"text": " University Code"
},
{
"code": null,
"e": 8482,
"s": 8448,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8497,
"s": 8482,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 8504,
"s": 8497,
"text": " Print"
},
{
"code": null,
"e": 8515,
"s": 8504,
"text": " Add Notes"
}
] |
Write a program to print message without using println() method in java? | The println() method of the System class accepts aStringas parameter an prints the given String on the console.
public class PrintData {
public static void main(String args[]) {
System.out.println("Hello how are you");
}
}
Hello how are you
In addition to this you can print data on the console in several other ways, some of them are −
Using output stream classes, you can write dat on the specified destination. You can print data on the screen/console by passing the standard output Stream object System.out as source to them.
import java.io.IOException;
import java.io.OutputStreamWriter;
public class PrintData {
public static void main(String args[]) throws IOException {
//Creating a OutputStreamWriter object
OutputStreamWriter streamWriter = new OutputStreamWriter(System.out);
streamWriter.write("Hello welcome to Tutorialspoint . . . . .");
streamWriter.flush();
}
}
Hello welcome to Tutorialspoint . . . . .
The PrintStream class of Java provides two more methods to print data on the console (in addition to the println() method).
The print() − This method accepts a single value of any of the primitive or reference data types as a parameter and prints the given value on the console.
(double value or, a float value or, an int value or, a long value or, a char value, a boolean value or, a char array, a String or, an array or, an object)
The printf() − This method accepts a local variable, a String value representing the required format, objects of variable number representing the arguments and, prints data as instructed.
public class PrintData {
public static void main(String args[]) {
System.out.print("Hello how are you");
System.out.printf(" "+"welcome to Tutorialspoint");
}
}
Hello how are you Welcome to Tutorialspoint
The Logger class of the log4j library provides methods to print data on the console.
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
import java.util.logging.Logger;
public class PrintData{
static Logger log = Logger.getLogger(PrintData.class.getName());
public static void main(String[] args){
log.info("Hello how are you Welcome to Tutorialspoint");
}
}
Jun 28, 2019 2:49:25 PM Mypackage.PrintData main
INFO: Hello how are you Welcome to Tutorialspoint | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "The println() method of the System class accepts aStringas parameter an prints the given String on the console."
},
{
"code": null,
"e": 1297,
"s": 1174,
"text": "public class PrintData {\n public static void main(String args[]) {\n System.out.println(\"Hello how are you\");\n }\n}"
},
{
"code": null,
"e": 1315,
"s": 1297,
"text": "Hello how are you"
},
{
"code": null,
"e": 1411,
"s": 1315,
"text": "In addition to this you can print data on the console in several other ways, some of them are −"
},
{
"code": null,
"e": 1604,
"s": 1411,
"text": "Using output stream classes, you can write dat on the specified destination. You can print data on the screen/console by passing the standard output Stream object System.out as source to them."
},
{
"code": null,
"e": 1982,
"s": 1604,
"text": "import java.io.IOException;\nimport java.io.OutputStreamWriter;\npublic class PrintData {\n public static void main(String args[]) throws IOException {\n //Creating a OutputStreamWriter object\n OutputStreamWriter streamWriter = new OutputStreamWriter(System.out);\n streamWriter.write(\"Hello welcome to Tutorialspoint . . . . .\");\n streamWriter.flush();\n }\n}"
},
{
"code": null,
"e": 2024,
"s": 1982,
"text": "Hello welcome to Tutorialspoint . . . . ."
},
{
"code": null,
"e": 2148,
"s": 2024,
"text": "The PrintStream class of Java provides two more methods to print data on the console (in addition to the println() method)."
},
{
"code": null,
"e": 2303,
"s": 2148,
"text": "The print() − This method accepts a single value of any of the primitive or reference data types as a parameter and prints the given value on the console."
},
{
"code": null,
"e": 2458,
"s": 2303,
"text": "(double value or, a float value or, an int value or, a long value or, a char value, a boolean value or, a char array, a String or, an array or, an object)"
},
{
"code": null,
"e": 2646,
"s": 2458,
"text": "The printf() − This method accepts a local variable, a String value representing the required format, objects of variable number representing the arguments and, prints data as instructed."
},
{
"code": null,
"e": 2825,
"s": 2646,
"text": "public class PrintData {\n public static void main(String args[]) {\n System.out.print(\"Hello how are you\");\n System.out.printf(\" \"+\"welcome to Tutorialspoint\");\n }\n}"
},
{
"code": null,
"e": 2869,
"s": 2825,
"text": "Hello how are you Welcome to Tutorialspoint"
},
{
"code": null,
"e": 2954,
"s": 2869,
"text": "The Logger class of the log4j library provides methods to print data on the console."
},
{
"code": null,
"e": 3292,
"s": 2954,
"text": "<dependencies>\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-api</artifactId>\n <version>2.4</version>\n </dependency>\n <dependency>\n <groupId>org.apache.logging.log4j</groupId>\n <artifactId>log4j-core</artifactId>\n <version>2.4</version>\n </dependency>\n</dependencies>"
},
{
"code": null,
"e": 3530,
"s": 3292,
"text": "import java.util.logging.Logger;\npublic class PrintData{\n static Logger log = Logger.getLogger(PrintData.class.getName());\n public static void main(String[] args){\n log.info(\"Hello how are you Welcome to Tutorialspoint\");\n }\n}"
},
{
"code": null,
"e": 3629,
"s": 3530,
"text": "Jun 28, 2019 2:49:25 PM Mypackage.PrintData main\nINFO: Hello how are you Welcome to Tutorialspoint"
}
] |
String after processing backspace characters - GeeksforGeeks | 21 Jul, 2021
Given a string S containing letters and ‘#‘. The ‘#” represents a backspace. The task is to print the new string without ‘#‘.Examples:
Input : S = "abc#de#f#ghi#jklmn#op#"
Output : abdghjklmo
Input : S = "##geeks##for##geeks#"
Output : geefgeek
Approach: A simple approach to this problem by using deque is as follows:
Traverse the string S.
If any character except ‘#’ is found push it at back in deque.
if the character ‘#’ is found pop a character from back of deque.
Finally pop all elements from front of deque to make new string.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// CPP implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find new final Stringstring newString(string S){ deque<char> q; for (int i = 0; i < S.length(); ++i) { if (S[i] != '#') q.push_back(S[i]); else if (!q.empty()) q.pop_back(); } // build final string string ans = ""; while (!q.empty()) { ans += q.front(); q.pop_front(); } // return final string return ans;} // Driver programint main(){ string S = "##geeks##for##geeks#"; // function call to print required answer cout << newString(S); return 0;} // This code is contributed by Sanjit_Prasad
// Java implementation of above approachimport java.util.*;class GFG{ // Function to find new final Stringstatic String newString(String S){ Stack<Character> q = new Stack<Character>(); for (int i = 0; i < S.length(); ++i) { if (S.charAt(i) != '#') q.push(S.charAt(i)); else if (!q.isEmpty()) q.pop(); } // build final string String ans = ""; while (!q.isEmpty()) { ans += q.pop(); } // return final string String answer = ""; for(int j = ans.length() - 1; j >= 0; j--) { answer += ans.charAt(j); } return answer;} // Driver Codepublic static void main(String[] args){ String S = "##geeks##for##geeks#"; // function call to print // required answer System.out.println(newString(S));}} // This code is contributed// by prerna saini
# Python3 implementation of above approach # Function to find new final Stringdef newString(S): q = [] for i in range(0, len(S)): if S[i] != '#': q.append(S[i]) elif len(q) != 0: q.pop() # Build final string ans = "" while len(q) != 0: ans += q[0] q.pop(0) # return final string return ans # Driver Codeif __name__ == "__main__": S = "##geeks##for##geeks#" # Function call to print # required answer print(newString(S)) # This code is contributed by Rituraj Jain
// C# implementation of above approachusing System.Collections.Generic;using System; class GFG{ // Function to find new final Stringstatic String newString(String S){ Stack<Char> q = new Stack<Char>(); for (int i = 0; i < S.Length; ++i) { if (S[i] != '#') q.Push(S[i]); else if (q.Count!=0) q.Pop(); } // build final string String ans = ""; while (q.Count!=0) { ans += q.Pop(); } // return final string String answer = ""; for(int j = ans.Length - 1; j >= 0; j--) { answer += ans[j]; } return answer;} // Driver Codepublic static void Main(String []args){ String S = "##geeks##for##geeks#"; // function call to print // required answer Console.WriteLine(newString(S));}} // This code is contributed by 29AjayKumar
<script>// Javascript implementation of above approach // Function to find new final Stringfunction newString(S){ let q = []; for (let i = 0; i < S.length; ++i) { if (S[i] != '#') q.push(S[i]); else if (q.length!=0) q.pop(); } // build final string let ans = ""; while (q.length!=0) { ans += q.pop(); } // return final string let answer = ""; for(let j = ans.length - 1; j >= 0; j--) { answer += ans[j]; } return answer;} // Driver Codelet S = "##geeks##for##geeks#"; // function call to print// required answerdocument.write(newString(S)+"<br>"); // This code is contributed by rag2127</script>
geefgeek
Time Complexity: O(N), where N is the length of the String.
prerna saini
rituraj_jain
29AjayKumar
rag2127
cpp-deque
cpp-strings
deque
Queue
Strings
cpp-strings
Strings
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation)
Sliding Window Maximum (Maximum of all subarrays of size k)
Implement Stack using Queues
Applications of Queue Data Structure
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types | [
{
"code": null,
"e": 24893,
"s": 24865,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 25030,
"s": 24893,
"text": "Given a string S containing letters and ‘#‘. The ‘#” represents a backspace. The task is to print the new string without ‘#‘.Examples: "
},
{
"code": null,
"e": 25141,
"s": 25030,
"text": "Input : S = \"abc#de#f#ghi#jklmn#op#\"\nOutput : abdghjklmo\n\nInput : S = \"##geeks##for##geeks#\"\nOutput : geefgeek"
},
{
"code": null,
"e": 25218,
"s": 25143,
"text": "Approach: A simple approach to this problem by using deque is as follows: "
},
{
"code": null,
"e": 25241,
"s": 25218,
"text": "Traverse the string S."
},
{
"code": null,
"e": 25304,
"s": 25241,
"text": "If any character except ‘#’ is found push it at back in deque."
},
{
"code": null,
"e": 25370,
"s": 25304,
"text": "if the character ‘#’ is found pop a character from back of deque."
},
{
"code": null,
"e": 25435,
"s": 25370,
"text": "Finally pop all elements from front of deque to make new string."
},
{
"code": null,
"e": 25484,
"s": 25435,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 25488,
"s": 25484,
"text": "C++"
},
{
"code": null,
"e": 25493,
"s": 25488,
"text": "Java"
},
{
"code": null,
"e": 25501,
"s": 25493,
"text": "Python3"
},
{
"code": null,
"e": 25504,
"s": 25501,
"text": "C#"
},
{
"code": null,
"e": 25515,
"s": 25504,
"text": "Javascript"
},
{
"code": "// CPP implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find new final Stringstring newString(string S){ deque<char> q; for (int i = 0; i < S.length(); ++i) { if (S[i] != '#') q.push_back(S[i]); else if (!q.empty()) q.pop_back(); } // build final string string ans = \"\"; while (!q.empty()) { ans += q.front(); q.pop_front(); } // return final string return ans;} // Driver programint main(){ string S = \"##geeks##for##geeks#\"; // function call to print required answer cout << newString(S); return 0;} // This code is contributed by Sanjit_Prasad",
"e": 26201,
"s": 25515,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*;class GFG{ // Function to find new final Stringstatic String newString(String S){ Stack<Character> q = new Stack<Character>(); for (int i = 0; i < S.length(); ++i) { if (S.charAt(i) != '#') q.push(S.charAt(i)); else if (!q.isEmpty()) q.pop(); } // build final string String ans = \"\"; while (!q.isEmpty()) { ans += q.pop(); } // return final string String answer = \"\"; for(int j = ans.length() - 1; j >= 0; j--) { answer += ans.charAt(j); } return answer;} // Driver Codepublic static void main(String[] args){ String S = \"##geeks##for##geeks#\"; // function call to print // required answer System.out.println(newString(S));}} // This code is contributed// by prerna saini",
"e": 27044,
"s": 26201,
"text": null
},
{
"code": "# Python3 implementation of above approach # Function to find new final Stringdef newString(S): q = [] for i in range(0, len(S)): if S[i] != '#': q.append(S[i]) elif len(q) != 0: q.pop() # Build final string ans = \"\" while len(q) != 0: ans += q[0] q.pop(0) # return final string return ans # Driver Codeif __name__ == \"__main__\": S = \"##geeks##for##geeks#\" # Function call to print # required answer print(newString(S)) # This code is contributed by Rituraj Jain",
"e": 27606,
"s": 27044,
"text": null
},
{
"code": "// C# implementation of above approachusing System.Collections.Generic;using System; class GFG{ // Function to find new final Stringstatic String newString(String S){ Stack<Char> q = new Stack<Char>(); for (int i = 0; i < S.Length; ++i) { if (S[i] != '#') q.Push(S[i]); else if (q.Count!=0) q.Pop(); } // build final string String ans = \"\"; while (q.Count!=0) { ans += q.Pop(); } // return final string String answer = \"\"; for(int j = ans.Length - 1; j >= 0; j--) { answer += ans[j]; } return answer;} // Driver Codepublic static void Main(String []args){ String S = \"##geeks##for##geeks#\"; // function call to print // required answer Console.WriteLine(newString(S));}} // This code is contributed by 29AjayKumar",
"e": 28432,
"s": 27606,
"text": null
},
{
"code": "<script>// Javascript implementation of above approach // Function to find new final Stringfunction newString(S){ let q = []; for (let i = 0; i < S.length; ++i) { if (S[i] != '#') q.push(S[i]); else if (q.length!=0) q.pop(); } // build final string let ans = \"\"; while (q.length!=0) { ans += q.pop(); } // return final string let answer = \"\"; for(let j = ans.length - 1; j >= 0; j--) { answer += ans[j]; } return answer;} // Driver Codelet S = \"##geeks##for##geeks#\"; // function call to print// required answerdocument.write(newString(S)+\"<br>\"); // This code is contributed by rag2127</script>",
"e": 29135,
"s": 28432,
"text": null
},
{
"code": null,
"e": 29144,
"s": 29135,
"text": "geefgeek"
},
{
"code": null,
"e": 29207,
"s": 29146,
"text": "Time Complexity: O(N), where N is the length of the String. "
},
{
"code": null,
"e": 29220,
"s": 29207,
"text": "prerna saini"
},
{
"code": null,
"e": 29233,
"s": 29220,
"text": "rituraj_jain"
},
{
"code": null,
"e": 29245,
"s": 29233,
"text": "29AjayKumar"
},
{
"code": null,
"e": 29253,
"s": 29245,
"text": "rag2127"
},
{
"code": null,
"e": 29263,
"s": 29253,
"text": "cpp-deque"
},
{
"code": null,
"e": 29275,
"s": 29263,
"text": "cpp-strings"
},
{
"code": null,
"e": 29281,
"s": 29275,
"text": "deque"
},
{
"code": null,
"e": 29287,
"s": 29281,
"text": "Queue"
},
{
"code": null,
"e": 29295,
"s": 29287,
"text": "Strings"
},
{
"code": null,
"e": 29307,
"s": 29295,
"text": "cpp-strings"
},
{
"code": null,
"e": 29315,
"s": 29307,
"text": "Strings"
},
{
"code": null,
"e": 29321,
"s": 29315,
"text": "Queue"
},
{
"code": null,
"e": 29419,
"s": 29321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29428,
"s": 29419,
"text": "Comments"
},
{
"code": null,
"e": 29441,
"s": 29428,
"text": "Old Comments"
},
{
"code": null,
"e": 29476,
"s": 29441,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 29539,
"s": 29476,
"text": "Circular Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 29599,
"s": 29539,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
},
{
"code": null,
"e": 29628,
"s": 29599,
"text": "Implement Stack using Queues"
},
{
"code": null,
"e": 29665,
"s": 29628,
"text": "Applications of Queue Data Structure"
},
{
"code": null,
"e": 29690,
"s": 29665,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29736,
"s": 29690,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 29770,
"s": 29736,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 29830,
"s": 29770,
"text": "Write a program to print all permutations of a given string"
}
] |
What is the AddRange method in C# lists? | AddRange method in lists adds an entire collection of elements. Let us see an example −
Firstly, set a list in C# and add elements −
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
Now set an array of elements to be added to the list −
// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;
Use the AddRange() method add the entire collection of elements in the list −
list.AddRange(arr);
Now let us see the complete code and display the list −
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;
list.AddRange(arr);
foreach (int val in list) {
Console.WriteLine(val);
}
}
} | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "AddRange method in lists adds an entire collection of elements. Let us see an example −"
},
{
"code": null,
"e": 1195,
"s": 1150,
"text": "Firstly, set a list in C# and add elements −"
},
{
"code": null,
"e": 1289,
"s": 1195,
"text": "List<int> list = new List<int>();\nlist.Add(100);\nlist.Add(200);\nlist.Add(300);\nlist.Add(400);"
},
{
"code": null,
"e": 1344,
"s": 1289,
"text": "Now set an array of elements to be added to the list −"
},
{
"code": null,
"e": 1447,
"s": 1344,
"text": "// array of 4 elements\nint[] arr = new int[4];\narr[0] = 500;\narr[1] = 600;\narr[2] = 700;\narr[3] = 800;"
},
{
"code": null,
"e": 1525,
"s": 1447,
"text": "Use the AddRange() method add the entire collection of elements in the list −"
},
{
"code": null,
"e": 1545,
"s": 1525,
"text": "list.AddRange(arr);"
},
{
"code": null,
"e": 1601,
"s": 1545,
"text": "Now let us see the complete code and display the list −"
},
{
"code": null,
"e": 2064,
"s": 1601,
"text": "using System;\nusing System.Collections.Generic;\n\nclass Demo {\n static void Main() {\n List<int> list = new List<int>();\n list.Add(100);\n list.Add(200);\n list.Add(300);\n list.Add(400);\n\n // array of 4 elements\n int[] arr = new int[4];\n arr[0] = 500;\n arr[1] = 600;\n arr[2] = 700;\n arr[3] = 800;\n \n list.AddRange(arr);\n\n foreach (int val in list) {\n Console.WriteLine(val);\n }\n }\n}"
}
] |
Artificial Neural Network Implementation using NumPy and Classification of the Fruits360 Image Dataset | by Ahmed Gad | Towards Data Science | This tutorial builds artificial neural network in Python using NumPy from scratch in order to do an image classification application for the Fruits360 dataset. Everything (i.e. images and source codes) used in this tutorial, rather than the color Fruits360 images, are exclusive rights for my book cited as “Ahmed Fawzy Gad ‘Practical Computer Vision Applications Using Deep Learning with CNNs’. Dec. 2018, Apress, 978–1–4842–4167–7 “. The book is available at Springer at this link: https://springer.com/us/book/9781484241660.
The source code used in this tutorial is available in my GitHub page here: https://github.com/ahmedfgad/NumPyANN
The example being used in the book is about classification of the Fruits360 image dataset using artificial neural network (ANN). The example does not assume that the reader neither extracted the features nor implemented the ANN as it discusses what the suitable set of features for use are and also how to implement the ANN in NumPy from scratch. The Fruits360 dataset has 60 classes of fruits such as apple, guava, avocado, banana, cherry, dates, kiwi, peach, and more. For making things simpler, it just works on 4 selected classes which are apple Braeburn, lemon Meyer, mango, and raspberry. Each class has around 491 images for training and another 162 for testing. The image size is 100x100 pixels.
Feature Extraction
The book starts by selecting the suitable set of features in order to achieve the highest classification accuracy. Based on the sample images from the 4 selected classes shown below, it seems that their color is different. This is why the color features are suitable ones for use in this task.
The RGB color space does not isolates color information from other types of information such as illumination. Thus, if the RGB is used for representing the images, the 3 channels will be involved in the calculations. For such a reason, it is better to use a color space that isolates the color information into a single channel such as HSV. The color channel in this case is the hue channel (H). The next figure shows the hue channel of the 4 samples presented previously. We can notice how the hue value for each image is different from the other images.
The hue channel size is still 100x100. If the entire channel is applied to the ANN, then the input layer will have 10,000 neurons. The network is still huge. In order to reduce the amounts of data being used, we can use the histogram for representing the hue channel. The histogram will have 360 bins reflecting the number of possible values for the hue value. Here are the histograms for the 4 sample images. Using a 360 bins histogram for the hue channel, it seems that every fruit votes to some specific bins of the histogram. There is less overlap among the different classes compared to using any channel from the RGB color space. For example, the bins in the apple histogram range from 0 to 10 compared to mango with its bins range from 90 to 110. The margin between each of the classes makes it easier to reduce the ambiguity in classification and thus increasing the prediction accuracy.
Here is the code that calculates the hue channel histogram from the 4 images.
import numpy import skimage.io, skimage.color import matplotlib.pyplot raspberry = skimage.io.imread(fname="raspberry.jpg", as_grey=False) apple = skimage.io.imread(fname="apple.jpg", as_grey=False) mango = skimage.io.imread(fname="mango.jpg", as_grey=False) lemon = skimage.io.imread(fname="lemon.jpg", as_grey=False) apple_hsv = skimage.color.rgb2hsv(rgb=apple) mango_hsv = skimage.color.rgb2hsv(rgb=mango) raspberry_hsv = skimage.color.rgb2hsv(rgb=raspberry) lemon_hsv = skimage.color.rgb2hsv(rgb=lemon) fruits = ["apple", "raspberry", "mango", "lemon"] hsv_fruits_data = [apple_hsv, raspberry_hsv, mango_hsv, lemon_hsv] idx = 0 for hsv_fruit_data in hsv_fruits_data: fruit = fruits[idx] hist = numpy.histogram(a=hsv_fruit_data[:, :, 0], bins=360) matplotlib.pyplot.bar(left=numpy.arange(360), height=hist[0]) matplotlib.pyplot.savefig(fruit+"-hue-histogram.jpg", bbox_inches="tight") matplotlib.pyplot.close("all") idx = idx + 1
By looping through all images in the 4 image classes used, we can extract the features from all images. The next code does this. According to the number of images in the 4 classes (1,962) and the feature vector length extracted from each image (360), a NumPy array of zeros is created and saved in the dataset_features variable. In order to store the class label for each image, another NumPy array named outputs is created. The class label for apple is 0, lemon is 1, mango is 2, and raspberry is 3. The code expects that it runs in a root directory in which there are 4 folders named according to the fruits names listed in the list named fruits. It loops through all images in all folders, extract the hue histogram from each of them, assign each image a class label, and finally saves the extracted features and the class labels using the pickle library. You can also use NumPy for saving the resultant NumPy arrays rather than pickle.
import numpyimport skimage.io, skimage.color, skimage.featureimport osimport picklefruits = ["apple", "raspberry", "mango", "lemon"] #492+490+490+490=1,962dataset_features = numpy.zeros(shape=(1962, 360))outputs = numpy.zeros(shape=(1962))idx = 0class_label = 0for fruit_dir in fruits: curr_dir = os.path.join(os.path.sep, fruit_dir) all_imgs = os.listdir(os.getcwd()+curr_dir) for img_file in all_imgs: fruit_data = skimage.io.imread(fname=os.getcwd()+curr_dir+img_file, as_grey=False) fruit_data_hsv = skimage.color.rgb2hsv(rgb=fruit_data) hist = numpy.histogram(a=fruit_data_hsv[:, :, 0], bins=360) dataset_features[idx, :] = hist[0] outputs[idx] = class_label idx = idx + 1 class_label = class_label + 1with open("dataset_features.pkl", "wb") as f: pickle.dump("dataset_features.pkl", f)with open("outputs.pkl", "wb") as f: pickle.dump(outputs, f)
Currently, each image is represented using a feature vector of 360 elements. Such elements are filtered in order to just keep the most relevant elements for differentiating the 4 classes. The reduced feature vector length is 102 rather than 360. Using less elements helps to do faster training than before. The dataset_features variable shape will be 1962x102. You can read more in the book for reducing the feature vector length.
Up to this point, the training data (features and class labels) are ready. Next is implement the ANN using NumPy.
ANN Implementation
The next figure visualizes the target ANN structure. There is an input layer with 102 inputs, 2 hidden layers with 150 and 60 neurons, and an output layer with 4 outputs (one for each fruit class).
The input vector at any layer is multiplied (matrix multiplication) by the weights matrix connecting it to the next layer to produce an output vector. Such an output vector is again multiplied by the weights matrix connecting its layer to the next layer. The process continues until reaching the output layer. Summary of the matrix multiplications is in the next figure.
The input vector of size 1x102 is to be multiplied by the weights matrix of the first hidden layer of size 102x150. Remember it is matrix multiplication. Thus, the output array shape is 1x150. Such output is then used as the input to the second hidden layer, where it is multiplied by a weights matrix of size 150x60. The result size is 1x60. Finally, such output is multiplied by the weights between the second hidden layer and the output layer of size 60x4. The result finally has a size of 1x4. Every element in such resulted vector refers to an output class. The input sample is labeled according to the class with the highest score.
The Python code for implementing such multiplications is in listed below.
import numpyimport pickledef sigmoid(inpt): return 1.0 / (1 + numpy.exp(-1 * inpt))f = open("dataset_features.pkl", "rb")data_inputs2 = pickle.load(f)f.close()features_STDs = numpy.std(a=data_inputs2, axis=0)data_inputs = data_inputs2[:, features_STDs > 50]f = open("outputs.pkl", "rb")data_outputs = pickle.load(f)f.close()HL1_neurons = 150input_HL1_weights = numpy.random.uniform(low=-0.1, high=0.1, size=(data_inputs.shape[1], HL1_neurons))HL2_neurons = 60HL1_HL2_weights = numpy.random.uniform(low=-0.1, high=0.1, size=(HL1_neurons, HL2_neurons))output_neurons = 4HL2_output_weights = numpy.random.uniform(low=-0.1, high=0.1, size=(HL2_neurons, output_neurons))H1_outputs = numpy.matmul(a=data_inputs[0, :], b=input_HL1_weights)H1_outputs = sigmoid(H1_outputs)H2_outputs = numpy.matmul(a=H1_outputs, b=HL1_HL2_weights)H2_outputs = sigmoid(H2_outputs)out_otuputs = numpy.matmul(a=H2_outputs, b=HL2_output_weights)predicted_label = numpy.where(out_otuputs == numpy.max(out_otuputs))[0][0]print("Predicted class : ", predicted_label)
After reading the previously saved features and their output labels and filtering the features, the weights matrices of the layers are defined. They are randomly given values from -0.1 to 0.1. For example, the variable “input_HL1_weights” holds the weights matrix between the input layer and the first hidden layer. Size of such matrix is defined according to the number of feature elements and the number of neurons in the hidden layer.
After creating the weights matrices, next is to apply matrix multiplications. For example, the variable “H1_outputs” holds the output of multiplying the feature vector of a given sample to the weights matrix between the input layer and the first hidden layer.
Usually, an activation function is applied to the outputs of each hidden layer to create a non-linear relationship between the inputs and the outputs. For example, outputs of the matrix multiplications are applied to the sigmoid activation function.
After generating the output layer outputs, prediction takes place. The predicted class label is saved into the “predicted_label” variable. Such steps are repeated for each input sample. The complete code that works across all samples is given below.
import numpyimport pickledef sigmoid(inpt): return 1.0 / (1 + numpy.exp(-1 * inpt))def relu(inpt): result = inpt result[inpt < 0] = 0 return resultdef update_weights(weights, learning_rate): new_weights = weights - learning_rate * weights return new_weightsdef train_network(num_iterations, weights, data_inputs, data_outputs, learning_rate, activation="relu"): for iteration in range(num_iterations): print("Itreation ", iteration) for sample_idx in range(data_inputs.shape[0]): r1 = data_inputs[sample_idx, :] for idx in range(len(weights) - 1): curr_weights = weights[idx] r1 = numpy.matmul(a=r1, b=curr_weights) if activation == "relu": r1 = relu(r1) elif activation == "sigmoid": r1 = sigmoid(r1) curr_weights = weights[-1] r1 = numpy.matmul(a=r1, b=curr_weights) predicted_label = numpy.where(r1 == numpy.max(r1))[0][0] desired_label = data_outputs[sample_idx] if predicted_label != desired_label: weights = update_weights(weights, learning_rate=0.001) return weightsdef predict_outputs(weights, data_inputs, activation="relu"): predictions = numpy.zeros(shape=(data_inputs.shape[0])) for sample_idx in range(data_inputs.shape[0]): r1 = data_inputs[sample_idx, :] for curr_weights in weights: r1 = numpy.matmul(a=r1, b=curr_weights) if activation == "relu": r1 = relu(r1) elif activation == "sigmoid": r1 = sigmoid(r1) predicted_label = numpy.where(r1 == numpy.max(r1))[0][0] predictions[sample_idx] = predicted_label return predictionsf = open("dataset_features.pkl", "rb")data_inputs2 = pickle.load(f)f.close()features_STDs = numpy.std(a=data_inputs2, axis=0)data_inputs = data_inputs2[:, features_STDs > 50]f = open("outputs.pkl", "rb")data_outputs = pickle.load(f)f.close()HL1_neurons = 150input_HL1_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(data_inputs.shape[1], HL1_neurons))HL2_neurons = 60HL1_HL2_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(HL1_neurons,HL2_neurons))output_neurons = 4HL2_output_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(HL2_neurons,output_neurons))weights = numpy.array([input_HL1_weights, HL1_HL2_weights, HL2_output_weights])weights = train_network(num_iterations=10, weights=weights, data_inputs=data_inputs, data_outputs=data_outputs, learning_rate=0.01, activation="relu")predictions = predict_outputs(weights, data_inputs)num_flase = numpy.where(predictions != data_outputs)[0]print("num_flase ", num_flase.size)
The “weights” variables hold all weights across the entire network. Based on the size of each weight matrix, the network structure is dynamically specified. For example, if the size of the “input_HL1_weights” variable is 102x80, then we can deduce that the first hidden layer has 80 neurons.
The “train_network” is the core function as it trains the network by looping through all samples. For each sample, the steps discussed in listing 3–6 are applied. It accepts the number of training iterations, feature, output labels, weights, learning rate, and the activation function. There are two options for the activation functions which are either ReLU or sigmoid. ReLU is a thresholding function that returns the same input as long as it is greater than zero. Otherwise, it returns zero.
If the network made a false prediction for a given sample, then weights are updated using the “update_weights” function. No optimization algorithm is used to update the weights. Weights are simply updated according to the learning rate. The accuracy does not exceed 45%. For achieving better accuracy, an optimization algorithm is used for updating the weights. For example, you can find the gradient descent technique in the ANN implementation of the scikit-learn library.
In my book, you can find a guide for optimizing the ANN weights using the genetic algorithm (GA) optimization technique which increases the classification accuracy. You can read more about GA from the following resources I prepared:
Introduction to Optimization with Genetic Algorithm
https://www.linkedin.com/pulse/introduction-optimization-genetic-algorithm-ahmed-gad/
https://www.kdnuggets.com/2018/03/introduction-optimization-with-genetic-algorithm.html
https://towardsdatascience.com/introduction-to-optimization-with-genetic-algorithm-2f5001d9964b
https://www.springer.com/us/book/9781484241660
Genetic Algorithm (GA) Optimization — Step-by-Step Example
https://www.slideshare.net/AhmedGadFCIT/genetic-algorithm-ga-optimization-stepbystep-example
Genetic Algorithm Implementation in Python | [
{
"code": null,
"e": 700,
"s": 172,
"text": "This tutorial builds artificial neural network in Python using NumPy from scratch in order to do an image classification application for the Fruits360 dataset. Everything (i.e. images and source codes) used in this tutorial, rather than the color Fruits360 images, are exclusive rights for my book cited as “Ahmed Fawzy Gad ‘Practical Computer Vision Applications Using Deep Learning with CNNs’. Dec. 2018, Apress, 978–1–4842–4167–7 “. The book is available at Springer at this link: https://springer.com/us/book/9781484241660."
},
{
"code": null,
"e": 813,
"s": 700,
"text": "The source code used in this tutorial is available in my GitHub page here: https://github.com/ahmedfgad/NumPyANN"
},
{
"code": null,
"e": 1517,
"s": 813,
"text": "The example being used in the book is about classification of the Fruits360 image dataset using artificial neural network (ANN). The example does not assume that the reader neither extracted the features nor implemented the ANN as it discusses what the suitable set of features for use are and also how to implement the ANN in NumPy from scratch. The Fruits360 dataset has 60 classes of fruits such as apple, guava, avocado, banana, cherry, dates, kiwi, peach, and more. For making things simpler, it just works on 4 selected classes which are apple Braeburn, lemon Meyer, mango, and raspberry. Each class has around 491 images for training and another 162 for testing. The image size is 100x100 pixels."
},
{
"code": null,
"e": 1536,
"s": 1517,
"text": "Feature Extraction"
},
{
"code": null,
"e": 1830,
"s": 1536,
"text": "The book starts by selecting the suitable set of features in order to achieve the highest classification accuracy. Based on the sample images from the 4 selected classes shown below, it seems that their color is different. This is why the color features are suitable ones for use in this task."
},
{
"code": null,
"e": 2386,
"s": 1830,
"text": "The RGB color space does not isolates color information from other types of information such as illumination. Thus, if the RGB is used for representing the images, the 3 channels will be involved in the calculations. For such a reason, it is better to use a color space that isolates the color information into a single channel such as HSV. The color channel in this case is the hue channel (H). The next figure shows the hue channel of the 4 samples presented previously. We can notice how the hue value for each image is different from the other images."
},
{
"code": null,
"e": 3282,
"s": 2386,
"text": "The hue channel size is still 100x100. If the entire channel is applied to the ANN, then the input layer will have 10,000 neurons. The network is still huge. In order to reduce the amounts of data being used, we can use the histogram for representing the hue channel. The histogram will have 360 bins reflecting the number of possible values for the hue value. Here are the histograms for the 4 sample images. Using a 360 bins histogram for the hue channel, it seems that every fruit votes to some specific bins of the histogram. There is less overlap among the different classes compared to using any channel from the RGB color space. For example, the bins in the apple histogram range from 0 to 10 compared to mango with its bins range from 90 to 110. The margin between each of the classes makes it easier to reduce the ambiguity in classification and thus increasing the prediction accuracy."
},
{
"code": null,
"e": 3360,
"s": 3282,
"text": "Here is the code that calculates the hue channel histogram from the 4 images."
},
{
"code": null,
"e": 4320,
"s": 3360,
"text": "import numpy import skimage.io, skimage.color import matplotlib.pyplot raspberry = skimage.io.imread(fname=\"raspberry.jpg\", as_grey=False) apple = skimage.io.imread(fname=\"apple.jpg\", as_grey=False) mango = skimage.io.imread(fname=\"mango.jpg\", as_grey=False) lemon = skimage.io.imread(fname=\"lemon.jpg\", as_grey=False) apple_hsv = skimage.color.rgb2hsv(rgb=apple) mango_hsv = skimage.color.rgb2hsv(rgb=mango) raspberry_hsv = skimage.color.rgb2hsv(rgb=raspberry) lemon_hsv = skimage.color.rgb2hsv(rgb=lemon) fruits = [\"apple\", \"raspberry\", \"mango\", \"lemon\"] hsv_fruits_data = [apple_hsv, raspberry_hsv, mango_hsv, lemon_hsv] idx = 0 for hsv_fruit_data in hsv_fruits_data: fruit = fruits[idx] hist = numpy.histogram(a=hsv_fruit_data[:, :, 0], bins=360) matplotlib.pyplot.bar(left=numpy.arange(360), height=hist[0]) matplotlib.pyplot.savefig(fruit+\"-hue-histogram.jpg\", bbox_inches=\"tight\") matplotlib.pyplot.close(\"all\") idx = idx + 1"
},
{
"code": null,
"e": 5260,
"s": 4320,
"text": "By looping through all images in the 4 image classes used, we can extract the features from all images. The next code does this. According to the number of images in the 4 classes (1,962) and the feature vector length extracted from each image (360), a NumPy array of zeros is created and saved in the dataset_features variable. In order to store the class label for each image, another NumPy array named outputs is created. The class label for apple is 0, lemon is 1, mango is 2, and raspberry is 3. The code expects that it runs in a root directory in which there are 4 folders named according to the fruits names listed in the list named fruits. It loops through all images in all folders, extract the hue histogram from each of them, assign each image a class label, and finally saves the extracted features and the class labels using the pickle library. You can also use NumPy for saving the resultant NumPy arrays rather than pickle."
},
{
"code": null,
"e": 6172,
"s": 5260,
"text": "import numpyimport skimage.io, skimage.color, skimage.featureimport osimport picklefruits = [\"apple\", \"raspberry\", \"mango\", \"lemon\"] #492+490+490+490=1,962dataset_features = numpy.zeros(shape=(1962, 360))outputs = numpy.zeros(shape=(1962))idx = 0class_label = 0for fruit_dir in fruits: curr_dir = os.path.join(os.path.sep, fruit_dir) all_imgs = os.listdir(os.getcwd()+curr_dir) for img_file in all_imgs: fruit_data = skimage.io.imread(fname=os.getcwd()+curr_dir+img_file, as_grey=False) fruit_data_hsv = skimage.color.rgb2hsv(rgb=fruit_data) hist = numpy.histogram(a=fruit_data_hsv[:, :, 0], bins=360) dataset_features[idx, :] = hist[0] outputs[idx] = class_label idx = idx + 1 class_label = class_label + 1with open(\"dataset_features.pkl\", \"wb\") as f: pickle.dump(\"dataset_features.pkl\", f)with open(\"outputs.pkl\", \"wb\") as f: pickle.dump(outputs, f)"
},
{
"code": null,
"e": 6603,
"s": 6172,
"text": "Currently, each image is represented using a feature vector of 360 elements. Such elements are filtered in order to just keep the most relevant elements for differentiating the 4 classes. The reduced feature vector length is 102 rather than 360. Using less elements helps to do faster training than before. The dataset_features variable shape will be 1962x102. You can read more in the book for reducing the feature vector length."
},
{
"code": null,
"e": 6717,
"s": 6603,
"text": "Up to this point, the training data (features and class labels) are ready. Next is implement the ANN using NumPy."
},
{
"code": null,
"e": 6736,
"s": 6717,
"text": "ANN Implementation"
},
{
"code": null,
"e": 6934,
"s": 6736,
"text": "The next figure visualizes the target ANN structure. There is an input layer with 102 inputs, 2 hidden layers with 150 and 60 neurons, and an output layer with 4 outputs (one for each fruit class)."
},
{
"code": null,
"e": 7305,
"s": 6934,
"text": "The input vector at any layer is multiplied (matrix multiplication) by the weights matrix connecting it to the next layer to produce an output vector. Such an output vector is again multiplied by the weights matrix connecting its layer to the next layer. The process continues until reaching the output layer. Summary of the matrix multiplications is in the next figure."
},
{
"code": null,
"e": 7943,
"s": 7305,
"text": "The input vector of size 1x102 is to be multiplied by the weights matrix of the first hidden layer of size 102x150. Remember it is matrix multiplication. Thus, the output array shape is 1x150. Such output is then used as the input to the second hidden layer, where it is multiplied by a weights matrix of size 150x60. The result size is 1x60. Finally, such output is multiplied by the weights between the second hidden layer and the output layer of size 60x4. The result finally has a size of 1x4. Every element in such resulted vector refers to an output class. The input sample is labeled according to the class with the highest score."
},
{
"code": null,
"e": 8017,
"s": 7943,
"text": "The Python code for implementing such multiplications is in listed below."
},
{
"code": null,
"e": 9055,
"s": 8017,
"text": "import numpyimport pickledef sigmoid(inpt): return 1.0 / (1 + numpy.exp(-1 * inpt))f = open(\"dataset_features.pkl\", \"rb\")data_inputs2 = pickle.load(f)f.close()features_STDs = numpy.std(a=data_inputs2, axis=0)data_inputs = data_inputs2[:, features_STDs > 50]f = open(\"outputs.pkl\", \"rb\")data_outputs = pickle.load(f)f.close()HL1_neurons = 150input_HL1_weights = numpy.random.uniform(low=-0.1, high=0.1, size=(data_inputs.shape[1], HL1_neurons))HL2_neurons = 60HL1_HL2_weights = numpy.random.uniform(low=-0.1, high=0.1, size=(HL1_neurons, HL2_neurons))output_neurons = 4HL2_output_weights = numpy.random.uniform(low=-0.1, high=0.1, size=(HL2_neurons, output_neurons))H1_outputs = numpy.matmul(a=data_inputs[0, :], b=input_HL1_weights)H1_outputs = sigmoid(H1_outputs)H2_outputs = numpy.matmul(a=H1_outputs, b=HL1_HL2_weights)H2_outputs = sigmoid(H2_outputs)out_otuputs = numpy.matmul(a=H2_outputs, b=HL2_output_weights)predicted_label = numpy.where(out_otuputs == numpy.max(out_otuputs))[0][0]print(\"Predicted class : \", predicted_label)"
},
{
"code": null,
"e": 9493,
"s": 9055,
"text": "After reading the previously saved features and their output labels and filtering the features, the weights matrices of the layers are defined. They are randomly given values from -0.1 to 0.1. For example, the variable “input_HL1_weights” holds the weights matrix between the input layer and the first hidden layer. Size of such matrix is defined according to the number of feature elements and the number of neurons in the hidden layer."
},
{
"code": null,
"e": 9753,
"s": 9493,
"text": "After creating the weights matrices, next is to apply matrix multiplications. For example, the variable “H1_outputs” holds the output of multiplying the feature vector of a given sample to the weights matrix between the input layer and the first hidden layer."
},
{
"code": null,
"e": 10003,
"s": 9753,
"text": "Usually, an activation function is applied to the outputs of each hidden layer to create a non-linear relationship between the inputs and the outputs. For example, outputs of the matrix multiplications are applied to the sigmoid activation function."
},
{
"code": null,
"e": 10253,
"s": 10003,
"text": "After generating the output layer outputs, prediction takes place. The predicted class label is saved into the “predicted_label” variable. Such steps are repeated for each input sample. The complete code that works across all samples is given below."
},
{
"code": null,
"e": 13130,
"s": 10253,
"text": "import numpyimport pickledef sigmoid(inpt): return 1.0 / (1 + numpy.exp(-1 * inpt))def relu(inpt): result = inpt result[inpt < 0] = 0 return resultdef update_weights(weights, learning_rate): new_weights = weights - learning_rate * weights return new_weightsdef train_network(num_iterations, weights, data_inputs, data_outputs, learning_rate, activation=\"relu\"): for iteration in range(num_iterations): print(\"Itreation \", iteration) for sample_idx in range(data_inputs.shape[0]): r1 = data_inputs[sample_idx, :] for idx in range(len(weights) - 1): curr_weights = weights[idx] r1 = numpy.matmul(a=r1, b=curr_weights) if activation == \"relu\": r1 = relu(r1) elif activation == \"sigmoid\": r1 = sigmoid(r1) curr_weights = weights[-1] r1 = numpy.matmul(a=r1, b=curr_weights) predicted_label = numpy.where(r1 == numpy.max(r1))[0][0] desired_label = data_outputs[sample_idx] if predicted_label != desired_label: weights = update_weights(weights, learning_rate=0.001) return weightsdef predict_outputs(weights, data_inputs, activation=\"relu\"): predictions = numpy.zeros(shape=(data_inputs.shape[0])) for sample_idx in range(data_inputs.shape[0]): r1 = data_inputs[sample_idx, :] for curr_weights in weights: r1 = numpy.matmul(a=r1, b=curr_weights) if activation == \"relu\": r1 = relu(r1) elif activation == \"sigmoid\": r1 = sigmoid(r1) predicted_label = numpy.where(r1 == numpy.max(r1))[0][0] predictions[sample_idx] = predicted_label return predictionsf = open(\"dataset_features.pkl\", \"rb\")data_inputs2 = pickle.load(f)f.close()features_STDs = numpy.std(a=data_inputs2, axis=0)data_inputs = data_inputs2[:, features_STDs > 50]f = open(\"outputs.pkl\", \"rb\")data_outputs = pickle.load(f)f.close()HL1_neurons = 150input_HL1_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(data_inputs.shape[1], HL1_neurons))HL2_neurons = 60HL1_HL2_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(HL1_neurons,HL2_neurons))output_neurons = 4HL2_output_weights = numpy.random.uniform(low=-0.1, high=0.1,size=(HL2_neurons,output_neurons))weights = numpy.array([input_HL1_weights, HL1_HL2_weights, HL2_output_weights])weights = train_network(num_iterations=10, weights=weights, data_inputs=data_inputs, data_outputs=data_outputs, learning_rate=0.01, activation=\"relu\")predictions = predict_outputs(weights, data_inputs)num_flase = numpy.where(predictions != data_outputs)[0]print(\"num_flase \", num_flase.size)"
},
{
"code": null,
"e": 13422,
"s": 13130,
"text": "The “weights” variables hold all weights across the entire network. Based on the size of each weight matrix, the network structure is dynamically specified. For example, if the size of the “input_HL1_weights” variable is 102x80, then we can deduce that the first hidden layer has 80 neurons."
},
{
"code": null,
"e": 13917,
"s": 13422,
"text": "The “train_network” is the core function as it trains the network by looping through all samples. For each sample, the steps discussed in listing 3–6 are applied. It accepts the number of training iterations, feature, output labels, weights, learning rate, and the activation function. There are two options for the activation functions which are either ReLU or sigmoid. ReLU is a thresholding function that returns the same input as long as it is greater than zero. Otherwise, it returns zero."
},
{
"code": null,
"e": 14391,
"s": 13917,
"text": "If the network made a false prediction for a given sample, then weights are updated using the “update_weights” function. No optimization algorithm is used to update the weights. Weights are simply updated according to the learning rate. The accuracy does not exceed 45%. For achieving better accuracy, an optimization algorithm is used for updating the weights. For example, you can find the gradient descent technique in the ANN implementation of the scikit-learn library."
},
{
"code": null,
"e": 14624,
"s": 14391,
"text": "In my book, you can find a guide for optimizing the ANN weights using the genetic algorithm (GA) optimization technique which increases the classification accuracy. You can read more about GA from the following resources I prepared:"
},
{
"code": null,
"e": 14676,
"s": 14624,
"text": "Introduction to Optimization with Genetic Algorithm"
},
{
"code": null,
"e": 14762,
"s": 14676,
"text": "https://www.linkedin.com/pulse/introduction-optimization-genetic-algorithm-ahmed-gad/"
},
{
"code": null,
"e": 14850,
"s": 14762,
"text": "https://www.kdnuggets.com/2018/03/introduction-optimization-with-genetic-algorithm.html"
},
{
"code": null,
"e": 14946,
"s": 14850,
"text": "https://towardsdatascience.com/introduction-to-optimization-with-genetic-algorithm-2f5001d9964b"
},
{
"code": null,
"e": 14993,
"s": 14946,
"text": "https://www.springer.com/us/book/9781484241660"
},
{
"code": null,
"e": 15052,
"s": 14993,
"text": "Genetic Algorithm (GA) Optimization — Step-by-Step Example"
},
{
"code": null,
"e": 15145,
"s": 15052,
"text": "https://www.slideshare.net/AhmedGadFCIT/genetic-algorithm-ga-optimization-stepbystep-example"
}
] |
jQWidgets jqxNavigationBar initContent Property - GeeksforGeeks | 29 Oct, 2021
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxNavigationBar is used for representing a jQuery widget that has header and content sections. On clicking over the header, the content will be expanded or collapsed accordingly.
The initContent property is used as a callback function that is called when an item’s content needs to be initialized. Here the index argument shows which item is initialized.
Syntax:
Set the initContent property:
$("Selector").jqxNavigationBar({
initContent: function (index) {
$("#jqxButton").jqxButton({
$('#jqxbutton_for_initContent')
.on('click', function () {
$('#jqx_Navigation_Bar')
.jqxNavigationBar('disable');
});
});
}
});
Return the initContent property:
var initContent =
$('Selector').jqxNavigationBar('initContent');
Linked Files: Download jQWidgets from the given link. In the HTML file, locate the script files in the downloaded folder.
<link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqxexpander.js”></script><script type=”text/javascript” src=”jqwidgets/jqxnavigationbar.js”></script>
Example: The below example illustrates the jQWidgets jqxNavigationBar initContent property used to disable the navigation bar.
HTML
<!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="jqwidgets/styles/jqx.base.css" type="text/css"/> <script type="text/javascript" src="scripts/jquery.js"> </script> <script type="text/javascript" src="jqwidgets/jqxcore.js"> </script> <script type="text/javascript" src="jqwidgets/jqxexpander.js"> </script> <script type="text/javascript" src="jqwidgets/jqxnavigationbar.js"> </script></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> jQWidgets jqxNavigationBar initContent Property </h3> <div id="jqx_Navigation_Bar" style="margin: 25px;" align="left"> <div>First Header</div> <div> <h8>Content for the first header</h8> <ul> <li>GFG</li> <li>CSE</li> </ul> </div> <div> Second Header</div> <div> <input type="button" style="margin: 29px;" id="jqxbutton_for_initContent" value="Disable"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("#jqx_Navigation_Bar"). jqxNavigationBar({ width: 250, height: 132, initContent: function (index) { if (index === 0) { $('#jqxbutton_for_initContent'). on('click', function () { $('#jqx_Navigation_Bar'). jqxNavigationBar( 'disable'); }); } } }); $("#jqxbutton_for_initContent"). jqxButton({ width: 100, }); }); </script> </center></body> </html>
Output:
Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxnavigationbar/jquery-navigationbar-api.htm?search=
jQuery-jQWidgets
jQWidgets-jqxNavigationBar
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
Difference Between JavaScript and jQuery
How to get the value in an input text box using jQuery ?
QR Code Generator using HTML, CSS and jQuery
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25364,
"s": 25336,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 25733,
"s": 25364,
"text": "jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxNavigationBar is used for representing a jQuery widget that has header and content sections. On clicking over the header, the content will be expanded or collapsed accordingly."
},
{
"code": null,
"e": 25909,
"s": 25733,
"text": "The initContent property is used as a callback function that is called when an item’s content needs to be initialized. Here the index argument shows which item is initialized."
},
{
"code": null,
"e": 25917,
"s": 25909,
"text": "Syntax:"
},
{
"code": null,
"e": 25947,
"s": 25917,
"text": "Set the initContent property:"
},
{
"code": null,
"e": 26266,
"s": 25947,
"text": "$(\"Selector\").jqxNavigationBar({\n initContent: function (index) {\n $(\"#jqxButton\").jqxButton({ \n $('#jqxbutton_for_initContent')\n .on('click', function () {\n $('#jqx_Navigation_Bar')\n .jqxNavigationBar('disable');\n }); \n });\n }\n});"
},
{
"code": null,
"e": 26301,
"s": 26268,
"text": "Return the initContent property:"
},
{
"code": null,
"e": 26371,
"s": 26301,
"text": "var initContent = \n $('Selector').jqxNavigationBar('initContent');"
},
{
"code": null,
"e": 26494,
"s": 26371,
"text": "Linked Files: Download jQWidgets from the given link. In the HTML file, locate the script files in the downloaded folder. "
},
{
"code": null,
"e": 26851,
"s": 26494,
"text": "<link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqxexpander.js”></script><script type=”text/javascript” src=”jqwidgets/jqxnavigationbar.js”></script>"
},
{
"code": null,
"e": 26978,
"s": 26851,
"text": "Example: The below example illustrates the jQWidgets jqxNavigationBar initContent property used to disable the navigation bar."
},
{
"code": null,
"e": 26983,
"s": 26978,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"jqwidgets/styles/jqx.base.css\" type=\"text/css\"/> <script type=\"text/javascript\" src=\"scripts/jquery.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqxcore.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqxexpander.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqxnavigationbar.js\"> </script></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> jQWidgets jqxNavigationBar initContent Property </h3> <div id=\"jqx_Navigation_Bar\" style=\"margin: 25px;\" align=\"left\"> <div>First Header</div> <div> <h8>Content for the first header</h8> <ul> <li>GFG</li> <li>CSE</li> </ul> </div> <div> Second Header</div> <div> <input type=\"button\" style=\"margin: 29px;\" id=\"jqxbutton_for_initContent\" value=\"Disable\"/> </div> </div> <script type=\"text/javascript\"> $(document).ready(function () { $(\"#jqx_Navigation_Bar\"). jqxNavigationBar({ width: 250, height: 132, initContent: function (index) { if (index === 0) { $('#jqxbutton_for_initContent'). on('click', function () { $('#jqx_Navigation_Bar'). jqxNavigationBar( 'disable'); }); } } }); $(\"#jqxbutton_for_initContent\"). jqxButton({ width: 100, }); }); </script> </center></body> </html>",
"e": 29172,
"s": 26983,
"text": null
},
{
"code": null,
"e": 29180,
"s": 29172,
"text": "Output:"
},
{
"code": null,
"e": 29314,
"s": 29180,
"text": "Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxnavigationbar/jquery-navigationbar-api.htm?search="
},
{
"code": null,
"e": 29331,
"s": 29314,
"text": "jQuery-jQWidgets"
},
{
"code": null,
"e": 29358,
"s": 29331,
"text": "jQWidgets-jqxNavigationBar"
},
{
"code": null,
"e": 29365,
"s": 29358,
"text": "JQuery"
},
{
"code": null,
"e": 29382,
"s": 29365,
"text": "Web Technologies"
},
{
"code": null,
"e": 29480,
"s": 29382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29489,
"s": 29480,
"text": "Comments"
},
{
"code": null,
"e": 29502,
"s": 29489,
"text": "Old Comments"
},
{
"code": null,
"e": 29575,
"s": 29502,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 29598,
"s": 29575,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29639,
"s": 29598,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 29696,
"s": 29639,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 29741,
"s": 29696,
"text": "QR Code Generator using HTML, CSS and jQuery"
},
{
"code": null,
"e": 29797,
"s": 29741,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29830,
"s": 29797,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29892,
"s": 29830,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29935,
"s": 29892,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Find element with maximum weight in given price range for Q queries - GeeksforGeeks | 18 Feb, 2022
Given an array arr[] of size N where each element denotes a pair in the form (price, weight) denoting the price and weight of each item. Given Q queries of the form [X, Y] denoting the price range. The task is to find the element with the highest weight within a given price range for each query.
Examples:
Input: arr[][] = {{24, 6}, {30, 8}, {21, 7}}, queries[][] = {{10, 24}, {20, 30}} Output: [7, 8]Explanation: The following are the items chosen for the above range For first query: There are two items with given range [10, 24] -> {24, 6} and {21, 7} . Highest weight is 7. For second query: There are two items with given range [20, 30] -> {24, 6}, {21, 7} and {30, 8}. Highest weight is 8.Therefore, answer is [7, 8].
Input: arr[][] = {{1000, 300}, {1100, 400}, {1300, 200}, {1700, 500}, {2000, 600}}, queries[][] = {{1000, 1400}, {1700, 500}, {2000, 600}}Output: [400, 500, 600]
Naive Approach: A Simple Solution is to run a loop for the price range and find the maximum weight for each query.
Time Complexity: O(Q*N).Auxiliary Space: O(1)
Efficient Approach: An efficient approach is to preprocess to store the maximum weight in the price range [i, j] for any i and j. Use Segment Tree for preprocessing and query in moderate time.
Representation of Segment trees
Leaf Nodes are the weight corresponding to elements of the input array.Each internal node represents the maximum weight of all leaves under it.
Leaf Nodes are the weight corresponding to elements of the input array.
Each internal node represents the maximum weight of all leaves under it.
An array representation of a tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, the right child is at 2*i+2 and the parent is at ⌊(i – 1) / 2⌋.
The solution can be elaborated by dividing the approach into two parts:
Construction of Segment Tree from the given array: Start with a segment [0 . . . N-1]. and every time divide the current segment into two halves (if it has not yet become a segment of length 1).Then call the same procedure on both halves, and for each such segment, store the maximum value in a segment tree node. Each node here represents the max weight for the given price range between given segment indexes.Note: All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because segments are divided into two halves at every level. Since the constructed tree is always a full binary tree with N leaves.The query for the minimum value of the given range: Once the tree is constructed, how to do range maximum query using the constructed segment tree. Following is the algorithm to get the maximum.If the price range of the node is same as the given price range of the query, return the value in the node.If the range is completely outside the given range return an extremely high value or say infinite value.Otherwise, call a recursive function for both left and right children and return the max received from the recursive calls.
Construction of Segment Tree from the given array: Start with a segment [0 . . . N-1]. and every time divide the current segment into two halves (if it has not yet become a segment of length 1).Then call the same procedure on both halves, and for each such segment, store the maximum value in a segment tree node. Each node here represents the max weight for the given price range between given segment indexes.Note: All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because segments are divided into two halves at every level. Since the constructed tree is always a full binary tree with N leaves.
Construction of Segment Tree from the given array:
Start with a segment [0 . . . N-1]. and every time divide the current segment into two halves (if it has not yet become a segment of length 1).
Then call the same procedure on both halves, and for each such segment, store the maximum value in a segment tree node. Each node here represents the max weight for the given price range between given segment indexes.
Note: All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because segments are divided into two halves at every level. Since the constructed tree is always a full binary tree with N leaves.
The query for the minimum value of the given range: Once the tree is constructed, how to do range maximum query using the constructed segment tree. Following is the algorithm to get the maximum.If the price range of the node is same as the given price range of the query, return the value in the node.If the range is completely outside the given range return an extremely high value or say infinite value.Otherwise, call a recursive function for both left and right children and return the max received from the recursive calls.
The query for the minimum value of the given range: Once the tree is constructed, how to do range maximum query using the constructed segment tree. Following is the algorithm to get the maximum.
If the price range of the node is same as the given price range of the query, return the value in the node.
If the range is completely outside the given range return an extremely high value or say infinite value.
Otherwise, call a recursive function for both left and right children and return the max received from the recursive calls.
See the image below to understand the formation of segment tree for given input.
Image representation of segment tree for the given input
See the following algorithm for better understanding.
// qs –> query start price, qe –> query end price
int RMQ(node, qs, qe){ if price range of node is within qs and qe return value in node else if price range of node is completely outside qs and qe return INFINITEelse return max( RMQ(node’s left child, qs, qe), RMQ(node’s right child, qs, qe) )}
Below is the implementation of the above approach.
Java
// Java code to implement above approachimport java.io.*;import java.util.*; class GFG { static int[] segmentTree; // Function to get mid public static int getMid(int start, int end) { return start + (end - start) / 2; } // Function to fill segment tree public static void fillSegmentTree(int[][] arr) { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); int n = arr.length; int maxHeight = (int)Math.ceil(Math.log(n) / Math.log(2)); int maxSize = 2 * (int)Math.pow(2, maxHeight) - 1; segmentTree = new int[maxSize]; fillSegmentTreeUtil(segmentTree, arr, 0, n - 1, 0); } // Function to utilise the segment tree public static int fillSegmentTreeUtil(int[] segmentTree, int[][] arr, int start, int end, int currNode) { if (start == end) { segmentTree[currNode] = arr[start][1]; return segmentTree[currNode]; } int mid = getMid(start, end); segmentTree[currNode] = Math.max( fillSegmentTreeUtil(segmentTree, arr, start, mid, currNode * 2 + 1), fillSegmentTreeUtil(segmentTree, arr, mid + 1, end, currNode * 2 + 2)); return segmentTree[currNode]; } // Function to find the maximum rating public static int findMaxRating(int[][] arr, int[] query) { int n = arr.length; return findMaxRatingUtil(segmentTree, arr, 0, n - 1, query[0], query[1], 0); } // Function to utilise the // maxRating function public static int findMaxRatingUtil(int[] segmentTree, int[][] arr, int start, int end, int qStart, int qEnd, int currNode) { if (qStart <= arr[start][0] && qEnd >= arr[end][0]) { return segmentTree[currNode]; } if (qStart > arr[end][0] || qEnd < arr[start][0]) { return -1; } int mid = getMid(start, end); return Math.max( findMaxRatingUtil(segmentTree, arr, start, mid, qStart, qEnd, currNode * 2 + 1), findMaxRatingUtil(segmentTree, arr, mid + 1, end, qStart, qEnd, currNode * 2 + 2)); } // Driver code public static void main(String[] args) { int[][] arr = { { 1000, 300 }, { 1100, 400 }, { 1300, 200 }, { 1700, 500 }, { 2000, 600 } }; fillSegmentTree(arr); int[][] queries = { { 1000, 1400 }, { 1700, 1900 }, { 0, 3000 } }; for (int[] query : queries) { System.out.println( findMaxRating(arr, query)); } }}
400
500
600
Time Complexity: O(N log N + Q*log N)Auxiliary Space: O(N)
Analyzing Time Complexity: Time Complexity for sorting the given input array is O(N * LogN)Time Complexity for tree construction is O(N). There is a total of 2N-1 nodes, and the value of every node is calculated only once in tree construction.The time complexity for each query is O(LogN). To query a range maximum, process at most two nodes at every level, and the number of levels is O(LogN).
surinderdawra388
array-range-queries
Segment-Tree
Arrays
Arrays
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Building Heap from Array
Remove duplicates from sorted array
Sliding Window Maximum (Maximum of all subarrays of size k)
Move all negative numbers to beginning and positive to end with constant extra space | [
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 24729,
"s": 24431,
"text": "Given an array arr[] of size N where each element denotes a pair in the form (price, weight) denoting the price and weight of each item. Given Q queries of the form [X, Y] denoting the price range. The task is to find the element with the highest weight within a given price range for each query. "
},
{
"code": null,
"e": 24740,
"s": 24729,
"text": "Examples: "
},
{
"code": null,
"e": 25159,
"s": 24740,
"text": "Input: arr[][] = {{24, 6}, {30, 8}, {21, 7}}, queries[][] = {{10, 24}, {20, 30}} Output: [7, 8]Explanation: The following are the items chosen for the above range For first query: There are two items with given range [10, 24] -> {24, 6} and {21, 7} . Highest weight is 7. For second query: There are two items with given range [20, 30] -> {24, 6}, {21, 7} and {30, 8}. Highest weight is 8.Therefore, answer is [7, 8]."
},
{
"code": null,
"e": 25322,
"s": 25159,
"text": "Input: arr[][] = {{1000, 300}, {1100, 400}, {1300, 200}, {1700, 500}, {2000, 600}}, queries[][] = {{1000, 1400}, {1700, 500}, {2000, 600}}Output: [400, 500, 600]"
},
{
"code": null,
"e": 25438,
"s": 25322,
"text": "Naive Approach: A Simple Solution is to run a loop for the price range and find the maximum weight for each query. "
},
{
"code": null,
"e": 25484,
"s": 25438,
"text": "Time Complexity: O(Q*N).Auxiliary Space: O(1)"
},
{
"code": null,
"e": 25677,
"s": 25484,
"text": "Efficient Approach: An efficient approach is to preprocess to store the maximum weight in the price range [i, j] for any i and j. Use Segment Tree for preprocessing and query in moderate time."
},
{
"code": null,
"e": 25709,
"s": 25677,
"text": "Representation of Segment trees"
},
{
"code": null,
"e": 25853,
"s": 25709,
"text": "Leaf Nodes are the weight corresponding to elements of the input array.Each internal node represents the maximum weight of all leaves under it."
},
{
"code": null,
"e": 25925,
"s": 25853,
"text": "Leaf Nodes are the weight corresponding to elements of the input array."
},
{
"code": null,
"e": 25998,
"s": 25925,
"text": "Each internal node represents the maximum weight of all leaves under it."
},
{
"code": null,
"e": 26192,
"s": 25998,
"text": "An array representation of a tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, the right child is at 2*i+2 and the parent is at ⌊(i – 1) / 2⌋."
},
{
"code": null,
"e": 26264,
"s": 26192,
"text": "The solution can be elaborated by dividing the approach into two parts:"
},
{
"code": null,
"e": 27475,
"s": 26264,
"text": "Construction of Segment Tree from the given array: Start with a segment [0 . . . N-1]. and every time divide the current segment into two halves (if it has not yet become a segment of length 1).Then call the same procedure on both halves, and for each such segment, store the maximum value in a segment tree node. Each node here represents the max weight for the given price range between given segment indexes.Note: All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because segments are divided into two halves at every level. Since the constructed tree is always a full binary tree with N leaves.The query for the minimum value of the given range: Once the tree is constructed, how to do range maximum query using the constructed segment tree. Following is the algorithm to get the maximum.If the price range of the node is same as the given price range of the query, return the value in the node.If the range is completely outside the given range return an extremely high value or say infinite value.Otherwise, call a recursive function for both left and right children and return the max received from the recursive calls."
},
{
"code": null,
"e": 28158,
"s": 27475,
"text": "Construction of Segment Tree from the given array: Start with a segment [0 . . . N-1]. and every time divide the current segment into two halves (if it has not yet become a segment of length 1).Then call the same procedure on both halves, and for each such segment, store the maximum value in a segment tree node. Each node here represents the max weight for the given price range between given segment indexes.Note: All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because segments are divided into two halves at every level. Since the constructed tree is always a full binary tree with N leaves."
},
{
"code": null,
"e": 28210,
"s": 28158,
"text": "Construction of Segment Tree from the given array: "
},
{
"code": null,
"e": 28354,
"s": 28210,
"text": "Start with a segment [0 . . . N-1]. and every time divide the current segment into two halves (if it has not yet become a segment of length 1)."
},
{
"code": null,
"e": 28572,
"s": 28354,
"text": "Then call the same procedure on both halves, and for each such segment, store the maximum value in a segment tree node. Each node here represents the max weight for the given price range between given segment indexes."
},
{
"code": null,
"e": 28844,
"s": 28572,
"text": "Note: All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree because segments are divided into two halves at every level. Since the constructed tree is always a full binary tree with N leaves."
},
{
"code": null,
"e": 29373,
"s": 28844,
"text": "The query for the minimum value of the given range: Once the tree is constructed, how to do range maximum query using the constructed segment tree. Following is the algorithm to get the maximum.If the price range of the node is same as the given price range of the query, return the value in the node.If the range is completely outside the given range return an extremely high value or say infinite value.Otherwise, call a recursive function for both left and right children and return the max received from the recursive calls."
},
{
"code": null,
"e": 29568,
"s": 29373,
"text": "The query for the minimum value of the given range: Once the tree is constructed, how to do range maximum query using the constructed segment tree. Following is the algorithm to get the maximum."
},
{
"code": null,
"e": 29676,
"s": 29568,
"text": "If the price range of the node is same as the given price range of the query, return the value in the node."
},
{
"code": null,
"e": 29781,
"s": 29676,
"text": "If the range is completely outside the given range return an extremely high value or say infinite value."
},
{
"code": null,
"e": 29905,
"s": 29781,
"text": "Otherwise, call a recursive function for both left and right children and return the max received from the recursive calls."
},
{
"code": null,
"e": 29986,
"s": 29905,
"text": "See the image below to understand the formation of segment tree for given input."
},
{
"code": null,
"e": 30043,
"s": 29986,
"text": "Image representation of segment tree for the given input"
},
{
"code": null,
"e": 30097,
"s": 30043,
"text": "See the following algorithm for better understanding."
},
{
"code": null,
"e": 30147,
"s": 30097,
"text": "// qs –> query start price, qe –> query end price"
},
{
"code": null,
"e": 30406,
"s": 30147,
"text": "int RMQ(node, qs, qe){ if price range of node is within qs and qe return value in node else if price range of node is completely outside qs and qe return INFINITEelse return max( RMQ(node’s left child, qs, qe), RMQ(node’s right child, qs, qe) )}"
},
{
"code": null,
"e": 30457,
"s": 30406,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 30462,
"s": 30457,
"text": "Java"
},
{
"code": "// Java code to implement above approachimport java.io.*;import java.util.*; class GFG { static int[] segmentTree; // Function to get mid public static int getMid(int start, int end) { return start + (end - start) / 2; } // Function to fill segment tree public static void fillSegmentTree(int[][] arr) { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); int n = arr.length; int maxHeight = (int)Math.ceil(Math.log(n) / Math.log(2)); int maxSize = 2 * (int)Math.pow(2, maxHeight) - 1; segmentTree = new int[maxSize]; fillSegmentTreeUtil(segmentTree, arr, 0, n - 1, 0); } // Function to utilise the segment tree public static int fillSegmentTreeUtil(int[] segmentTree, int[][] arr, int start, int end, int currNode) { if (start == end) { segmentTree[currNode] = arr[start][1]; return segmentTree[currNode]; } int mid = getMid(start, end); segmentTree[currNode] = Math.max( fillSegmentTreeUtil(segmentTree, arr, start, mid, currNode * 2 + 1), fillSegmentTreeUtil(segmentTree, arr, mid + 1, end, currNode * 2 + 2)); return segmentTree[currNode]; } // Function to find the maximum rating public static int findMaxRating(int[][] arr, int[] query) { int n = arr.length; return findMaxRatingUtil(segmentTree, arr, 0, n - 1, query[0], query[1], 0); } // Function to utilise the // maxRating function public static int findMaxRatingUtil(int[] segmentTree, int[][] arr, int start, int end, int qStart, int qEnd, int currNode) { if (qStart <= arr[start][0] && qEnd >= arr[end][0]) { return segmentTree[currNode]; } if (qStart > arr[end][0] || qEnd < arr[start][0]) { return -1; } int mid = getMid(start, end); return Math.max( findMaxRatingUtil(segmentTree, arr, start, mid, qStart, qEnd, currNode * 2 + 1), findMaxRatingUtil(segmentTree, arr, mid + 1, end, qStart, qEnd, currNode * 2 + 2)); } // Driver code public static void main(String[] args) { int[][] arr = { { 1000, 300 }, { 1100, 400 }, { 1300, 200 }, { 1700, 500 }, { 2000, 600 } }; fillSegmentTree(arr); int[][] queries = { { 1000, 1400 }, { 1700, 1900 }, { 0, 3000 } }; for (int[] query : queries) { System.out.println( findMaxRating(arr, query)); } }}",
"e": 34158,
"s": 30462,
"text": null
},
{
"code": null,
"e": 34171,
"s": 34158,
"text": "400\n500\n600\n"
},
{
"code": null,
"e": 34230,
"s": 34171,
"text": "Time Complexity: O(N log N + Q*log N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 34626,
"s": 34230,
"text": "Analyzing Time Complexity: Time Complexity for sorting the given input array is O(N * LogN)Time Complexity for tree construction is O(N). There is a total of 2N-1 nodes, and the value of every node is calculated only once in tree construction.The time complexity for each query is O(LogN). To query a range maximum, process at most two nodes at every level, and the number of levels is O(LogN). "
},
{
"code": null,
"e": 34643,
"s": 34626,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34663,
"s": 34643,
"text": "array-range-queries"
},
{
"code": null,
"e": 34676,
"s": 34663,
"text": "Segment-Tree"
},
{
"code": null,
"e": 34683,
"s": 34676,
"text": "Arrays"
},
{
"code": null,
"e": 34690,
"s": 34683,
"text": "Arrays"
},
{
"code": null,
"e": 34703,
"s": 34690,
"text": "Segment-Tree"
},
{
"code": null,
"e": 34801,
"s": 34703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34810,
"s": 34801,
"text": "Comments"
},
{
"code": null,
"e": 34823,
"s": 34810,
"text": "Old Comments"
},
{
"code": null,
"e": 34844,
"s": 34823,
"text": "Next Greater Element"
},
{
"code": null,
"e": 34869,
"s": 34844,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34896,
"s": 34869,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 34945,
"s": 34896,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34983,
"s": 34945,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 35042,
"s": 34983,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 35067,
"s": 35042,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 35103,
"s": 35067,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 35163,
"s": 35103,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
}
] |
List Data Type in Python | Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
This produce the following result −
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] | [
{
"code": null,
"e": 1359,
"s": 1062,
"text": "Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type."
},
{
"code": null,
"e": 1648,
"s": 1359,
"text": "The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −"
},
{
"code": null,
"e": 2031,
"s": 1648,
"text": "#!/usr/bin/python\nlist = [ 'abcd', 786 , 2.23, 'john', 70.2 ]\ntinylist = [123, 'john']\nprint list # Prints complete list\nprint list[0] # Prints first element of the list\nprint list[1:3] # Prints elements starting from 2nd till 3rd\nprint list[2:] # Prints elements starting from 3rd element\nprint tinylist * 2 # Prints list two times\nprint list + tinylist # Prints concatenated lists"
},
{
"code": null,
"e": 2067,
"s": 2031,
"text": "This produce the following result −"
},
{
"code": null,
"e": 2213,
"s": 2067,
"text": "['abcd', 786, 2.23, 'john', 70.2]\nabcd\n[786, 2.23]\n[2.23, 'john', 70.2]\n[123, 'john', 123, 'john']\n['abcd', 786, 2.23, 'john', 70.2, 123, 'john']"
}
] |
JCL Online Quiz | Following quiz provides Multiple Choice Questions (MCQs) related to JCL Framework. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - What does JCL stands for?
A - Job Cobol Language
B - Job Communication Language
C - Job Control Language
D - None of these
JCL stands for Job Control Language which provides the specifications necessary to process a job.
Q 2 - What operation is performed by JOB statement?
A - Job Identification
B - Execution of program
C - Includes name of the dataset to operate
D - None of these
Specifies the information required for SPOOLing of the job such as job id, priority of execution, user-id to be notified upon completion of the job.
Q 3 - What will happen to Step2 if Step1 executes with RC=0?
//TXXXXXX JOB (XXXXX), ’XXXX’
//STEP1 EXEC PGM = PR1
//STEP2 EXEC PGM = PR2, COND = (0, EQ, STEP1)
A - Step2 will be bypassed
B - Step2 will be executed
C - None of these
It will read the condition on step2 as 0 EQUAL 0, which is true, so step will be bypassed. If condition is true then the step will be bypassed.
Q 4 - If COND parameter is coded on both JOB and EXEC statement, then the condition on JOB is checked before checking the condition on EXEC statement. State whether true or false?
A - True
B - False
This statement is correct.
Q 5 - How you will define a temporary dataset in JCL?
A - DSN = &&TEMP with DSN parameters
B - DSN = temp-file-name with DSN parameters
C - DSN = temp-file-name with out DSN parameters
D - DSN = &&TEMP with out DSN parameters
A temporary dataset is the one that is created and deleted within a job and is declared as DSN=&&TEMP. Do not mention the DSN parameters with this.
Q 6 - Which utility is used to update PDS?
A - IEBGENER
B - IEBCOPY
C - IEBCOMPR
D - IEBUPDTE
IEBUPDTE is used to update PDS
Q 7 - A CHKPT is the parameter coded for multi-volume QSAM datasets in a DD statement. When a CHKPT is coded as CHKPT=EOV, a checkpoint is written to the dataset specified in the SYSCKEOV statement at the end of each volume of the input/output multi-volume dataset. State whether true or false?
A - False
B - True
This is self explanatory.
Q 8 - In-stream procedure is coded as a separate member of a PDS. State whether true or false?
A - True
B - False
In-stream procedure is coded inside the JCL itself. So this statement is incorrect.
Q 9 - If we have created a (+1) generation dataset in the first step of a job then how we can reference it in later steps of the same job for input?
A - As (+2) generation
B - As (+0) generation
C - As (+1) generation
D - As (-2) generation
As we have created it in the same JCL, then we use (+1) as its reference.
Q 10 - What units are used for allocation of output dataset?
A - KB
B - Bytes
C - Cylinders, Tracks & Blocks
D - MB
In mainframes, we use cylinders, tracks and blocks for allocation of datasets.
12 Lectures
2 hours
Nishant Malik
73 Lectures
4.5 hours
Topictrick Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2191,
"s": 1864,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to JCL Framework. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 2223,
"s": 2191,
"text": "Q 1 - What does JCL stands for?"
},
{
"code": null,
"e": 2246,
"s": 2223,
"text": "A - Job Cobol Language"
},
{
"code": null,
"e": 2277,
"s": 2246,
"text": "B - Job Communication Language"
},
{
"code": null,
"e": 2302,
"s": 2277,
"text": "C - Job Control Language"
},
{
"code": null,
"e": 2320,
"s": 2302,
"text": "D - None of these"
},
{
"code": null,
"e": 2418,
"s": 2320,
"text": "JCL stands for Job Control Language which provides the specifications necessary to process a job."
},
{
"code": null,
"e": 2470,
"s": 2418,
"text": "Q 2 - What operation is performed by JOB statement?"
},
{
"code": null,
"e": 2493,
"s": 2470,
"text": "A - Job Identification"
},
{
"code": null,
"e": 2518,
"s": 2493,
"text": "B - Execution of program"
},
{
"code": null,
"e": 2562,
"s": 2518,
"text": "C - Includes name of the dataset to operate"
},
{
"code": null,
"e": 2580,
"s": 2562,
"text": "D - None of these"
},
{
"code": null,
"e": 2729,
"s": 2580,
"text": "Specifies the information required for SPOOLing of the job such as job id, priority of execution, user-id to be notified upon completion of the job."
},
{
"code": null,
"e": 2790,
"s": 2729,
"text": "Q 3 - What will happen to Step2 if Step1 executes with RC=0?"
},
{
"code": null,
"e": 2889,
"s": 2790,
"text": "//TXXXXXX JOB (XXXXX), ’XXXX’\n//STEP1 EXEC PGM = PR1\n//STEP2 EXEC PGM = PR2, COND = (0, EQ, STEP1)"
},
{
"code": null,
"e": 2917,
"s": 2889,
"text": "A - Step2 will be bypassed "
},
{
"code": null,
"e": 2944,
"s": 2917,
"text": "B - Step2 will be executed"
},
{
"code": null,
"e": 2962,
"s": 2944,
"text": "C - None of these"
},
{
"code": null,
"e": 3106,
"s": 2962,
"text": "It will read the condition on step2 as 0 EQUAL 0, which is true, so step will be bypassed. If condition is true then the step will be bypassed."
},
{
"code": null,
"e": 3286,
"s": 3106,
"text": "Q 4 - If COND parameter is coded on both JOB and EXEC statement, then the condition on JOB is checked before checking the condition on EXEC statement. State whether true or false?"
},
{
"code": null,
"e": 3295,
"s": 3286,
"text": "A - True"
},
{
"code": null,
"e": 3305,
"s": 3295,
"text": "B - False"
},
{
"code": null,
"e": 3332,
"s": 3305,
"text": "This statement is correct."
},
{
"code": null,
"e": 3386,
"s": 3332,
"text": "Q 5 - How you will define a temporary dataset in JCL?"
},
{
"code": null,
"e": 3423,
"s": 3386,
"text": "A - DSN = &&TEMP with DSN parameters"
},
{
"code": null,
"e": 3468,
"s": 3423,
"text": "B - DSN = temp-file-name with DSN parameters"
},
{
"code": null,
"e": 3517,
"s": 3468,
"text": "C - DSN = temp-file-name with out DSN parameters"
},
{
"code": null,
"e": 3558,
"s": 3517,
"text": "D - DSN = &&TEMP with out DSN parameters"
},
{
"code": null,
"e": 3706,
"s": 3558,
"text": "A temporary dataset is the one that is created and deleted within a job and is declared as DSN=&&TEMP. Do not mention the DSN parameters with this."
},
{
"code": null,
"e": 3749,
"s": 3706,
"text": "Q 6 - Which utility is used to update PDS?"
},
{
"code": null,
"e": 3762,
"s": 3749,
"text": "A - IEBGENER"
},
{
"code": null,
"e": 3774,
"s": 3762,
"text": "B - IEBCOPY"
},
{
"code": null,
"e": 3787,
"s": 3774,
"text": "C - IEBCOMPR"
},
{
"code": null,
"e": 3800,
"s": 3787,
"text": "D - IEBUPDTE"
},
{
"code": null,
"e": 3831,
"s": 3800,
"text": "IEBUPDTE is used to update PDS"
},
{
"code": null,
"e": 4126,
"s": 3831,
"text": "Q 7 - A CHKPT is the parameter coded for multi-volume QSAM datasets in a DD statement. When a CHKPT is coded as CHKPT=EOV, a checkpoint is written to the dataset specified in the SYSCKEOV statement at the end of each volume of the input/output multi-volume dataset. State whether true or false?"
},
{
"code": null,
"e": 4136,
"s": 4126,
"text": "A - False"
},
{
"code": null,
"e": 4145,
"s": 4136,
"text": "B - True"
},
{
"code": null,
"e": 4171,
"s": 4145,
"text": "This is self explanatory."
},
{
"code": null,
"e": 4266,
"s": 4171,
"text": "Q 8 - In-stream procedure is coded as a separate member of a PDS. State whether true or false?"
},
{
"code": null,
"e": 4275,
"s": 4266,
"text": "A - True"
},
{
"code": null,
"e": 4285,
"s": 4275,
"text": "B - False"
},
{
"code": null,
"e": 4369,
"s": 4285,
"text": "In-stream procedure is coded inside the JCL itself. So this statement is incorrect."
},
{
"code": null,
"e": 4518,
"s": 4369,
"text": "Q 9 - If we have created a (+1) generation dataset in the first step of a job then how we can reference it in later steps of the same job for input?"
},
{
"code": null,
"e": 4541,
"s": 4518,
"text": "A - As (+2) generation"
},
{
"code": null,
"e": 4564,
"s": 4541,
"text": "B - As (+0) generation"
},
{
"code": null,
"e": 4587,
"s": 4564,
"text": "C - As (+1) generation"
},
{
"code": null,
"e": 4610,
"s": 4587,
"text": "D - As (-2) generation"
},
{
"code": null,
"e": 4684,
"s": 4610,
"text": "As we have created it in the same JCL, then we use (+1) as its reference."
},
{
"code": null,
"e": 4745,
"s": 4684,
"text": "Q 10 - What units are used for allocation of output dataset?"
},
{
"code": null,
"e": 4752,
"s": 4745,
"text": "A - KB"
},
{
"code": null,
"e": 4762,
"s": 4752,
"text": "B - Bytes"
},
{
"code": null,
"e": 4793,
"s": 4762,
"text": "C - Cylinders, Tracks & Blocks"
},
{
"code": null,
"e": 4800,
"s": 4793,
"text": "D - MB"
},
{
"code": null,
"e": 4879,
"s": 4800,
"text": "In mainframes, we use cylinders, tracks and blocks for allocation of datasets."
},
{
"code": null,
"e": 4912,
"s": 4879,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4927,
"s": 4912,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4962,
"s": 4927,
"text": "\n 73 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4984,
"s": 4962,
"text": " Topictrick Education"
},
{
"code": null,
"e": 4991,
"s": 4984,
"text": " Print"
},
{
"code": null,
"e": 5002,
"s": 4991,
"text": " Add Notes"
}
] |
How to use a StringVar object in an Entry widget in Tkinter? | A StringVar object in Tkinter can help manage the value of a widget such as an Entry widget or a Label widget. You can assign a StringVar object to the textvariable of a widget. For example,
data = ['Car', 'Bus', 'Truck', 'Bike', 'Airplane']
var = StringVar(win)
my_spinbox = Spinbox(win, values=data, textvariable=var)
Here, we created a list of strings followed by a StringVar object "var". Next, we assigned var to the textvariable of a Spinbox widget. To get the current value of the Spinbox, you can use var.get().
The following example demonstrates how you can use a StringVar object in an Entry widget.
from tkinter import *
top = Tk()
top.geometry("700x300")
top.title("StringVar Object in Entry Widget")
var = StringVar(top)
def submit():
Label2.config(text="Your User ID is: " +var.get(), font=("Calibri,15,Bold"))
Label1 = Label(top, text='Your User ID:')
Label1.grid(column=0, row=0, padx=(20,20), pady=(20,20))
myEntry = Entry(top, textvariable=var)
myEntry.grid(column=1, row=0, padx=(20,20), pady=(20,20))
myButton = Button(top, text="Submit", command=submit)
myButton.grid(column=2, row=0)
Label2 = Label(top, font="Calibri,10")
Label2.grid(column=0, row=1, columnspan=3)
top.mainloop()
It will produce the following output − | [
{
"code": null,
"e": 1253,
"s": 1062,
"text": "A StringVar object in Tkinter can help manage the value of a widget such as an Entry widget or a Label widget. You can assign a StringVar object to the textvariable of a widget. For example,"
},
{
"code": null,
"e": 1384,
"s": 1253,
"text": "data = ['Car', 'Bus', 'Truck', 'Bike', 'Airplane']\n\nvar = StringVar(win)\n\nmy_spinbox = Spinbox(win, values=data, textvariable=var)"
},
{
"code": null,
"e": 1584,
"s": 1384,
"text": "Here, we created a list of strings followed by a StringVar object \"var\". Next, we assigned var to the textvariable of a Spinbox widget. To get the current value of the Spinbox, you can use var.get()."
},
{
"code": null,
"e": 1674,
"s": 1584,
"text": "The following example demonstrates how you can use a StringVar object in an Entry widget."
},
{
"code": null,
"e": 2278,
"s": 1674,
"text": "from tkinter import *\n\ntop = Tk()\ntop.geometry(\"700x300\")\ntop.title(\"StringVar Object in Entry Widget\")\n\nvar = StringVar(top)\n\ndef submit():\n Label2.config(text=\"Your User ID is: \" +var.get(), font=(\"Calibri,15,Bold\"))\n\nLabel1 = Label(top, text='Your User ID:')\nLabel1.grid(column=0, row=0, padx=(20,20), pady=(20,20))\n\nmyEntry = Entry(top, textvariable=var)\nmyEntry.grid(column=1, row=0, padx=(20,20), pady=(20,20))\n\nmyButton = Button(top, text=\"Submit\", command=submit)\nmyButton.grid(column=2, row=0)\n\nLabel2 = Label(top, font=\"Calibri,10\")\nLabel2.grid(column=0, row=1, columnspan=3)\n\ntop.mainloop()"
},
{
"code": null,
"e": 2317,
"s": 2278,
"text": "It will produce the following output −"
}
] |
How to add the tag of Azure VM using PowerShell? | To add the tag to the Azure VM we need to use the Update-AZTag command. This command will merge the new tag to the existing tag(s) of the VM. If you are planning to add the entirely new VM tag, you can use the New-AZTag command. Once you use the New-AZTag command, other tags will be deleted for that particular VM and the New tag will be created so pls be careful with that command.
We have the VM called TestMachine2k12 on Azure and there are few existing tags applied to the VM as shown below.
Get-AzVM -Name TestMachine2k12 | Select -ExpandProperty Tags
We need to add the new tag called Patching_Day and its value should be Sunday. We will first create a tag that is a Hashtable with its name and associated value as shown below.
$tag = @{'Patching_Day' = 'Monday'}
Once the tag is created, we can use the Update-AZTag command. This command uses the resource ID. So we need VM resource ID to apply the tag.
PS C:\> $vm = Get-AzVM -Name TestMachine2k12
PS C:\> Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Merge -Verbose
Here, we are retrieving the VM information first to get the resource ID of it and you might have noticed that we are using Merge operation here. When you check the applied tag, it should show.
If you have multiple tags for the single VM then, you can add the additional tag to the TAG hashtable by a semicolon as shown below.
$tag = @{'Patching_Day' = 'Sunday'; 'App_Owner'='James Clean'}
You can use the Update-AZTag command to update the tag. When you have more than one VM to apply the same tag then you can use the foreach loop for it and if you have different tags for the different VMs then we can use the CSV file which has VM and associated tags and then foreach loop to apply the tag. | [
{
"code": null,
"e": 1446,
"s": 1062,
"text": "To add the tag to the Azure VM we need to use the Update-AZTag command. This command will merge the new tag to the existing tag(s) of the VM. If you are planning to add the entirely new VM tag, you can use the New-AZTag command. Once you use the New-AZTag command, other tags will be deleted for that particular VM and the New tag will be created so pls be careful with that command."
},
{
"code": null,
"e": 1559,
"s": 1446,
"text": "We have the VM called TestMachine2k12 on Azure and there are few existing tags applied to the VM as shown below."
},
{
"code": null,
"e": 1620,
"s": 1559,
"text": "Get-AzVM -Name TestMachine2k12 | Select -ExpandProperty Tags"
},
{
"code": null,
"e": 1797,
"s": 1620,
"text": "We need to add the new tag called Patching_Day and its value should be Sunday. We will first create a tag that is a Hashtable with its name and associated value as shown below."
},
{
"code": null,
"e": 1833,
"s": 1797,
"text": "$tag = @{'Patching_Day' = 'Monday'}"
},
{
"code": null,
"e": 1974,
"s": 1833,
"text": "Once the tag is created, we can use the Update-AZTag command. This command uses the resource ID. So we need VM resource ID to apply the tag."
},
{
"code": null,
"e": 2095,
"s": 1974,
"text": "PS C:\\> $vm = Get-AzVM -Name TestMachine2k12\nPS C:\\> Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Merge -Verbose"
},
{
"code": null,
"e": 2288,
"s": 2095,
"text": "Here, we are retrieving the VM information first to get the resource ID of it and you might have noticed that we are using Merge operation here. When you check the applied tag, it should show."
},
{
"code": null,
"e": 2421,
"s": 2288,
"text": "If you have multiple tags for the single VM then, you can add the additional tag to the TAG hashtable by a semicolon as shown below."
},
{
"code": null,
"e": 2484,
"s": 2421,
"text": "$tag = @{'Patching_Day' = 'Sunday'; 'App_Owner'='James Clean'}"
},
{
"code": null,
"e": 2789,
"s": 2484,
"text": "You can use the Update-AZTag command to update the tag. When you have more than one VM to apply the same tag then you can use the foreach loop for it and if you have different tags for the different VMs then we can use the CSV file which has VM and associated tags and then foreach loop to apply the tag."
}
] |
Pandas GroupBy - GeeksforGeeks | 29 Dec, 2021
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept but it’s an extremely valuable technique that’s widely used in data science. In real data science projects, you’ll be dealing with large amounts of data and trying things over and over, so for efficiency, we use Groupby concept. Groupby concept is really important because it’s ability to aggregate data efficiently, both in performance and the amount code is magnificent. Groupby mainly refers to a process involving one or more of the following steps they are:
Splitting : It is a process in which we split data into group by applying some conditions on datasets.
Applying : It is a process in which we apply a function to each group independently
Combining : It is a process in which we combine different datasets after applying groupby and results into a data structure
The following image will help in understanding a process involve in Groupby concept. 1. Group the unique values from the Team column
2. Now there’s a bucket for each group
3. Toss the other data into the buckets
4. Apply a function on the weight column of each bucket.
Splitting is a process in which we split data into a group by applying some conditions on datasets. In order to split the data, we apply certain conditions on datasets. In order to split the data, we use groupby() function this function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names. Pandas datasets can be split into any of their objects. There are multiple ways to split data like:
obj.groupby(key)
obj.groupby(key, axis=1)
obj.groupby([key1, key2])
Note :In this we refer to the grouping objects as the keys. Grouping data with one key: In order to group data with one key, we pass only one key as an argument in groupby function.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we group a data of Name using groupby() function.
Python3
# using groupby function# with one key df.groupby('Name')print(df.groupby('Name').groups)
Output :
Now we print the first entries in all the groups formed.
Python3
# applying groupby() function to# group the data on Name value.gk = df.groupby('Name') # Let's print the first entries# in all the groups formed.gk.first()
Output :
Grouping data with multiple keys : In order to group data with multiple keys, we pass multiple keys in groupby function.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we group a data of “Name” and “Qualification” together using multiple keys in groupby function.
Python3
# Using multiple keys in# groupby() functiondf.groupby(['Name', 'Qualification']) print(df.groupby(['Name', 'Qualification']).groups)
Output :
Grouping data by sorting keys : Group keys are sorted by default using the groupby operation. User can pass sort=False for potential speedups.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], } # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we apply groupby() without sort
Python3
# using groupby function# without using sort df.groupby(['Name']).sum()
Output :
Now we apply groupby() using sort in order to attain potential speedups
Python3
# using groupby function# with sort df.groupby(['Name'], sort = False).sum()
Output :
Grouping data with object attributes : Groups attribute is like dictionary whose keys are the computed unique groups and corresponding values being the axis labels belonging to each group.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we group data like we do in a dictionary using keys.
Python3
# using keys for grouping# data df.groupby('Name').groups
Output :
In order to iterate an element of groups, we can iterate through the object similar to itertools.obj.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we iterate an element of group in a similar way we do in itertools.obj.
Python3
# iterating an element# of group grp = df.groupby('Name')for name, group in grp: print(name) print(group) print()
Output :
Now we iterate an element of group containing multiple keys
Python3
# iterating an element# of group containing# multiple keys grp = df.groupby(['Name', 'Qualification'])for name, group in grp: print(name) print(group) print()
Output : As shown in output that group name will be tuple
In order to select a group, we can select group using GroupBy.get_group(). We can select a group by applying a function GroupBy.get_group this function select a single group.
Python3
# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we select a single group using Groupby.get_group.
Python3
# selecting a single group grp = df.groupby('Name')grp.get_group('Jai')
Output :
Now we select an object grouped on multiple columns
Python3
# selecting object grouped# on multiple columns grp = df.groupby(['Name', 'Qualification'])grp.get_group(('Jai', 'Msc'))
Output :
After splitting a data into a group, we apply a function to each group in order to do that we perform some operation they are:
Aggregation : It is a process in which we compute a summary statistic (or statistics) about each group. For Example, Compute group sums ormeans
Transformation : It is a process in which we perform some group-specific computations and return a like-indexed. For Example, Filling NAs within groups with a value derived from each group
Filtration : It is a process in which we discard some groups, according to a group-wise computation that evaluates True or False. For Example, Filtering out data based on the group sum or mean
Aggregation : Aggregation is a process in which we compute a summary statistic about each group. Aggregated function returns a single aggregated value for each group. After splitting a data into groups using groupby function, several aggregation operations can be performed on the grouped data. Code #1: Using aggregation via the aggregate method
Python3
# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we perform aggregation using aggregate method
Python3
# performing aggregation using# aggregate method grp1 = df.groupby('Name') grp1.aggregate(np.sum)
Output :
Now we perform aggregation on agroup containing multiple keys
Python3
# performing aggregation on# group containing multiple# keysgrp1 = df.groupby(['Name', 'Qualification']) grp1.aggregate(np.sum)
Output :
Applying multiple functions at once : We can apply a multiple functions at once by passing a list or dictionary of functions to do aggregation with, outputting a DataFrame.
Python3
# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we apply a multiple functions by passing a list of functions.
Python3
# applying a function by passing# a list of functions grp = df.groupby('Name') grp['Age'].agg([np.sum, np.mean, np.std])
Output :
Applying different functions to DataFrame columns : In order to apply a different aggregation to the columns of a DataFrame, we can pass a dictionary to aggregate .
Python3
# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA'], 'Score': [23, 34, 35, 45, 47, 50, 52, 53]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we apply a different aggregation to the columns of a dataframe.
Python3
# using different aggregation# function by passing dictionary# to aggregategrp = df.groupby('Name') grp.agg({'Age' : 'sum', 'Score' : 'std'})
Output :
Transformation : Transformation is a process in which we perform some group-specific computations and return a like-indexed. Transform method returns an object that is indexed the same (same size) as the one being grouped. The transform function must:
Return a result that is either the same size as the group chunk
Operate column-by-column on the group chunk
Not perform in-place operations on the group chunk.
Python3
# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA'], 'Score': [23, 34, 35, 45, 47, 50, 52, 53]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we perform some group-specific computations and return a like-indexed.
Python3
# using transform functiongrp = df.groupby('Name')sc = lambda x: (x - x.mean()) / x.std()*10grp.transform(sc)
Output :
Filtration : Filtration is a process in which we discard some groups, according to a group-wise computation that evaluates True or False. In order to filter a group, we use filter method and apply some condition by which we filter group.
Python3
# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA'], 'Score': [23, 34, 35, 45, 47, 50, 52, 53]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)
Now we filter data that to return the Name which have lived two or more times .
Python3
# filtering data using# filter datagrp = df.groupby('Name')grp.filter(lambda x: len(x) >= 2)
Output :
nidhi_biet
sumitgumber28
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace() | [
{
"code": null,
"e": 41553,
"s": 41525,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 42155,
"s": 41553,
"text": "Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept but it’s an extremely valuable technique that’s widely used in data science. In real data science projects, you’ll be dealing with large amounts of data and trying things over and over, so for efficiency, we use Groupby concept. Groupby concept is really important because it’s ability to aggregate data efficiently, both in performance and the amount code is magnificent. Groupby mainly refers to a process involving one or more of the following steps they are: "
},
{
"code": null,
"e": 42258,
"s": 42155,
"text": "Splitting : It is a process in which we split data into group by applying some conditions on datasets."
},
{
"code": null,
"e": 42342,
"s": 42258,
"text": "Applying : It is a process in which we apply a function to each group independently"
},
{
"code": null,
"e": 42466,
"s": 42342,
"text": "Combining : It is a process in which we combine different datasets after applying groupby and results into a data structure"
},
{
"code": null,
"e": 42601,
"s": 42466,
"text": "The following image will help in understanding a process involve in Groupby concept. 1. Group the unique values from the Team column "
},
{
"code": null,
"e": 42642,
"s": 42601,
"text": "2. Now there’s a bucket for each group "
},
{
"code": null,
"e": 42684,
"s": 42642,
"text": "3. Toss the other data into the buckets "
},
{
"code": null,
"e": 42743,
"s": 42684,
"text": "4. Apply a function on the weight column of each bucket. "
},
{
"code": null,
"e": 43282,
"s": 42745,
"text": "Splitting is a process in which we split data into a group by applying some conditions on datasets. In order to split the data, we apply certain conditions on datasets. In order to split the data, we use groupby() function this function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names. Pandas datasets can be split into any of their objects. There are multiple ways to split data like: "
},
{
"code": null,
"e": 43299,
"s": 43282,
"text": "obj.groupby(key)"
},
{
"code": null,
"e": 43324,
"s": 43299,
"text": "obj.groupby(key, axis=1)"
},
{
"code": null,
"e": 43350,
"s": 43324,
"text": "obj.groupby([key1, key2])"
},
{
"code": null,
"e": 43534,
"s": 43350,
"text": "Note :In this we refer to the grouping objects as the keys. Grouping data with one key: In order to group data with one key, we pass only one key as an argument in groupby function. "
},
{
"code": null,
"e": 43542,
"s": 43534,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 44112,
"s": 43542,
"text": null
},
{
"code": null,
"e": 44168,
"s": 44112,
"text": "Now we group a data of Name using groupby() function. "
},
{
"code": null,
"e": 44176,
"s": 44168,
"text": "Python3"
},
{
"code": "# using groupby function# with one key df.groupby('Name')print(df.groupby('Name').groups)",
"e": 44266,
"s": 44176,
"text": null
},
{
"code": null,
"e": 44277,
"s": 44266,
"text": "Output : "
},
{
"code": null,
"e": 44338,
"s": 44277,
"text": " Now we print the first entries in all the groups formed. "
},
{
"code": null,
"e": 44346,
"s": 44338,
"text": "Python3"
},
{
"code": "# applying groupby() function to# group the data on Name value.gk = df.groupby('Name') # Let's print the first entries# in all the groups formed.gk.first()",
"e": 44504,
"s": 44346,
"text": null
},
{
"code": null,
"e": 44515,
"s": 44504,
"text": "Output : "
},
{
"code": null,
"e": 44640,
"s": 44515,
"text": " Grouping data with multiple keys : In order to group data with multiple keys, we pass multiple keys in groupby function. "
},
{
"code": null,
"e": 44648,
"s": 44640,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 45218,
"s": 44648,
"text": null
},
{
"code": null,
"e": 45320,
"s": 45218,
"text": "Now we group a data of “Name” and “Qualification” together using multiple keys in groupby function. "
},
{
"code": null,
"e": 45328,
"s": 45320,
"text": "Python3"
},
{
"code": "# Using multiple keys in# groupby() functiondf.groupby(['Name', 'Qualification']) print(df.groupby(['Name', 'Qualification']).groups)",
"e": 45462,
"s": 45328,
"text": null
},
{
"code": null,
"e": 45473,
"s": 45462,
"text": "Output : "
},
{
"code": null,
"e": 45620,
"s": 45473,
"text": " Grouping data by sorting keys : Group keys are sorted by default using the groupby operation. User can pass sort=False for potential speedups. "
},
{
"code": null,
"e": 45628,
"s": 45620,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], } # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 45966,
"s": 45628,
"text": null
},
{
"code": null,
"e": 46004,
"s": 45966,
"text": "Now we apply groupby() without sort "
},
{
"code": null,
"e": 46012,
"s": 46004,
"text": "Python3"
},
{
"code": "# using groupby function# without using sort df.groupby(['Name']).sum()",
"e": 46084,
"s": 46012,
"text": null
},
{
"code": null,
"e": 46095,
"s": 46084,
"text": "Output : "
},
{
"code": null,
"e": 46169,
"s": 46095,
"text": "Now we apply groupby() using sort in order to attain potential speedups "
},
{
"code": null,
"e": 46177,
"s": 46169,
"text": "Python3"
},
{
"code": "# using groupby function# with sort df.groupby(['Name'], sort = False).sum()",
"e": 46254,
"s": 46177,
"text": null
},
{
"code": null,
"e": 46265,
"s": 46254,
"text": "Output : "
},
{
"code": null,
"e": 46458,
"s": 46265,
"text": " Grouping data with object attributes : Groups attribute is like dictionary whose keys are the computed unique groups and corresponding values being the axis labels belonging to each group. "
},
{
"code": null,
"e": 46466,
"s": 46458,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 47036,
"s": 46466,
"text": null
},
{
"code": null,
"e": 47095,
"s": 47036,
"text": "Now we group data like we do in a dictionary using keys. "
},
{
"code": null,
"e": 47103,
"s": 47095,
"text": "Python3"
},
{
"code": "# using keys for grouping# data df.groupby('Name').groups",
"e": 47161,
"s": 47103,
"text": null
},
{
"code": null,
"e": 47172,
"s": 47161,
"text": "Output : "
},
{
"code": null,
"e": 47280,
"s": 47176,
"text": "In order to iterate an element of groups, we can iterate through the object similar to itertools.obj. "
},
{
"code": null,
"e": 47288,
"s": 47280,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 47858,
"s": 47288,
"text": null
},
{
"code": null,
"e": 47936,
"s": 47858,
"text": "Now we iterate an element of group in a similar way we do in itertools.obj. "
},
{
"code": null,
"e": 47944,
"s": 47936,
"text": "Python3"
},
{
"code": "# iterating an element# of group grp = df.groupby('Name')for name, group in grp: print(name) print(group) print()",
"e": 48067,
"s": 47944,
"text": null
},
{
"code": null,
"e": 48078,
"s": 48067,
"text": "Output : "
},
{
"code": null,
"e": 48140,
"s": 48078,
"text": "Now we iterate an element of group containing multiple keys "
},
{
"code": null,
"e": 48148,
"s": 48140,
"text": "Python3"
},
{
"code": "# iterating an element# of group containing# multiple keys grp = df.groupby(['Name', 'Qualification'])for name, group in grp: print(name) print(group) print()",
"e": 48316,
"s": 48148,
"text": null
},
{
"code": null,
"e": 48376,
"s": 48316,
"text": "Output : As shown in output that group name will be tuple "
},
{
"code": null,
"e": 48557,
"s": 48380,
"text": "In order to select a group, we can select group using GroupBy.get_group(). We can select a group by applying a function GroupBy.get_group this function select a single group. "
},
{
"code": null,
"e": 48565,
"s": 48557,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 49135,
"s": 48565,
"text": null
},
{
"code": null,
"e": 49191,
"s": 49135,
"text": "Now we select a single group using Groupby.get_group. "
},
{
"code": null,
"e": 49199,
"s": 49191,
"text": "Python3"
},
{
"code": "# selecting a single group grp = df.groupby('Name')grp.get_group('Jai')",
"e": 49271,
"s": 49199,
"text": null
},
{
"code": null,
"e": 49282,
"s": 49271,
"text": "Output : "
},
{
"code": null,
"e": 49336,
"s": 49282,
"text": "Now we select an object grouped on multiple columns "
},
{
"code": null,
"e": 49344,
"s": 49336,
"text": "Python3"
},
{
"code": "# selecting object grouped# on multiple columns grp = df.groupby(['Name', 'Qualification'])grp.get_group(('Jai', 'Msc'))",
"e": 49465,
"s": 49344,
"text": null
},
{
"code": null,
"e": 49476,
"s": 49465,
"text": "Output : "
},
{
"code": null,
"e": 49607,
"s": 49478,
"text": "After splitting a data into a group, we apply a function to each group in order to do that we perform some operation they are: "
},
{
"code": null,
"e": 49751,
"s": 49607,
"text": "Aggregation : It is a process in which we compute a summary statistic (or statistics) about each group. For Example, Compute group sums ormeans"
},
{
"code": null,
"e": 49940,
"s": 49751,
"text": "Transformation : It is a process in which we perform some group-specific computations and return a like-indexed. For Example, Filling NAs within groups with a value derived from each group"
},
{
"code": null,
"e": 50133,
"s": 49940,
"text": "Filtration : It is a process in which we discard some groups, according to a group-wise computation that evaluates True or False. For Example, Filtering out data based on the group sum or mean"
},
{
"code": null,
"e": 50484,
"s": 50133,
"text": " Aggregation : Aggregation is a process in which we compute a summary statistic about each group. Aggregated function returns a single aggregated value for each group. After splitting a data into groups using groupby function, several aggregation operations can be performed on the grouped data. Code #1: Using aggregation via the aggregate method "
},
{
"code": null,
"e": 50492,
"s": 50484,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 51104,
"s": 50492,
"text": null
},
{
"code": null,
"e": 51156,
"s": 51104,
"text": "Now we perform aggregation using aggregate method "
},
{
"code": null,
"e": 51164,
"s": 51156,
"text": "Python3"
},
{
"code": "# performing aggregation using# aggregate method grp1 = df.groupby('Name') grp1.aggregate(np.sum)",
"e": 51262,
"s": 51164,
"text": null
},
{
"code": null,
"e": 51273,
"s": 51262,
"text": "Output : "
},
{
"code": null,
"e": 51337,
"s": 51273,
"text": "Now we perform aggregation on agroup containing multiple keys "
},
{
"code": null,
"e": 51345,
"s": 51337,
"text": "Python3"
},
{
"code": "# performing aggregation on# group containing multiple# keysgrp1 = df.groupby(['Name', 'Qualification']) grp1.aggregate(np.sum)",
"e": 51473,
"s": 51345,
"text": null
},
{
"code": null,
"e": 51484,
"s": 51473,
"text": "Output : "
},
{
"code": null,
"e": 51661,
"s": 51484,
"text": " Applying multiple functions at once : We can apply a multiple functions at once by passing a list or dictionary of functions to do aggregation with, outputting a DataFrame. "
},
{
"code": null,
"e": 51669,
"s": 51661,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA']} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 52281,
"s": 51669,
"text": null
},
{
"code": null,
"e": 52349,
"s": 52281,
"text": "Now we apply a multiple functions by passing a list of functions. "
},
{
"code": null,
"e": 52357,
"s": 52349,
"text": "Python3"
},
{
"code": "# applying a function by passing# a list of functions grp = df.groupby('Name') grp['Age'].agg([np.sum, np.mean, np.std])",
"e": 52478,
"s": 52357,
"text": null
},
{
"code": null,
"e": 52489,
"s": 52478,
"text": "Output : "
},
{
"code": null,
"e": 52658,
"s": 52489,
"text": " Applying different functions to DataFrame columns : In order to apply a different aggregation to the columns of a DataFrame, we can pass a dictionary to aggregate . "
},
{
"code": null,
"e": 52666,
"s": 52658,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA'], 'Score': [23, 34, 35, 45, 47, 50, 52, 53]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 53328,
"s": 52666,
"text": null
},
{
"code": null,
"e": 53398,
"s": 53328,
"text": "Now we apply a different aggregation to the columns of a dataframe. "
},
{
"code": null,
"e": 53406,
"s": 53398,
"text": "Python3"
},
{
"code": "# using different aggregation# function by passing dictionary# to aggregategrp = df.groupby('Name') grp.agg({'Age' : 'sum', 'Score' : 'std'})",
"e": 53548,
"s": 53406,
"text": null
},
{
"code": null,
"e": 53559,
"s": 53548,
"text": "Output : "
},
{
"code": null,
"e": 53813,
"s": 53559,
"text": "Transformation : Transformation is a process in which we perform some group-specific computations and return a like-indexed. Transform method returns an object that is indexed the same (same size) as the one being grouped. The transform function must: "
},
{
"code": null,
"e": 53877,
"s": 53813,
"text": "Return a result that is either the same size as the group chunk"
},
{
"code": null,
"e": 53921,
"s": 53877,
"text": "Operate column-by-column on the group chunk"
},
{
"code": null,
"e": 53973,
"s": 53921,
"text": "Not perform in-place operations on the group chunk."
},
{
"code": null,
"e": 53983,
"s": 53975,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA'], 'Score': [23, 34, 35, 45, 47, 50, 52, 53]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 54645,
"s": 53983,
"text": null
},
{
"code": null,
"e": 54722,
"s": 54645,
"text": "Now we perform some group-specific computations and return a like-indexed. "
},
{
"code": null,
"e": 54730,
"s": 54722,
"text": "Python3"
},
{
"code": "# using transform functiongrp = df.groupby('Name')sc = lambda x: (x - x.mean()) / x.std()*10grp.transform(sc)",
"e": 54840,
"s": 54730,
"text": null
},
{
"code": null,
"e": 54851,
"s": 54840,
"text": "Output : "
},
{
"code": null,
"e": 55091,
"s": 54851,
"text": "Filtration : Filtration is a process in which we discard some groups, according to a group-wise computation that evaluates True or False. In order to filter a group, we use filter method and apply some condition by which we filter group. "
},
{
"code": null,
"e": 55099,
"s": 55091,
"text": "Python3"
},
{
"code": "# importing pandas moduleimport pandas as pd # importing numpy as npimport numpy as np # Define a dictionary containing employee datadata1 = {'Name':['Jai', 'Anuj', 'Jai', 'Princi', 'Gaurav', 'Anuj', 'Princi', 'Abhi'], 'Age':[27, 24, 22, 32, 33, 36, 27, 32], 'Address':['Nagpur', 'Kanpur', 'Allahabad', 'Kannuaj', 'Jaunpur', 'Kanpur', 'Allahabad', 'Aligarh'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd', 'B.Tech', 'B.com', 'Msc', 'MA'], 'Score': [23, 34, 35, 45, 47, 50, 52, 53]} # Convert the dictionary into DataFrame df = pd.DataFrame(data1) print(df)",
"e": 55761,
"s": 55099,
"text": null
},
{
"code": null,
"e": 55843,
"s": 55761,
"text": "Now we filter data that to return the Name which have lived two or more times . "
},
{
"code": null,
"e": 55851,
"s": 55843,
"text": "Python3"
},
{
"code": "# filtering data using# filter datagrp = df.groupby('Name')grp.filter(lambda x: len(x) >= 2)",
"e": 55944,
"s": 55851,
"text": null
},
{
"code": null,
"e": 55955,
"s": 55944,
"text": "Output : "
},
{
"code": null,
"e": 55968,
"s": 55957,
"text": "nidhi_biet"
},
{
"code": null,
"e": 55982,
"s": 55968,
"text": "sumitgumber28"
},
{
"code": null,
"e": 55996,
"s": 55982,
"text": "Python-pandas"
},
{
"code": null,
"e": 56003,
"s": 55996,
"text": "Python"
},
{
"code": null,
"e": 56101,
"s": 56003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 56110,
"s": 56101,
"text": "Comments"
},
{
"code": null,
"e": 56123,
"s": 56110,
"text": "Old Comments"
},
{
"code": null,
"e": 56151,
"s": 56123,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 56201,
"s": 56151,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 56223,
"s": 56201,
"text": "Python map() function"
},
{
"code": null,
"e": 56267,
"s": 56223,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 56302,
"s": 56267,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 56324,
"s": 56302,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 56356,
"s": 56324,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 56386,
"s": 56356,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 56428,
"s": 56386,
"text": "Different ways to create Pandas Dataframe"
}
] |
iBATIS - Quick Guide | iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. The mappings are decoupled from the application logic by packaging the SQL statements in XML configuration files.
iBATIS is a lightweight framework and persistence API good for persisting POJOs( Plain Old Java Objects).
iBATIS is what is known as a data mapper and takes care of mapping the parameters and results between the class properties and the columns of the database table.
A significant difference between iBATIS and other persistence frameworks such as Hibernate is that iBATIS emphasizes the use of SQL, while other frameworks typically use a custom query language such has the Hibernate Query Language (HQL) or Enterprise JavaBeans Query Language (EJB QL).
iBATIS comes with the following design philosophies −
Simplicity − iBATIS is widely regarded as being one of the simplest persistence frameworks available today.
Simplicity − iBATIS is widely regarded as being one of the simplest persistence frameworks available today.
Fast Development − iBATIS does all it can to facilitate hyper-fast development.
Fast Development − iBATIS does all it can to facilitate hyper-fast development.
Portability − iBATIS can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET.
Portability − iBATIS can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET.
Independent Interfaces − iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources.
Independent Interfaces − iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources.
Open source − iBATIS is free and an open source software.
Open source − iBATIS is free and an open source software.
iBATIS offers the following advantages −
Supports stored procedures − iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.
Supports stored procedures − iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.
Supports inline SQL − No precompiler is needed, and you have full access to all of the features of SQL.
Supports inline SQL − No precompiler is needed, and you have full access to all of the features of SQL.
Supports dynamic SQL − iBATIS provides features for dynamically building SQL queries based on parameters.
Supports dynamic SQL − iBATIS provides features for dynamically building SQL queries based on parameters.
Supports O/RM − iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance
Supports O/RM − iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance
iBATIS makes use of JAVA programming language while developing database oriented application. Before proceeding further, make sure that you understand the basics of procedural and object-oriented programming − control structures, data structures and variables, classes, objects, etc.
To understand JAVA in detail you can go through our JAVA Tutorial.
You would have to set up a proper environment for iBATIS before starting off with actual development work. This chapter explains how to set up a working environment for iBATIS.
Carry out the following simple steps to install iBATIS on your Linux machine −
Download the latest version of iBATIS from Download iBATIS.
Download the latest version of iBATIS from Download iBATIS.
Unzip the downloaded file to extract .jar file from the bundle and keep them in appropriate lib directory.
Unzip the downloaded file to extract .jar file from the bundle and keep them in appropriate lib directory.
Set PATH and CLASSPATH variables at the extracted .jar file(s) appropriately.
Set PATH and CLASSPATH variables at the extracted .jar file(s) appropriately.
$ unzip ibatis-2.3.4.726.zip
inflating: META-INF/MANIFEST.MF
creating: doc/
creating: lib/
creating: simple_example/
creating: simple_example/com/
creating: simple_example/com/mydomain/
creating: simple_example/com/mydomain/data/
creating: simple_example/com/mydomain/domain/
creating: src/
inflating: doc/dev-javadoc.zip
inflating: doc/user-javadoc.zip
inflating: jar-dependencies.txt
inflating: lib/ibatis-2.3.4.726.jar
inflating: license.txt
inflating: notice.txt
inflating: release.txt
$pwd
/var/home/ibatis
$set PATH=$PATH:/var/home/ibatis/
$set CLASSPATH=$CLASSPATH:/var/home/ibatis\
/lib/ibatis-2.3.4.726.jar
Create an EMPLOYEE table in any MySQL database using the following syntax −
mysql> CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Consider the following −
We are going to use JDBC to access the database testdb.
We are going to use JDBC to access the database testdb.
JDBC driver for MySQL is "com.mysql.jdbc.Driver".
JDBC driver for MySQL is "com.mysql.jdbc.Driver".
Connection URL is "jdbc:mysql://localhost:3306/testdb".
Connection URL is "jdbc:mysql://localhost:3306/testdb".
We would use username and password as "root" and "root" respectively.
We would use username and password as "root" and "root" respectively.
Our sql statement mappings for all the operations would be described in "Employee.xml".
Our sql statement mappings for all the operations would be described in "Employee.xml".
Based on the above assumptions, we have to create an XML configuration file with name SqlMapConfig.xml with the following content. This is where you need to provide all configurations required for iBatis −
It is important that both the files SqlMapConfig.xml and Employee.xml should be present in the class path. For now, we would keep Employee.xml file empty and we would cover its contents in subsequent chapters.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings useStatementNamespaces="true"/>
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/testdb"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value="root"/>
</dataSource>
</transactionManager>
<sqlMap resource="Employee.xml"/>
</sqlMapConfig>
You can set the following optional properties as well using SqlMapConfig.xml file −
<property name="JDBC.AutoCommit" value="true"/>
<property name="Pool.MaximumActiveConnections" value="10"/>
<property name="Pool.MaximumIdleConnections" value="5"/>
<property name="Pool.MaximumCheckoutTime" value="150000"/>
<property name="Pool.MaximumTimeToWait" value="500"/>
<property name="Pool.PingQuery" value="select 1 from Employee"/>
<property name="Pool.PingEnabled" value="false"/>
To perform any Create, Read, Update, and Delete (CRUD) operation using iBATIS, you would need to create a Plain Old Java Objects (POJO) class corresponding to the table. This class describes the objects that will "model" database table rows.
The POJO class would have implementation for all the methods required to perform desired operations.
Let us assume we have the following EMPLOYEE table in MySQL −
CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
We would create an Employee class in Employee.java file as follows −
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
/* Define constructors for the Employee class. */
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
} /* End of Employee */
You can define methods to set individual fields in the table. The next chapter explains how to get the values of individual fields.
To define SQL mapping statement using iBATIS, we would use <insert> tag and inside this tag definition, we would define an "id" which will be used in IbatisInsert.java file for executing SQL INSERT query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<insert id="insert" parameterClass="Employee">
insert into EMPLOYEE(first_name, last_name, salary)
values (#first_name#, #last_name#, #salary#)
<selectKey resultClass="int" keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>
</sqlMap>
Here parameterClass − could take a value as string, int, float, double, or any class object based on requirement. In this example, we would pass Employee object as a parameter while calling insert method of SqlMap class.
If your database table uses an IDENTITY, AUTO_INCREMENT, or SERIAL column or you have defined a SEQUENCE/GENERATOR, you can use the <selectKey> element in an <insert> statement to use or return that database-generated value.
This file would have application level logic to insert records in the Employee table −
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisInsert{
public static void main(String[] args)throws IOException,SQLException{
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
/* This would insert one record in Employee table. */
System.out.println("Going to insert record.....");
Employee em = new Employee("Zara", "Ali", 5000);
smc.insert("Employee.insert", em);
System.out.println("Record Inserted Successfully ");
}
}
Here are the steps to compile and run the above mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisInsert.java as shown above and compile it.
Execute IbatisInsert binary to run the program.
You would get the following result, and a record would be created in the EMPLOYEE table.
$java IbatisInsert
Going to insert record.....
Record Inserted Successfully
If you check the EMPLOYEE table, it should display the following result −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 1 | Zara | Ali | 5000 |
+----+------------+-----------+--------+
1 row in set (0.00 sec)
We discussed, in the last chapter, how to perform CREATE operation on a table using iBATIS. This chapter explains how to read a table using iBATIS.
We have the following EMPLOYEE table in MySQL −
CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
This table has only one record as follows −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 1 | Zara | Ali | 5000 |
+----+------------+-----------+--------+
1 row in set (0.00 sec)
To perform read operation, we would modify the Employee class in Employee.java as follows −
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
/* Define constructors for the Employee class. */
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
/* Here are the method definitions */
public int getId() {
return id;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {
return last_name;
}
public int getSalary() {
return salary;
}
} /* End of Employee */
To define SQL mapping statement using iBATIS, we would add <select> tag in Employee.xml file and inside this tag definition, we would define an "id" which will be used in IbatisRead.java file for executing SQL SELECT query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<insert id="insert" parameterClass="Employee">
INSERT INTO EMPLOYEE(first_name, last_name, salary)
values (#first_name#, #last_name#, #salary#)
<selectKey resultClass="int" keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>
<select id="getAll" resultClass="Employee">
SELECT * FROM EMPLOYEE
</select>
</sqlMap>
Here we did not use WHERE clause with SQL SELECT statement. We would demonstrate, in the next chapter, how you can use WHERE clause with SELECT statement and how you can pass values to that WHERE clause.
This file has application level logic to read records from the Employee table −
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisRead{
public static void main(String[] args)throws IOException,SQLException{
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
/* This would read all records from the Employee table. */
System.out.println("Going to read records.....");
List <Employee> ems = (List<Employee>)
smc.queryForList("Employee.getAll", null);
Employee em = null;
for (Employee e : ems) {
System.out.print(" " + e.getId());
System.out.print(" " + e.getFirstName());
System.out.print(" " + e.getLastName());
System.out.print(" " + e.getSalary());
em = e;
System.out.println("");
}
System.out.println("Records Read Successfully ");
}
}
Here are the steps to compile and run the above mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisRead.java as shown above and compile it.
Execute IbatisRead binary to run the program.
You would get the following result, and a record would be read from the EMPLOYEE table as follows −
Going to read records.....
1 Zara Ali 5000
Record Reads Successfully
We discussed, in the last chapter, how to perform READ operation on a table using iBATIS. This chapter explains how you can update records in a table using iBATIS.
We have the following EMPLOYEE table in MySQL −
CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
This table has only one record as follows −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 1 | Zara | Ali | 5000 |
+----+------------+-----------+--------+
1 row in set (0.00 sec)
To perform udpate operation, you would need to modify Employee.java file as follows −
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
/* Define constructors for the Employee class. */
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
/* Here are the required method definitions */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return first_name;
}
public void setFirstName(String fname) {
this.first_name = fname;
}
public String getLastName() {
return last_name;
}
public void setlastName(String lname) {
this.last_name = lname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
} /* End of Employee */
To define SQL mapping statement using iBATIS, we would add <update> tag in Employee.xml and inside this tag definition, we would define an "id" which will be used in IbatisUpdate.java file for executing SQL UPDATE query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<insert id="insert" parameterClass="Employee">
INSERT INTO EMPLOYEE(first_name, last_name, salary)
values (#first_name#, #last_name#, #salary#)
<selectKey resultClass="int" keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>
<select id="getAll" resultClass="Employee">
SELECT * FROM EMPLOYEE
</select>
<update id="update" parameterClass="Employee">
UPDATE EMPLOYEE
SET first_name = #first_name#
WHERE id = #id#
</update>
</sqlMap>
This file has application level logic to update records into the Employee table −
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisUpdate{
public static void main(String[] args)
throws IOException,SQLException{
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
/* This would update one record in Employee table. */
System.out.println("Going to update record.....");
Employee rec = new Employee();
rec.setId(1);
rec.setFirstName( "Roma");
smc.update("Employee.update", rec );
System.out.println("Record updated Successfully ");
System.out.println("Going to read records.....");
List <Employee> ems = (List<Employee>)
smc.queryForList("Employee.getAll", null);
Employee em = null;
for (Employee e : ems) {
System.out.print(" " + e.getId());
System.out.print(" " + e.getFirstName());
System.out.print(" " + e.getLastName());
System.out.print(" " + e.getSalary());
em = e;
System.out.println("");
}
System.out.println("Records Read Successfully ");
}
}
Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisUpdate.java as shown above and compile it.
Execute IbatisUpdate binary to run the program.
You would get following result, and a record would be updated in EMPLOYEE table and later, the same record would be read from the EMPLOYEE table.
Going to update record.....
Record updated Successfully
Going to read records.....
1 Roma Ali 5000
Records Read Successfully
This chapter describes how to delete records from a table using iBATIS.
We have the following EMPLOYEE table in MySQL −
CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Assume this table has two records as follows −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 1 | Zara | Ali | 5000 |
| 2 | Roma | Ali | 3000 |
+----+------------+-----------+--------+
2 row in set (0.00 sec)
To perform delete operation, you do not need to modify Employee.java file. Let us keep it as it was in the last chapter.
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
/* Define constructors for the Employee class. */
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
/* Here are the required method definitions */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return first_name;
}
public void setFirstName(String fname) {
this.first_name = fname;
}
public String getLastName() {
return last_name;
}
public void setlastName(String lname) {
this.last_name = lname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
} /* End of Employee */
To define SQL mapping statement using iBATIS, we would add <delete> tag in Employee.xml and inside this tag definition, we would define an "id" which will be used in IbatisDelete.java file for executing SQL DELETE query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<insert id="insert" parameterClass="Employee">
INSERT INTO EMPLOYEE(first_name, last_name, salary)
values (#first_name#, #last_name#, #salary#)
<selectKey resultClass="int" keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>
<select id="getAll" resultClass="Employee">
SELECT * FROM EMPLOYEE
</select>
<update id="update" parameterClass="Employee">
UPDATE EMPLOYEE
SET first_name = #first_name#
WHERE id = #id#
</update>
<delete id="delete" parameterClass="int">
DELETE FROM EMPLOYEE
WHERE id = #id#
</delete>
</sqlMap>
This file has application level logic to delete records from the Employee table −
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisDelete{
public static void main(String[] args)
throws IOException,SQLException{
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
/* This would delete one record in Employee table. */
System.out.println("Going to delete record.....");
int id = 1;
smc.delete("Employee.delete", id );
System.out.println("Record deleted Successfully ");
System.out.println("Going to read records.....");
List <Employee> ems = (List<Employee>)
smc.queryForList("Employee.getAll", null);
Employee em = null;
for (Employee e : ems) {
System.out.print(" " + e.getId());
System.out.print(" " + e.getFirstName());
System.out.print(" " + e.getLastName());
System.out.print(" " + e.getSalary());
em = e;
System.out.println("");
}
System.out.println("Records Read Successfully ");
}
}
Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisDelete.java as shown above and compile it.
Execute IbatisDelete binary to run the program.
You would get the following result, and a record with ID = 1 would be deleted from the EMPLOYEE table and the rest of the records would be read.
Going to delete record.....
Record deleted Successfully
Going to read records.....
2 Roma Ali 3000
Records Read Successfully
The resultMap element is the most important and powerful element in iBATIS. You can reduce up to 90% JDBC coding using iBATIS ResultMap and in some cases, it allows you to do things that JDBC does not even support.
The design of ResultMaps is such that simple statements don't require explicit result mappings at all, and more complex statements require no more than is absolutely necessary to describe the relationships.
This chapter provides just a simple introduction of iBATIS ResultMaps.
We have the following EMPLOYEE table in MySQL −
CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
This table has two records as follows −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 1 | Zara | Ali | 5000 |
| 2 | Roma | Ali | 3000 |
+----+------------+-----------+--------+
2 row in set (0.00 sec)
To use iBATIS ResultMap, you do not need to modify the Employee.java file. Let us keep it as it was in the last chapter.
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
/* Define constructors for the Employee class. */
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
/* Here are the required method definitions */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return first_name;
}
public void setFirstName(String fname) {
this.first_name = fname;
}
public String getLastName() {
return last_name;
}
public void setlastName(String lname) {
this.last_name = lname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
} /* End of Employee */
Here we would modify Employee.xml to introduce <resultMap></resultMap> tag. This tag would have an id which is required to run this resultMap in our <select> tag's resultMap attribute.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<!-- Perform Insert Operation -->
<insert id="insert" parameterClass="Employee">
INSERT INTO EMPLOYEE(first_name, last_name, salary)
values (#first_name#, #last_name#, #salary#)
<selectKey resultClass="int" keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>
<!-- Perform Read Operation -->
<select id="getAll" resultClass="Employee">
SELECT * FROM EMPLOYEE
</select>
<!-- Perform Update Operation -->
<update id="update" parameterClass="Employee">
UPDATE EMPLOYEE
SET first_name = #first_name#
WHERE id = #id#
</update>
<!-- Perform Delete Operation -->
<delete id="delete" parameterClass="int">
DELETE FROM EMPLOYEE
WHERE id = #id#
</delete>
<!-- Using ResultMap -->
<resultMap id="result" class="Employee">
<result property="id" column="id"/>
<result property="first_name" column="first_name"/>
<result property="last_name" column="last_name"/>
<result property="salary" column="salary"/>
</resultMap>
<select id="useResultMap" resultMap="result">
SELECT * FROM EMPLOYEE
WHERE id=#id#
</select>
</sqlMap>
This file has application level logic to read records from the Employee table using ResultMap −
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisResultMap{
public static void main(String[] args)
throws IOException,SQLException{
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
int id = 1;
System.out.println("Going to read record.....");
Employee e = (Employee)smc.queryForObject ("Employee.useResultMap", id);
System.out.println("ID: " + e.getId());
System.out.println("First Name: " + e.getFirstName());
System.out.println("Last Name: " + e.getLastName());
System.out.println("Salary: " + e.getSalary());
System.out.println("Record read Successfully ");
}
}
Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisResultMap.java as shown above and compile it.
Execute IbatisResultMap binary to run the program.
You would get the following result which is a read operation on the EMPLOYEE table.
Going to read record.....
ID: 1
First Name: Zara
Last Name: Ali
Salary: 5000
Record read Successfully
You can call a stored procedure using iBATIS configuration. First of all, let us understand how to create a stored procedure in MySQL.
We have the following EMPLOYEE table in MySQL −
CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Let us create the following stored procedure in MySQL database −
DELIMITER $$
DROP PROCEDURE IF EXISTS `testdb`.`getEmp` $$
CREATE PROCEDURE `testdb`.`getEmp`
(IN empid INT)
BEGIN
SELECT * FROM EMPLOYEE
WHERE ID = empid;
END $$
DELIMITER;
Let’s consider the EMPLOYEE table has two records as follows −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 1 | Zara | Ali | 5000 |
| 2 | Roma | Ali | 3000 |
+----+------------+-----------+--------+
2 row in set (0.00 sec)
To use stored procedure, you do not need to modify the Employee.java file. Let us keep it as it was in the last chapter.
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
/* Define constructors for the Employee class. */
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
/* Here are the required method definitions */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return first_name;
}
public void setFirstName(String fname) {
this.first_name = fname;
}
public String getLastName() {
return last_name;
}
public void setlastName(String lname) {
this.last_name = lname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
} /* End of Employee */
Here we would modify Employee.xml to introduce <procedure></procedure> and <parameterMap></parameterMap> tags. Here <procedure></procedure> tag would have an id which we would use in our application to call the stored procedure.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<!-- Perform Insert Operation -->
<insert id="insert" parameterClass="Employee">
INSERT INTO EMPLOYEE(first_name, last_name, salary)
values (#first_name#, #last_name#, #salary#)
<selectKey resultClass="int" keyProperty="id">
select last_insert_id() as id
</selectKey>
</insert>
<!-- Perform Read Operation -->
<select id="getAll" resultClass="Employee">
SELECT * FROM EMPLOYEE
</select>
<!-- Perform Update Operation -->
<update id="update" parameterClass="Employee">
UPDATE EMPLOYEE
SET first_name = #first_name#
WHERE id = #id#
</update>
<!-- Perform Delete Operation -->
<delete id="delete" parameterClass="int">
DELETE FROM EMPLOYEE
WHERE id = #id#
</delete>
<!-- To call stored procedure. -->
<procedure id="getEmpInfo" resultClass="Employee" parameterMap="getEmpInfoCall">
{ call getEmp( #acctID# ) }
</procedure>
<parameterMap id="getEmpInfoCall" class="map">
<parameter property="acctID" jdbcType="INT" javaType="java.lang.Integer" mode="IN"/>
</parameterMap>
</sqlMap>
This file has application level logic to read the names of the employees from the Employee table using ResultMap −
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisSP{
public static void main(String[] args)
throws IOException,SQLException{
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
int id = 1;
System.out.println("Going to read employee name.....");
Employee e = (Employee) smc.queryForObject ("Employee.getEmpInfo", id);
System.out.println("First Name: " + e.getFirstName());
System.out.println("Record name Successfully ");
}
}
Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisSP.java as shown above and compile it.
Execute IbatisSP binary to run the program.
You would get the following result:
Going to read employee name.....
First Name: Zara
Record name Successfully
Dynamic SQL is a very powerful feature of iBATIS. Sometimes you have to change the WHERE clause criterion based on your parameter object's state. In such situations, iBATIS provides a set of dynamic SQL tags that can be used within mapped statements to enhance the reusability and flexibility of the SQL.
All the logic is put in .XML file using some additional tags. Following is an example where the SELECT statement would work in two ways −
If you pass an ID, then it would return all the records corresponding to that ID.
Otherwise, it would return all the records where employee ID is set to NULL.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<select id="findByID" resultClass="Employee">
SELECT * FROM EMPLOYEE
<dynamic prepend="WHERE ">
<isNull property="id">
id IS NULL
</isNull>
<isNotNull property="id">
id = #id#
</isNotNull>
</dynamic>
</select>
</sqlMap>
You can check a condition using the <isNotEmpty> tag as follows. Here a condition would be added only when a passed property is not empty.
..................
<select id="findByID" resultClass="Employee">
SELECT * FROM EMPLOYEE
<dynamic prepend="WHERE ">
<isNotEmpty property="id">
id = #id#
</isNotEmpty>
</dynamic>
</select>
..................
If you want a query where we can select an id and/or the first name of an Employee, your SELECT statement would be as follows −
..................
<select id="findByID" resultClass="Employee">
SELECT * FROM EMPLOYEE
<dynamic prepend="WHERE ">
<isNotEmpty prepend="AND" property="id">
id = #id#
</isNotEmpty>
<isNotEmpty prepend="OR" property="first_name">
first_name = #first_name#
</isNotEmpty>
</dynamic>
</select>
..................
The following example shows how you can write a SELECT statement with dynamic SQL. Consider, we have the following EMPLOYEE table in MySQL −
CREATE TABLE EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Let’s assume this table has only one record as follows −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 1 | Zara | Ali | 5000 |
+----+------------+-----------+--------+
1 row in set (0.00 sec)
To perform read operation, let us have an Employee class in Employee.java as follows −
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
/* Define constructors for the Employee class. */
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
/* Here are the method definitions */
public int getId() {
return id;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {
return last_name;
}
public int getSalary() {
return salary;
}
} /* End of Employee */
To define SQL mapping statement using iBATIS, we would add the following modified <select> tag in Employee.xml and inside this tag definition, we would define an "id" which will be used in IbatisReadDy.java for executing Dynamic SQL SELECT query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
<select id="findByID" resultClass="Employee">
SELECT * FROM EMPLOYEE
<dynamic prepend="WHERE ">
<isNotNull property="id">
id = #id#
</isNotNull>
</dynamic>
</select>
</sqlMap>
The above SELECT statement would work in two ways −
If you pass an ID, then it returns records corresponding to that ID Otherwise, it returns all the records.
If you pass an ID, then it returns records corresponding to that ID Otherwise, it returns all the records.
This file has application level logic to read conditional records from the Employee table −
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisReadDy{
public static void main(String[] args)
throws IOException,SQLException{
Reader rd=Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc=SqlMapClientBuilder.buildSqlMapClient(rd);
/* This would read all records from the Employee table.*/
System.out.println("Going to read records.....");
Employee rec = new Employee();
rec.setId(1);
List <Employee> ems = (List<Employee>)
smc.queryForList("Employee.findByID", rec);
Employee em = null;
for (Employee e : ems) {
System.out.print(" " + e.getId());
System.out.print(" " + e.getFirstName());
System.out.print(" " + e.getLastName());
System.out.print(" " + e.getSalary());
em = e;
System.out.println("");
}
System.out.println("Records Read Successfully ");
}
}
Here are the steps to compile and run the above mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisReadDy.java as shown above and compile it.
Execute IbatisReadDy binary to run the program.
You would get the following result, and a record would be read from the EMPLOYEE table.
Going to read records.....
1 Zara Ali 5000
Record Reads Successfully
Try the above example by passing null as smc.queryForList("Employee.findByID", null).
iBATIS provides powerful OGNL based expressions to eliminate most of the other elements.
if Statement
choose, when, otherwise Statement
where Statement
foreach Statement
The most common thing to do in dynamic SQL is conditionally include a part of a where clause. For example −
<select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog">
SELECT * FROM BLOG
WHERE state = 'ACTIVE.
<if test="title != null">
AND title like #{title}
</if>
</select>
This statement provides an optional text search type of functionality. If you pass in no title, then all active Blogs are returned. But if you do pass in a title, it will look for a title with the given like condition.
You can include multiple if conditions as follows −
<select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog">
SELECT * FROM BLOG
WHERE state = 'ACTIVE.
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null">
AND author like #{author}
</if>
</select>
iBATIS offers a choose element which is similar to Java's switch statement. It helps choose only one case among many options.
The following example would search only by title if one is provided, then only by author if one is provided. If neither is provided, it returns only featured blogs −
<select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog">
SELECT * FROM BLOG
WHERE state = 'ACTIVE.
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author like #{author}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
Take a look at our previous examples to see what happens if none of the conditions are met. You would end up with an SQL that looks like this −
SELECT * FROM BLOG
WHERE
This would fail, but iBATIS has a simple solution with one simple change, everything works fine −
<select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null>
AND author like #{author}
</if>
</where>
</select>
The where element inserts a WHERE only when the containing tags return any content. Furthermore, if that content begins with AND or OR, it knows to strip it off.
The foreach element allows you to specify a collection and declare item and index variables that can be used inside the body of the element.
It also allows you to specify opening and closing strings, and add a separator to place in between iterations. You can build an IN condition as follows −
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
It is easy to debug your program while working with iBATIS. iBATIS has built-in logging support and it works with the following logging libraries and searches for them in this order.
Jakarta Commons Logging (JCL).
Log4J
JDK logging
You can use any of the above listed libraries along with iBATIS.
Assuming you are going to use Log4J for logging. Before proceeding, you need to cross-check the following points −
The Log4J JAR file (log4j-{version}.jar) should be in the CLASSPATH.
You have log4j.properties available in the CLASSPATH.
Following is the log4j.properties file. Note that some of the lines are commented out. You can uncomment them if you need additional debugging information.
# Global logging configuration
log4j.rootLogger = ERROR, stdout
log4j.logger.com.ibatis = DEBUG
# shows SQL of prepared statements
#log4j.logger.java.sql.Connection = DEBUG
# shows parameters inserted into prepared statements
#log4j.logger.java.sql.PreparedStatement = DEBUG
# shows query results
#log4j.logger.java.sql.ResultSet = DEBUG
#log4j.logger.java.sql.Statement = DEBUG
# Console output
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %5p [%t] − %m%n
You can find the complete documentation for Log4J from Apaches site − Log4J Documentation.
The following Java class is a very simple example that initializes and then uses the Log4J logging library for Java applications. We would use the above-mentioned property file which lies in CLASSPATH.
import org.apache.log4j.Logger;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.*;
import java.sql.SQLException;
import java.util.*;
public class IbatisUpdate{
static Logger log = Logger.getLogger(IbatisUpdate.class.getName());
public static void main(String[] args)
throws IOException,SQLException{
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
/* This would insert one record in Employee table. */
log.info("Going to update record.....");
Employee rec = new Employee();
rec.setId(1);
rec.setFirstName( "Roma");
smc.update("Employee.update", rec );
log.info("Record updated Successfully ");
log.debug("Going to read records.....");
List <Employee> ems = (List<Employee>)
smc.queryForList("Employee.getAll", null);
Employee em = null;
for (Employee e : ems) {
System.out.print(" " + e.getId());
System.out.print(" " + e.getFirstName());
System.out.print(" " + e.getLastName());
System.out.print(" " + e.getSalary());
em = e;
System.out.println("");
}
log.debug("Records Read Successfully ");
}
}
First of all, make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Employee.xml as shown above.
Create Employee.java as shown above and compile it.
Create IbatisUpdate.java as shown above and compile it.
Create log4j.properties as shown above.
Execute IbatisUpdate binary to run the program.
You would get the following result. A record would be updated in the EMPLOYEE table and later, the same record would be read from the EMPLOYEE table.
DEBUG [main] - Created connection 28405330.
DEBUG [main] - Returned connection 28405330 to pool.
DEBUG [main] - Checked out connection 28405330 from pool.
DEBUG [main] - Returned connection 28405330 to pool.
1 Roma Ali 5000
2 Zara Ali 5000
3 Zara Ali 5000
In the above example, we used only info() method, however you can use any of the following methods as per your requirements −
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);
There are major differences between iBATIS and Hibernate. Both the solutions work well, given their specific domain. iBATIS is suggested in case −
You want to create your own SQL's and you are willing to maintain them.
Your environment is driven by relational data model.
You have to work on existing and complex schemas.
Use Hibernate if the environment is driven by object model and needs to generate SQL automatically.
Both Hibernate and iBATIS are open source Object Relational Mapping (ORM) tools available in the industry. Use of each of these tools depends on the context you are using them.
The following table highlights the differences between iBATIS and Hibernate −
Both Hibernate and iBATIS receive good support from the SPRING framework, so it should not be a problem to choose one of them.
iBATOR is a code generator for iBATIS. iBATOR introspects one or more database tables and generates iBATIS artifacts that can be used to access the tables.
Later you can write your custom SQL code or stored procedure to meet your requirements. iBATOR generates the following artifacts −
SqlMap XML Files
Java Classes to match the primary key and fields of the table(s)
DAO Classes that use the above objects (optional)
iBATOR can run as a standalone JAR file, or as an Ant task, or as an Eclipse plugin. This tutorial describes the simplest way of generating iBATIS configuration files from command line.
Download the standalone JAR if you are using an IDE other than Eclipse. The standalone JAR includes an Ant task to run iBATOR, or you can run iBATOR from the command line of Java code.
You can download zip file from Download iBATOR.
You can download zip file from Download iBATOR.
You can check online documentation − iBATOR Documentation.
You can check online documentation − iBATOR Documentation.
To run iBATOR, follow these steps −
Create and fill a configuration file ibatorConfig.xml appropriately. At a minimum, you must specify −
A <jdbcConnection> element to specify how to connect to the target database.
A <jdbcConnection> element to specify how to connect to the target database.
A <javaModelGenerator> element to specify the target package and the target project for the generated Java model objects.
A <javaModelGenerator> element to specify the target package and the target project for the generated Java model objects.
A <sqlMapGenerator> element to specify the target package and the target project for the generated SQL map files.
A <sqlMapGenerator> element to specify the target package and the target project for the generated SQL map files.
A <daoGenerator> element to specify the target package and the target project for the generated DAO interfaces and classes (you may omit the <daoGenerator> element if you don't wish to generate DAOs).
A <daoGenerator> element to specify the target package and the target project for the generated DAO interfaces and classes (you may omit the <daoGenerator> element if you don't wish to generate DAOs).
At least one database <table> element
At least one database <table> element
NOTE − See the XML Configuration File Reference page for an example of an iBATOR configuration file.
Save the file in a convenient location, for example, at: \temp\ibatorConfig.xml.
Now run iBATOR from the command line as follows −
java -jar abator.jar -configfile \temp\abatorConfig.xml -overwrite
It will tell iBATOR to run using your configuration file. It will also tell iBATOR to overwrite any existing Java files with the same name. If you want to save any existing Java files, then omit the −overwrite parameter.
If there is a conflict, iBATOR saves the newly generated file with a unique name.
After running iBATOR, you need to create or modify the standard iBATIS configuration files to make use of your newly generated code. This is explained in the next section.
After you run iBATOR, you need to create or modify other iBATIS configuration artifacts. The main tasks are as follows −
Create or modify the SqlMapConfig.xml file.
Create or modify the dao.xml file (only if you are using the iBATIS DAO Framework).
Each task is described in detail below −
iBATIS uses an XML file, commonly named SqlMapConfig.xml, to specify information for a database connection, a transaction management scheme, and SQL map XML files that are used in an iBATIS session.
iBATOR cannot create this file for you because it knows nothing about your execution environment. However, some of the items in this file relate directly to iBATOR generated items.
iBATOR specific needs in the configuration file are as follows −
Statement namespaces must be enabled.
iBATOR generated SQL Map XML files must be listed.
For example, suppose iBATOR has generated an SQL Map XML file called MyTable_SqlMap.xml, and that the file has been placed in the test.xml package of your project. The SqlMapConfig.xml file should have these entries −
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- Statement namespaces are required for Abator -->
<settings useStatementNamespaces="true" />
<!-- Setup the transaction manager and data source that are
appropriate for your environment
-->
<transactionManager type="...">
<dataSource type="...">
</dataSource>
</transactionManager>
<!-- SQL Map XML files should be listed here -->
<sqlMap resource="test/xml/MyTable_SqlMap.xml" />
</sqlMapConfig>
If there is more than one SQL Map XML file (as is quite common), then the files can be listed in any order with repeated <sqlMap> elements after the <transactionManager> element.
The iBATIS DAO framework is configured by an xml file commonly called dao.xml.
The iBATIS DAO framework uses this file to control the database connection information for DAOs, and also to list the DAO implementation classes and DAO interfaces.
In this file, you should specify the path to your SqlMapConfig.xml file, and all the iBATOR generated DAO interfaces and implementation classes.
For example, suppose iBATOR has generated a DAO interface called MyTableDAO and an implementation class called MyTableDAOImpl, and that the files have been placed in the test.dao package of your project.
The dao.xml file should have these entries −
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE daoConfig PUBLIC "-//ibatis.apache.org//DTD DAO Configuration 2.0//EN" "http://ibatis.apache.org/dtd/dao-2.dtd">
<daoConfig>
<context>
<transactionManager type="SQLMAP">
<property name="SqlMapConfigResource" value="test/SqlMapConfig.xml"/>
</transactionManager>
<!-- DAO interfaces and implementations should be listed here -->
<dao interface="test.dao.MyTableDAO" implementation="test.dao.MyTableDAOImpl" />
</context>
</daoConfig>
NOTE − This step is required only if you generated DAOs for the iBATIS DAO framework.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2088,
"s": 1844,
"text": "iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. The mappings are decoupled from the application logic by packaging the SQL statements in XML configuration files."
},
{
"code": null,
"e": 2194,
"s": 2088,
"text": "iBATIS is a lightweight framework and persistence API good for persisting POJOs( Plain Old Java Objects)."
},
{
"code": null,
"e": 2356,
"s": 2194,
"text": "iBATIS is what is known as a data mapper and takes care of mapping the parameters and results between the class properties and the columns of the database table."
},
{
"code": null,
"e": 2643,
"s": 2356,
"text": "A significant difference between iBATIS and other persistence frameworks such as Hibernate is that iBATIS emphasizes the use of SQL, while other frameworks typically use a custom query language such has the Hibernate Query Language (HQL) or Enterprise JavaBeans Query Language (EJB QL)."
},
{
"code": null,
"e": 2697,
"s": 2643,
"text": "iBATIS comes with the following design philosophies −"
},
{
"code": null,
"e": 2805,
"s": 2697,
"text": "Simplicity − iBATIS is widely regarded as being one of the simplest persistence frameworks available today."
},
{
"code": null,
"e": 2913,
"s": 2805,
"text": "Simplicity − iBATIS is widely regarded as being one of the simplest persistence frameworks available today."
},
{
"code": null,
"e": 2993,
"s": 2913,
"text": "Fast Development − iBATIS does all it can to facilitate hyper-fast development."
},
{
"code": null,
"e": 3073,
"s": 2993,
"text": "Fast Development − iBATIS does all it can to facilitate hyper-fast development."
},
{
"code": null,
"e": 3196,
"s": 3073,
"text": "Portability − iBATIS can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET."
},
{
"code": null,
"e": 3319,
"s": 3196,
"text": "Portability − iBATIS can be implemented for nearly any language or platform such as Java, Ruby, and C# for Microsoft .NET."
},
{
"code": null,
"e": 3496,
"s": 3319,
"text": "Independent Interfaces − iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources."
},
{
"code": null,
"e": 3673,
"s": 3496,
"text": "Independent Interfaces − iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources."
},
{
"code": null,
"e": 3731,
"s": 3673,
"text": "Open source − iBATIS is free and an open source software."
},
{
"code": null,
"e": 3789,
"s": 3731,
"text": "Open source − iBATIS is free and an open source software."
},
{
"code": null,
"e": 3830,
"s": 3789,
"text": "iBATIS offers the following advantages −"
},
{
"code": null,
"e": 4040,
"s": 3830,
"text": "Supports stored procedures − iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable."
},
{
"code": null,
"e": 4250,
"s": 4040,
"text": "Supports stored procedures − iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable."
},
{
"code": null,
"e": 4354,
"s": 4250,
"text": "Supports inline SQL − No precompiler is needed, and you have full access to all of the features of SQL."
},
{
"code": null,
"e": 4458,
"s": 4354,
"text": "Supports inline SQL − No precompiler is needed, and you have full access to all of the features of SQL."
},
{
"code": null,
"e": 4564,
"s": 4458,
"text": "Supports dynamic SQL − iBATIS provides features for dynamically building SQL queries based on parameters."
},
{
"code": null,
"e": 4670,
"s": 4564,
"text": "Supports dynamic SQL − iBATIS provides features for dynamically building SQL queries based on parameters."
},
{
"code": null,
"e": 4832,
"s": 4670,
"text": "Supports O/RM − iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance"
},
{
"code": null,
"e": 4994,
"s": 4832,
"text": "Supports O/RM − iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance"
},
{
"code": null,
"e": 5278,
"s": 4994,
"text": "iBATIS makes use of JAVA programming language while developing database oriented application. Before proceeding further, make sure that you understand the basics of procedural and object-oriented programming − control structures, data structures and variables, classes, objects, etc."
},
{
"code": null,
"e": 5345,
"s": 5278,
"text": "To understand JAVA in detail you can go through our JAVA Tutorial."
},
{
"code": null,
"e": 5522,
"s": 5345,
"text": "You would have to set up a proper environment for iBATIS before starting off with actual development work. This chapter explains how to set up a working environment for iBATIS."
},
{
"code": null,
"e": 5601,
"s": 5522,
"text": "Carry out the following simple steps to install iBATIS on your Linux machine −"
},
{
"code": null,
"e": 5661,
"s": 5601,
"text": "Download the latest version of iBATIS from Download iBATIS."
},
{
"code": null,
"e": 5721,
"s": 5661,
"text": "Download the latest version of iBATIS from Download iBATIS."
},
{
"code": null,
"e": 5828,
"s": 5721,
"text": "Unzip the downloaded file to extract .jar file from the bundle and keep them in appropriate lib directory."
},
{
"code": null,
"e": 5935,
"s": 5828,
"text": "Unzip the downloaded file to extract .jar file from the bundle and keep them in appropriate lib directory."
},
{
"code": null,
"e": 6013,
"s": 5935,
"text": "Set PATH and CLASSPATH variables at the extracted .jar file(s) appropriately."
},
{
"code": null,
"e": 6091,
"s": 6013,
"text": "Set PATH and CLASSPATH variables at the extracted .jar file(s) appropriately."
},
{
"code": null,
"e": 6764,
"s": 6091,
"text": "$ unzip ibatis-2.3.4.726.zip\ninflating: META-INF/MANIFEST.MF\n creating: doc/\n creating: lib/\n\t\n creating: simple_example/\n creating: simple_example/com/\n creating: simple_example/com/mydomain/\n creating: simple_example/com/mydomain/data/\n creating: simple_example/com/mydomain/domain/\n\t\n creating: src/\n\t\n inflating: doc/dev-javadoc.zip\n inflating: doc/user-javadoc.zip\n \n inflating: jar-dependencies.txt\n inflating: lib/ibatis-2.3.4.726.jar\n inflating: license.txt\n inflating: notice.txt\n inflating: release.txt\n \n$pwd\n/var/home/ibatis\n$set PATH=$PATH:/var/home/ibatis/\n$set CLASSPATH=$CLASSPATH:/var/home/ibatis\\\n /lib/ibatis-2.3.4.726.jar\n"
},
{
"code": null,
"e": 6840,
"s": 6764,
"text": "Create an EMPLOYEE table in any MySQL database using the following syntax −"
},
{
"code": null,
"e": 7043,
"s": 6840,
"text": "mysql> CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 7068,
"s": 7043,
"text": "Consider the following −"
},
{
"code": null,
"e": 7124,
"s": 7068,
"text": "We are going to use JDBC to access the database testdb."
},
{
"code": null,
"e": 7180,
"s": 7124,
"text": "We are going to use JDBC to access the database testdb."
},
{
"code": null,
"e": 7230,
"s": 7180,
"text": "JDBC driver for MySQL is \"com.mysql.jdbc.Driver\"."
},
{
"code": null,
"e": 7280,
"s": 7230,
"text": "JDBC driver for MySQL is \"com.mysql.jdbc.Driver\"."
},
{
"code": null,
"e": 7336,
"s": 7280,
"text": "Connection URL is \"jdbc:mysql://localhost:3306/testdb\"."
},
{
"code": null,
"e": 7392,
"s": 7336,
"text": "Connection URL is \"jdbc:mysql://localhost:3306/testdb\"."
},
{
"code": null,
"e": 7462,
"s": 7392,
"text": "We would use username and password as \"root\" and \"root\" respectively."
},
{
"code": null,
"e": 7532,
"s": 7462,
"text": "We would use username and password as \"root\" and \"root\" respectively."
},
{
"code": null,
"e": 7620,
"s": 7532,
"text": "Our sql statement mappings for all the operations would be described in \"Employee.xml\"."
},
{
"code": null,
"e": 7708,
"s": 7620,
"text": "Our sql statement mappings for all the operations would be described in \"Employee.xml\"."
},
{
"code": null,
"e": 7914,
"s": 7708,
"text": "Based on the above assumptions, we have to create an XML configuration file with name SqlMapConfig.xml with the following content. This is where you need to provide all configurations required for iBatis −"
},
{
"code": null,
"e": 8124,
"s": 7914,
"text": "It is important that both the files SqlMapConfig.xml and Employee.xml should be present in the class path. For now, we would keep Employee.xml file empty and we would cover its contents in subsequent chapters."
},
{
"code": null,
"e": 8807,
"s": 8124,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMapConfig PUBLIC \"-//ibatis.apache.org//DTD SQL Map Config 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-config-2.dtd\">\n\n<sqlMapConfig>\n <settings useStatementNamespaces=\"true\"/>\n\t\n <transactionManager type=\"JDBC\">\n <dataSource type=\"SIMPLE\">\n\t\t\n <property name=\"JDBC.Driver\" value=\"com.mysql.jdbc.Driver\"/>\n <property name=\"JDBC.ConnectionURL\" value=\"jdbc:mysql://localhost:3306/testdb\"/>\n <property name=\"JDBC.Username\" value=\"root\"/>\n <property name=\"JDBC.Password\" value=\"root\"/>\n\t\t\t\n </dataSource>\n </transactionManager>\n\t\n <sqlMap resource=\"Employee.xml\"/> \n</sqlMapConfig>"
},
{
"code": null,
"e": 8891,
"s": 8807,
"text": "You can set the following optional properties as well using SqlMapConfig.xml file −"
},
{
"code": null,
"e": 9288,
"s": 8891,
"text": "<property name=\"JDBC.AutoCommit\" value=\"true\"/>\n<property name=\"Pool.MaximumActiveConnections\" value=\"10\"/>\n<property name=\"Pool.MaximumIdleConnections\" value=\"5\"/>\n<property name=\"Pool.MaximumCheckoutTime\" value=\"150000\"/> \n<property name=\"Pool.MaximumTimeToWait\" value=\"500\"/> \n<property name=\"Pool.PingQuery\" value=\"select 1 from Employee\"/> \n<property name=\"Pool.PingEnabled\" value=\"false\"/>\n"
},
{
"code": null,
"e": 9530,
"s": 9288,
"text": "To perform any Create, Read, Update, and Delete (CRUD) operation using iBATIS, you would need to create a Plain Old Java Objects (POJO) class corresponding to the table. This class describes the objects that will \"model\" database table rows."
},
{
"code": null,
"e": 9631,
"s": 9530,
"text": "The POJO class would have implementation for all the methods required to perform desired operations."
},
{
"code": null,
"e": 9693,
"s": 9631,
"text": "Let us assume we have the following EMPLOYEE table in MySQL −"
},
{
"code": null,
"e": 9889,
"s": 9693,
"text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 9958,
"s": 9889,
"text": "We would create an Employee class in Employee.java file as follows −"
},
{
"code": null,
"e": 10349,
"s": 9958,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n} /* End of Employee */"
},
{
"code": null,
"e": 10481,
"s": 10349,
"text": "You can define methods to set individual fields in the table. The next chapter explains how to get the values of individual fields."
},
{
"code": null,
"e": 10698,
"s": 10481,
"text": "To define SQL mapping statement using iBATIS, we would use <insert> tag and inside this tag definition, we would define an \"id\" which will be used in IbatisInsert.java file for executing SQL INSERT query on database."
},
{
"code": null,
"e": 11180,
"s": 10698,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\"> \n\n <insert id=\"insert\" parameterClass=\"Employee\">\n insert into EMPLOYEE(first_name, last_name, salary)\n values (#first_name#, #last_name#, #salary#)\n\n <selectKey resultClass=\"int\" keyProperty=\"id\">\n select last_insert_id() as id\n </selectKey>\n </insert> \n\n</sqlMap>"
},
{
"code": null,
"e": 11401,
"s": 11180,
"text": "Here parameterClass − could take a value as string, int, float, double, or any class object based on requirement. In this example, we would pass Employee object as a parameter while calling insert method of SqlMap class."
},
{
"code": null,
"e": 11626,
"s": 11401,
"text": "If your database table uses an IDENTITY, AUTO_INCREMENT, or SERIAL column or you have defined a SEQUENCE/GENERATOR, you can use the <selectKey> element in an <insert> statement to use or return that database-generated value."
},
{
"code": null,
"e": 11713,
"s": 11626,
"text": "This file would have application level logic to insert records in the Employee table −"
},
{
"code": null,
"e": 12449,
"s": 11713,
"text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisInsert{\n public static void main(String[] args)throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n /* This would insert one record in Employee table. */\n System.out.println(\"Going to insert record.....\");\n Employee em = new Employee(\"Zara\", \"Ali\", 5000);\n\n smc.insert(\"Employee.insert\", em);\n\n System.out.println(\"Record Inserted Successfully \");\n }\n} "
},
{
"code": null,
"e": 12622,
"s": 12449,
"text": "Here are the steps to compile and run the above mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 12658,
"s": 12622,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 12710,
"s": 12658,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 12766,
"s": 12710,
"text": "Create IbatisInsert.java as shown above and compile it."
},
{
"code": null,
"e": 12814,
"s": 12766,
"text": "Execute IbatisInsert binary to run the program."
},
{
"code": null,
"e": 12903,
"s": 12814,
"text": "You would get the following result, and a record would be created in the EMPLOYEE table."
},
{
"code": null,
"e": 12980,
"s": 12903,
"text": "$java IbatisInsert\nGoing to insert record.....\nRecord Inserted Successfully\n"
},
{
"code": null,
"e": 13054,
"s": 12980,
"text": "If you check the EMPLOYEE table, it should display the following result −"
},
{
"code": null,
"e": 13315,
"s": 13054,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n+----+------------+-----------+--------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 13463,
"s": 13315,
"text": "We discussed, in the last chapter, how to perform CREATE operation on a table using iBATIS. This chapter explains how to read a table using iBATIS."
},
{
"code": null,
"e": 13511,
"s": 13463,
"text": "We have the following EMPLOYEE table in MySQL −"
},
{
"code": null,
"e": 13707,
"s": 13511,
"text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 13751,
"s": 13707,
"text": "This table has only one record as follows −"
},
{
"code": null,
"e": 14012,
"s": 13751,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n+----+------------+-----------+--------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 14104,
"s": 14012,
"text": "To perform read operation, we would modify the Employee class in Employee.java as follows −"
},
{
"code": null,
"e": 14771,
"s": 14104,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n\n /* Here are the method definitions */\n public int getId() {\n return id;\n }\n\t\n public String getFirstName() {\n return first_name;\n }\n\t\n public String getLastName() {\n return last_name;\n }\n\t\n public int getSalary() {\n return salary;\n }\n\t\n} /* End of Employee */"
},
{
"code": null,
"e": 15007,
"s": 14771,
"text": "To define SQL mapping statement using iBATIS, we would add <select> tag in Employee.xml file and inside this tag definition, we would define an \"id\" which will be used in IbatisRead.java file for executing SQL SELECT query on database."
},
{
"code": null,
"e": 15579,
"s": 15007,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n\n <insert id=\"insert\" parameterClass=\"Employee\">\n INSERT INTO EMPLOYEE(first_name, last_name, salary)\n values (#first_name#, #last_name#, #salary#)\n\n <selectKey resultClass=\"int\" keyProperty=\"id\">\n select last_insert_id() as id\n </selectKey>\n </insert>\n\t\n <select id=\"getAll\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n </select>\n\t\n</sqlMap>"
},
{
"code": null,
"e": 15783,
"s": 15579,
"text": "Here we did not use WHERE clause with SQL SELECT statement. We would demonstrate, in the next chapter, how you can use WHERE clause with SELECT statement and how you can pass values to that WHERE clause."
},
{
"code": null,
"e": 15863,
"s": 15783,
"text": "This file has application level logic to read records from the Employee table −"
},
{
"code": null,
"e": 16920,
"s": 15863,
"text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisRead{\n public static void main(String[] args)throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n /* This would read all records from the Employee table. */\n System.out.println(\"Going to read records.....\");\n List <Employee> ems = (List<Employee>)\n smc.queryForList(\"Employee.getAll\", null);\n Employee em = null;\n\t\t\n for (Employee e : ems) {\n System.out.print(\" \" + e.getId());\n System.out.print(\" \" + e.getFirstName());\n System.out.print(\" \" + e.getLastName());\n System.out.print(\" \" + e.getSalary());\n em = e; \n System.out.println(\"\");\n } \n\t\t\n System.out.println(\"Records Read Successfully \");\n }\n} "
},
{
"code": null,
"e": 17093,
"s": 16920,
"text": "Here are the steps to compile and run the above mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 17129,
"s": 17093,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 17181,
"s": 17129,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 17235,
"s": 17181,
"text": "Create IbatisRead.java as shown above and compile it."
},
{
"code": null,
"e": 17281,
"s": 17235,
"text": "Execute IbatisRead binary to run the program."
},
{
"code": null,
"e": 17381,
"s": 17281,
"text": "You would get the following result, and a record would be read from the EMPLOYEE table as follows −"
},
{
"code": null,
"e": 17457,
"s": 17381,
"text": "Going to read records.....\n 1 Zara Ali 5000\nRecord Reads Successfully\n"
},
{
"code": null,
"e": 17621,
"s": 17457,
"text": "We discussed, in the last chapter, how to perform READ operation on a table using iBATIS. This chapter explains how you can update records in a table using iBATIS."
},
{
"code": null,
"e": 17669,
"s": 17621,
"text": "We have the following EMPLOYEE table in MySQL −"
},
{
"code": null,
"e": 17865,
"s": 17669,
"text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 17909,
"s": 17865,
"text": "This table has only one record as follows −"
},
{
"code": null,
"e": 18170,
"s": 17909,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n+----+------------+-----------+--------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 18256,
"s": 18170,
"text": "To perform udpate operation, you would need to modify Employee.java file as follows −"
},
{
"code": null,
"e": 19223,
"s": 18256,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n\n /* Here are the required method definitions */\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getFirstName() {\n return first_name;\n }\n\t\n public void setFirstName(String fname) {\n this.first_name = fname;\n }\n\t\n public String getLastName() {\n return last_name;\n }\n public void setlastName(String lname) {\n this.last_name = lname;\n }\n\t\n public int getSalary() {\n return salary;\n }\n\t\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n} /* End of Employee */"
},
{
"code": null,
"e": 19456,
"s": 19223,
"text": "To define SQL mapping statement using iBATIS, we would add <update> tag in Employee.xml and inside this tag definition, we would define an \"id\" which will be used in IbatisUpdate.java file for executing SQL UPDATE query on database."
},
{
"code": null,
"e": 20175,
"s": 19456,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n\n <insert id=\"insert\" parameterClass=\"Employee\">\n INSERT INTO EMPLOYEE(first_name, last_name, salary)\n values (#first_name#, #last_name#, #salary#)\n\n <selectKey resultClass=\"int\" keyProperty=\"id\">\n select last_insert_id() as id\n </selectKey>\n </insert>\n\n <select id=\"getAll\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n </select>\n\n <update id=\"update\" parameterClass=\"Employee\">\n UPDATE EMPLOYEE\n SET first_name = #first_name#\n WHERE id = #id#\n </update>\n\t\n</sqlMap>"
},
{
"code": null,
"e": 20257,
"s": 20175,
"text": "This file has application level logic to update records into the Employee table −"
},
{
"code": null,
"e": 21562,
"s": 20257,
"text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisUpdate{\n public static void main(String[] args)\n throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n /* This would update one record in Employee table. */\n System.out.println(\"Going to update record.....\");\n Employee rec = new Employee();\n rec.setId(1);\n rec.setFirstName( \"Roma\");\n smc.update(\"Employee.update\", rec );\n System.out.println(\"Record updated Successfully \");\n\n System.out.println(\"Going to read records.....\");\n List <Employee> ems = (List<Employee>)\n smc.queryForList(\"Employee.getAll\", null);\n Employee em = null;\n\t\t\n for (Employee e : ems) {\n System.out.print(\" \" + e.getId());\n System.out.print(\" \" + e.getFirstName());\n System.out.print(\" \" + e.getLastName());\n System.out.print(\" \" + e.getSalary());\n em = e; \n System.out.println(\"\");\n } \n\n System.out.println(\"Records Read Successfully \");\n }\n} "
},
{
"code": null,
"e": 21735,
"s": 21562,
"text": "Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 21771,
"s": 21735,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 21823,
"s": 21771,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 21879,
"s": 21823,
"text": "Create IbatisUpdate.java as shown above and compile it."
},
{
"code": null,
"e": 21927,
"s": 21879,
"text": "Execute IbatisUpdate binary to run the program."
},
{
"code": null,
"e": 22073,
"s": 21927,
"text": "You would get following result, and a record would be updated in EMPLOYEE table and later, the same record would be read from the EMPLOYEE table."
},
{
"code": null,
"e": 22205,
"s": 22073,
"text": "Going to update record.....\nRecord updated Successfully\nGoing to read records.....\n 1 Roma Ali 5000\nRecords Read Successfully\n"
},
{
"code": null,
"e": 22277,
"s": 22205,
"text": "This chapter describes how to delete records from a table using iBATIS."
},
{
"code": null,
"e": 22325,
"s": 22277,
"text": "We have the following EMPLOYEE table in MySQL −"
},
{
"code": null,
"e": 22521,
"s": 22325,
"text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 22568,
"s": 22521,
"text": "Assume this table has two records as follows −"
},
{
"code": null,
"e": 22870,
"s": 22568,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n| 2 | Roma | Ali | 3000 |\n+----+------------+-----------+--------+\n2 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 22991,
"s": 22870,
"text": "To perform delete operation, you do not need to modify Employee.java file. Let us keep it as it was in the last chapter."
},
{
"code": null,
"e": 23960,
"s": 22991,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n\n /* Here are the required method definitions */\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getFirstName() {\n return first_name;\n }\n\t\n public void setFirstName(String fname) {\n this.first_name = fname;\n }\n\t\n public String getLastName() {\n return last_name;\n }\n\t\n public void setlastName(String lname) {\n this.last_name = lname;\n }\n\t\n public int getSalary() {\n return salary;\n }\n\t\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n} /* End of Employee */"
},
{
"code": null,
"e": 24193,
"s": 23960,
"text": "To define SQL mapping statement using iBATIS, we would add <delete> tag in Employee.xml and inside this tag definition, we would define an \"id\" which will be used in IbatisDelete.java file for executing SQL DELETE query on database."
},
{
"code": null,
"e": 25020,
"s": 24193,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n\n <insert id=\"insert\" parameterClass=\"Employee\">\n INSERT INTO EMPLOYEE(first_name, last_name, salary)\n values (#first_name#, #last_name#, #salary#)\n\n <selectKey resultClass=\"int\" keyProperty=\"id\">\n select last_insert_id() as id\n </selectKey>\n </insert>\n\n <select id=\"getAll\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n </select>\n\n <update id=\"update\" parameterClass=\"Employee\">\n UPDATE EMPLOYEE\n SET first_name = #first_name#\n WHERE id = #id#\n </update>\n\n <delete id=\"delete\" parameterClass=\"int\">\n DELETE FROM EMPLOYEE\n WHERE id = #id#\n </delete>\n\n</sqlMap>"
},
{
"code": null,
"e": 25102,
"s": 25020,
"text": "This file has application level logic to delete records from the Employee table −"
},
{
"code": null,
"e": 26335,
"s": 25102,
"text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisDelete{\n public static void main(String[] args)\n throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n /* This would delete one record in Employee table. */\n System.out.println(\"Going to delete record.....\");\n int id = 1;\n\n smc.delete(\"Employee.delete\", id );\n System.out.println(\"Record deleted Successfully \");\n\n System.out.println(\"Going to read records.....\");\n List <Employee> ems = (List<Employee>)\n smc.queryForList(\"Employee.getAll\", null);\n Employee em = null;\n\t\t\n for (Employee e : ems) {\n System.out.print(\" \" + e.getId());\n System.out.print(\" \" + e.getFirstName());\n System.out.print(\" \" + e.getLastName());\n System.out.print(\" \" + e.getSalary());\n em = e; \n System.out.println(\"\");\n } \n\n System.out.println(\"Records Read Successfully \");\n }\n} "
},
{
"code": null,
"e": 26508,
"s": 26335,
"text": "Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 26544,
"s": 26508,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 26596,
"s": 26544,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 26652,
"s": 26596,
"text": "Create IbatisDelete.java as shown above and compile it."
},
{
"code": null,
"e": 26700,
"s": 26652,
"text": "Execute IbatisDelete binary to run the program."
},
{
"code": null,
"e": 26845,
"s": 26700,
"text": "You would get the following result, and a record with ID = 1 would be deleted from the EMPLOYEE table and the rest of the records would be read."
},
{
"code": null,
"e": 26977,
"s": 26845,
"text": "Going to delete record.....\nRecord deleted Successfully\nGoing to read records.....\n 2 Roma Ali 3000\nRecords Read Successfully\n"
},
{
"code": null,
"e": 27192,
"s": 26977,
"text": "The resultMap element is the most important and powerful element in iBATIS. You can reduce up to 90% JDBC coding using iBATIS ResultMap and in some cases, it allows you to do things that JDBC does not even support."
},
{
"code": null,
"e": 27399,
"s": 27192,
"text": "The design of ResultMaps is such that simple statements don't require explicit result mappings at all, and more complex statements require no more than is absolutely necessary to describe the relationships."
},
{
"code": null,
"e": 27470,
"s": 27399,
"text": "This chapter provides just a simple introduction of iBATIS ResultMaps."
},
{
"code": null,
"e": 27518,
"s": 27470,
"text": "We have the following EMPLOYEE table in MySQL −"
},
{
"code": null,
"e": 27714,
"s": 27518,
"text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 27754,
"s": 27714,
"text": "This table has two records as follows −"
},
{
"code": null,
"e": 28056,
"s": 27754,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n| 2 | Roma | Ali | 3000 |\n+----+------------+-----------+--------+\n2 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 28177,
"s": 28056,
"text": "To use iBATIS ResultMap, you do not need to modify the Employee.java file. Let us keep it as it was in the last chapter."
},
{
"code": null,
"e": 29146,
"s": 28177,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n\n /* Here are the required method definitions */\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getFirstName() {\n return first_name;\n }\n\t\n public void setFirstName(String fname) {\n this.first_name = fname;\n }\n\t\n public String getLastName() {\n return last_name;\n }\n\t\n public void setlastName(String lname) {\n this.last_name = lname;\n }\n\t\n public int getSalary() {\n return salary;\n }\n\t\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n} /* End of Employee */"
},
{
"code": null,
"e": 29331,
"s": 29146,
"text": "Here we would modify Employee.xml to introduce <resultMap></resultMap> tag. This tag would have an id which is required to run this resultMap in our <select> tag's resultMap attribute."
},
{
"code": null,
"e": 30716,
"s": 29331,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n\n <!-- Perform Insert Operation -->\n\t\n <insert id=\"insert\" parameterClass=\"Employee\">\n INSERT INTO EMPLOYEE(first_name, last_name, salary)\n values (#first_name#, #last_name#, #salary#)\n\n <selectKey resultClass=\"int\" keyProperty=\"id\">\n select last_insert_id() as id\n </selectKey>\n </insert>\n\n <!-- Perform Read Operation -->\n <select id=\"getAll\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n </select>\n\n <!-- Perform Update Operation -->\n <update id=\"update\" parameterClass=\"Employee\">\n UPDATE EMPLOYEE\n SET first_name = #first_name#\n WHERE id = #id#\n </update>\n\n <!-- Perform Delete Operation -->\n <delete id=\"delete\" parameterClass=\"int\">\n DELETE FROM EMPLOYEE\n WHERE id = #id#\n </delete>\n\n <!-- Using ResultMap -->\n <resultMap id=\"result\" class=\"Employee\">\n <result property=\"id\" column=\"id\"/>\n <result property=\"first_name\" column=\"first_name\"/>\n <result property=\"last_name\" column=\"last_name\"/>\n <result property=\"salary\" column=\"salary\"/>\n </resultMap> \n\t\n <select id=\"useResultMap\" resultMap=\"result\">\n SELECT * FROM EMPLOYEE\n WHERE id=#id#\n </select>\n\n</sqlMap>"
},
{
"code": null,
"e": 30812,
"s": 30716,
"text": "This file has application level logic to read records from the Employee table using ResultMap −"
},
{
"code": null,
"e": 31713,
"s": 30812,
"text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisResultMap{\n public static void main(String[] args)\n throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n int id = 1;\n System.out.println(\"Going to read record.....\");\n Employee e = (Employee)smc.queryForObject (\"Employee.useResultMap\", id);\n\n System.out.println(\"ID: \" + e.getId());\n System.out.println(\"First Name: \" + e.getFirstName());\n System.out.println(\"Last Name: \" + e.getLastName());\n System.out.println(\"Salary: \" + e.getSalary());\n System.out.println(\"Record read Successfully \");\n }\n} "
},
{
"code": null,
"e": 31886,
"s": 31713,
"text": "Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 31922,
"s": 31886,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 31974,
"s": 31922,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 32033,
"s": 31974,
"text": "Create IbatisResultMap.java as shown above and compile it."
},
{
"code": null,
"e": 32084,
"s": 32033,
"text": "Execute IbatisResultMap binary to run the program."
},
{
"code": null,
"e": 32168,
"s": 32084,
"text": "You would get the following result which is a read operation on the EMPLOYEE table."
},
{
"code": null,
"e": 32275,
"s": 32168,
"text": "Going to read record.....\nID: 1\nFirst Name: Zara\nLast Name: Ali\nSalary: 5000\nRecord read Successfully\n"
},
{
"code": null,
"e": 32410,
"s": 32275,
"text": "You can call a stored procedure using iBATIS configuration. First of all, let us understand how to create a stored procedure in MySQL."
},
{
"code": null,
"e": 32458,
"s": 32410,
"text": "We have the following EMPLOYEE table in MySQL −"
},
{
"code": null,
"e": 32654,
"s": 32458,
"text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 32719,
"s": 32654,
"text": "Let us create the following stored procedure in MySQL database −"
},
{
"code": null,
"e": 32926,
"s": 32719,
"text": "DELIMITER $$\n\n DROP PROCEDURE IF EXISTS `testdb`.`getEmp` $$\n CREATE PROCEDURE `testdb`.`getEmp` \n (IN empid INT)\n\t\n BEGIN\n SELECT * FROM EMPLOYEE\n WHERE ID = empid;\n END $$\n\nDELIMITER;\n"
},
{
"code": null,
"e": 32989,
"s": 32926,
"text": "Let’s consider the EMPLOYEE table has two records as follows −"
},
{
"code": null,
"e": 33291,
"s": 32989,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n| 2 | Roma | Ali | 3000 |\n+----+------------+-----------+--------+\n2 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 33412,
"s": 33291,
"text": "To use stored procedure, you do not need to modify the Employee.java file. Let us keep it as it was in the last chapter."
},
{
"code": null,
"e": 34381,
"s": 33412,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n\n /* Here are the required method definitions */\n public int getId() {\n return id;\n }\n\t\n public void setId(int id) {\n this.id = id;\n }\n\t\n public String getFirstName() {\n return first_name;\n }\n\t\n public void setFirstName(String fname) {\n this.first_name = fname;\n }\n\t\n public String getLastName() {\n return last_name;\n }\n\t\n public void setlastName(String lname) {\n this.last_name = lname;\n }\n\t\n public int getSalary() {\n return salary;\n }\n\t\n public void setSalary(int salary) {\n this.salary = salary;\n }\n\n} /* End of Employee */"
},
{
"code": null,
"e": 34610,
"s": 34381,
"text": "Here we would modify Employee.xml to introduce <procedure></procedure> and <parameterMap></parameterMap> tags. Here <procedure></procedure> tag would have an id which we would use in our application to call the stored procedure."
},
{
"code": null,
"e": 35919,
"s": 34610,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n\n <!-- Perform Insert Operation -->\n <insert id=\"insert\" parameterClass=\"Employee\">\n INSERT INTO EMPLOYEE(first_name, last_name, salary)\n values (#first_name#, #last_name#, #salary#)\n\n <selectKey resultClass=\"int\" keyProperty=\"id\">\n select last_insert_id() as id\n </selectKey>\n </insert>\n\n <!-- Perform Read Operation -->\n <select id=\"getAll\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n </select>\n\n <!-- Perform Update Operation -->\n <update id=\"update\" parameterClass=\"Employee\">\n UPDATE EMPLOYEE\n SET first_name = #first_name#\n WHERE id = #id#\n </update>\n\n <!-- Perform Delete Operation -->\n <delete id=\"delete\" parameterClass=\"int\">\n DELETE FROM EMPLOYEE\n WHERE id = #id#\n </delete>\n\n <!-- To call stored procedure. -->\n <procedure id=\"getEmpInfo\" resultClass=\"Employee\" parameterMap=\"getEmpInfoCall\">\n { call getEmp( #acctID# ) } \n </procedure>\n\t\n <parameterMap id=\"getEmpInfoCall\" class=\"map\">\n <parameter property=\"acctID\" jdbcType=\"INT\" javaType=\"java.lang.Integer\" mode=\"IN\"/>\n </parameterMap>\n\n</sqlMap>"
},
{
"code": null,
"e": 36034,
"s": 35919,
"text": "This file has application level logic to read the names of the employees from the Employee table using ResultMap −"
},
{
"code": null,
"e": 36772,
"s": 36034,
"text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisSP{\n public static void main(String[] args)\n throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n int id = 1;\n System.out.println(\"Going to read employee name.....\");\n Employee e = (Employee) smc.queryForObject (\"Employee.getEmpInfo\", id);\n\n System.out.println(\"First Name: \" + e.getFirstName());\n System.out.println(\"Record name Successfully \");\n }\n} "
},
{
"code": null,
"e": 36945,
"s": 36772,
"text": "Here are the steps to compile and run the above-mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 36981,
"s": 36945,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 37033,
"s": 36981,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 37085,
"s": 37033,
"text": "Create IbatisSP.java as shown above and compile it."
},
{
"code": null,
"e": 37129,
"s": 37085,
"text": "Execute IbatisSP binary to run the program."
},
{
"code": null,
"e": 37165,
"s": 37129,
"text": "You would get the following result:"
},
{
"code": null,
"e": 37242,
"s": 37165,
"text": "Going to read employee name.....\nFirst Name: Zara\nRecord name Successfully\n"
},
{
"code": null,
"e": 37547,
"s": 37242,
"text": "Dynamic SQL is a very powerful feature of iBATIS. Sometimes you have to change the WHERE clause criterion based on your parameter object's state. In such situations, iBATIS provides a set of dynamic SQL tags that can be used within mapped statements to enhance the reusability and flexibility of the SQL."
},
{
"code": null,
"e": 37685,
"s": 37547,
"text": "All the logic is put in .XML file using some additional tags. Following is an example where the SELECT statement would work in two ways −"
},
{
"code": null,
"e": 37767,
"s": 37685,
"text": "If you pass an ID, then it would return all the records corresponding to that ID."
},
{
"code": null,
"e": 37844,
"s": 37767,
"text": "Otherwise, it would return all the records where employee ID is set to NULL."
},
{
"code": null,
"e": 38343,
"s": 37844,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n\n <select id=\"findByID\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n\t\t\n <dynamic prepend=\"WHERE \">\n <isNull property=\"id\">\n id IS NULL\n </isNull>\n\t\t\t\n <isNotNull property=\"id\">\n id = #id#\n </isNotNull>\n </dynamic>\n\t\t\n </select>\n</sqlMap>"
},
{
"code": null,
"e": 38482,
"s": 38343,
"text": "You can check a condition using the <isNotEmpty> tag as follows. Here a condition would be added only when a passed property is not empty."
},
{
"code": null,
"e": 38722,
"s": 38482,
"text": "..................\n<select id=\"findByID\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n\t\n <dynamic prepend=\"WHERE \">\n <isNotEmpty property=\"id\">\n id = #id#\n </isNotEmpty>\n </dynamic>\n\t\n</select>\n.................."
},
{
"code": null,
"e": 38850,
"s": 38722,
"text": "If you want a query where we can select an id and/or the first name of an Employee, your SELECT statement would be as follows −"
},
{
"code": null,
"e": 39214,
"s": 38850,
"text": "..................\n<select id=\"findByID\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n\t\n <dynamic prepend=\"WHERE \">\n <isNotEmpty prepend=\"AND\" property=\"id\">\n id = #id#\n </isNotEmpty>\n\t\t\n <isNotEmpty prepend=\"OR\" property=\"first_name\">\n first_name = #first_name#\n </isNotEmpty>\n </dynamic>\n</select>\n.................."
},
{
"code": null,
"e": 39355,
"s": 39214,
"text": "The following example shows how you can write a SELECT statement with dynamic SQL. Consider, we have the following EMPLOYEE table in MySQL −"
},
{
"code": null,
"e": 39551,
"s": 39355,
"text": "CREATE TABLE EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);\n"
},
{
"code": null,
"e": 39608,
"s": 39551,
"text": "Let’s assume this table has only one record as follows −"
},
{
"code": null,
"e": 39869,
"s": 39608,
"text": "mysql> select * from EMPLOYEE;\n+----+------------+-----------+--------+\n| id | first_name | last_name | salary |\n+----+------------+-----------+--------+\n| 1 | Zara | Ali | 5000 |\n+----+------------+-----------+--------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 39956,
"s": 39869,
"text": "To perform read operation, let us have an Employee class in Employee.java as follows −"
},
{
"code": null,
"e": 40623,
"s": 39956,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n /* Define constructors for the Employee class. */\n public Employee() {}\n \n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n\n /* Here are the method definitions */\n public int getId() {\n return id;\n }\n\t\n public String getFirstName() {\n return first_name;\n }\n\t\n public String getLastName() {\n return last_name;\n }\n\t\n public int getSalary() {\n return salary;\n }\n\t\n} /* End of Employee */"
},
{
"code": null,
"e": 40882,
"s": 40623,
"text": "To define SQL mapping statement using iBATIS, we would add the following modified <select> tag in Employee.xml and inside this tag definition, we would define an \"id\" which will be used in IbatisReadDy.java for executing Dynamic SQL SELECT query on database."
},
{
"code": null,
"e": 41301,
"s": 40882,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n\n<sqlMap namespace=\"Employee\">\n <select id=\"findByID\" resultClass=\"Employee\">\n SELECT * FROM EMPLOYEE\n\t\n <dynamic prepend=\"WHERE \">\n <isNotNull property=\"id\">\n id = #id#\n </isNotNull>\n </dynamic>\n\t\t\n </select>\n</sqlMap>"
},
{
"code": null,
"e": 41353,
"s": 41301,
"text": "The above SELECT statement would work in two ways −"
},
{
"code": null,
"e": 41460,
"s": 41353,
"text": "If you pass an ID, then it returns records corresponding to that ID Otherwise, it returns all the records."
},
{
"code": null,
"e": 41567,
"s": 41460,
"text": "If you pass an ID, then it returns records corresponding to that ID Otherwise, it returns all the records."
},
{
"code": null,
"e": 41659,
"s": 41567,
"text": "This file has application level logic to read conditional records from the Employee table −"
},
{
"code": null,
"e": 42775,
"s": 41659,
"text": "import com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisReadDy{\n public static void main(String[] args)\n throws IOException,SQLException{\n Reader rd=Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc=SqlMapClientBuilder.buildSqlMapClient(rd);\n\n /* This would read all records from the Employee table.*/\n System.out.println(\"Going to read records.....\");\n Employee rec = new Employee();\n rec.setId(1);\n\n List <Employee> ems = (List<Employee>) \n smc.queryForList(\"Employee.findByID\", rec);\n Employee em = null;\n\t\t\n for (Employee e : ems) {\n System.out.print(\" \" + e.getId());\n System.out.print(\" \" + e.getFirstName());\n System.out.print(\" \" + e.getLastName());\n System.out.print(\" \" + e.getSalary());\n em = e; \n System.out.println(\"\");\n } \n System.out.println(\"Records Read Successfully \");\n }\n} "
},
{
"code": null,
"e": 42948,
"s": 42775,
"text": "Here are the steps to compile and run the above mentioned software. Make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 42984,
"s": 42948,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 43036,
"s": 42984,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 43092,
"s": 43036,
"text": "Create IbatisReadDy.java as shown above and compile it."
},
{
"code": null,
"e": 43140,
"s": 43092,
"text": "Execute IbatisReadDy binary to run the program."
},
{
"code": null,
"e": 43228,
"s": 43140,
"text": "You would get the following result, and a record would be read from the EMPLOYEE table."
},
{
"code": null,
"e": 43304,
"s": 43228,
"text": "Going to read records.....\n 1 Zara Ali 5000\nRecord Reads Successfully\n"
},
{
"code": null,
"e": 43390,
"s": 43304,
"text": "Try the above example by passing null as smc.queryForList(\"Employee.findByID\", null)."
},
{
"code": null,
"e": 43479,
"s": 43390,
"text": "iBATIS provides powerful OGNL based expressions to eliminate most of the other elements."
},
{
"code": null,
"e": 43492,
"s": 43479,
"text": "if Statement"
},
{
"code": null,
"e": 43526,
"s": 43492,
"text": "choose, when, otherwise Statement"
},
{
"code": null,
"e": 43542,
"s": 43526,
"text": "where Statement"
},
{
"code": null,
"e": 43560,
"s": 43542,
"text": "foreach Statement"
},
{
"code": null,
"e": 43668,
"s": 43560,
"text": "The most common thing to do in dynamic SQL is conditionally include a part of a where clause. For example −"
},
{
"code": null,
"e": 43879,
"s": 43668,
"text": "<select id=\"findActiveBlogWithTitleLike\" parameterType=\"Blog\" resultType=\"Blog\">\n SELECT * FROM BLOG\n WHERE state = 'ACTIVE.\n\t\n <if test=\"title != null\">\n AND title like #{title}\n </if>\n\t\n</select>"
},
{
"code": null,
"e": 44098,
"s": 43879,
"text": "This statement provides an optional text search type of functionality. If you pass in no title, then all active Blogs are returned. But if you do pass in a title, it will look for a title with the given like condition."
},
{
"code": null,
"e": 44150,
"s": 44098,
"text": "You can include multiple if conditions as follows −"
},
{
"code": null,
"e": 44434,
"s": 44150,
"text": "<select id=\"findActiveBlogWithTitleLike\" parameterType=\"Blog\" resultType=\"Blog\">\n SELECT * FROM BLOG\n WHERE state = 'ACTIVE.\n\t\n <if test=\"title != null\">\n AND title like #{title}\n </if>\n\t\n <if test=\"author != null\">\n AND author like #{author}\n </if>\n\t\n</select>"
},
{
"code": null,
"e": 44560,
"s": 44434,
"text": "iBATIS offers a choose element which is similar to Java's switch statement. It helps choose only one case among many options."
},
{
"code": null,
"e": 44726,
"s": 44560,
"text": "The following example would search only by title if one is provided, then only by author if one is provided. If neither is provided, it returns only featured blogs −"
},
{
"code": null,
"e": 45152,
"s": 44726,
"text": "<select id=\"findActiveBlogWithTitleLike\" parameterType=\"Blog\" resultType=\"Blog\">\n SELECT * FROM BLOG\n WHERE state = 'ACTIVE.\n\t\n <choose>\n <when test=\"title != null\">\n AND title like #{title}\n </when>\n\t\t\n <when test=\"author != null and author.name != null\">\n AND author like #{author}\n </when>\n\t\t\n <otherwise>\n AND featured = 1\n </otherwise>\n </choose>\n\t\n</select>"
},
{
"code": null,
"e": 45296,
"s": 45152,
"text": "Take a look at our previous examples to see what happens if none of the conditions are met. You would end up with an SQL that looks like this −"
},
{
"code": null,
"e": 45322,
"s": 45296,
"text": "SELECT * FROM BLOG\nWHERE\n"
},
{
"code": null,
"e": 45420,
"s": 45322,
"text": "This would fail, but iBATIS has a simple solution with one simple change, everything works fine −"
},
{
"code": null,
"e": 45783,
"s": 45420,
"text": "<select id=\"findActiveBlogLike\" parameterType=\"Blog\" resultType=\"Blog\">\n SELECT * FROM BLOG\n\t\n <where>\n <if test=\"state != null\">\n state = #{state}\n </if>\n\t\t\n <if test=\"title != null\">\n AND title like #{title}\n </if>\n\t\t\n <if test=\"author != null>\n AND author like #{author}\n </if>\n </where>\n\t\n</select>"
},
{
"code": null,
"e": 45945,
"s": 45783,
"text": "The where element inserts a WHERE only when the containing tags return any content. Furthermore, if that content begins with AND or OR, it knows to strip it off."
},
{
"code": null,
"e": 46086,
"s": 45945,
"text": "The foreach element allows you to specify a collection and declare item and index variables that can be used inside the body of the element."
},
{
"code": null,
"e": 46240,
"s": 46086,
"text": "It also allows you to specify opening and closing strings, and add a separator to place in between iterations. You can build an IN condition as follows −"
},
{
"code": null,
"e": 46477,
"s": 46240,
"text": "<select id=\"selectPostIn\" resultType=\"domain.blog.Post\">\n SELECT *\n FROM POST P\n WHERE ID in\n\t\n <foreach item=\"item\" index=\"index\" collection=\"list\"\n open=\"(\" separator=\",\" close=\")\">\n #{item}\n </foreach>\n\t\n</select>"
},
{
"code": null,
"e": 46660,
"s": 46477,
"text": "It is easy to debug your program while working with iBATIS. iBATIS has built-in logging support and it works with the following logging libraries and searches for them in this order."
},
{
"code": null,
"e": 46691,
"s": 46660,
"text": "Jakarta Commons Logging (JCL)."
},
{
"code": null,
"e": 46697,
"s": 46691,
"text": "Log4J"
},
{
"code": null,
"e": 46709,
"s": 46697,
"text": "JDK logging"
},
{
"code": null,
"e": 46774,
"s": 46709,
"text": "You can use any of the above listed libraries along with iBATIS."
},
{
"code": null,
"e": 46889,
"s": 46774,
"text": "Assuming you are going to use Log4J for logging. Before proceeding, you need to cross-check the following points −"
},
{
"code": null,
"e": 46958,
"s": 46889,
"text": "The Log4J JAR file (log4j-{version}.jar) should be in the CLASSPATH."
},
{
"code": null,
"e": 47012,
"s": 46958,
"text": "You have log4j.properties available in the CLASSPATH."
},
{
"code": null,
"e": 47168,
"s": 47012,
"text": "Following is the log4j.properties file. Note that some of the lines are commented out. You can uncomment them if you need additional debugging information."
},
{
"code": null,
"e": 47755,
"s": 47168,
"text": "# Global logging configuration\nlog4j.rootLogger = ERROR, stdout\n\nlog4j.logger.com.ibatis = DEBUG\n\n# shows SQL of prepared statements\n#log4j.logger.java.sql.Connection = DEBUG\n\n# shows parameters inserted into prepared statements\n#log4j.logger.java.sql.PreparedStatement = DEBUG\n\n# shows query results\n#log4j.logger.java.sql.ResultSet = DEBUG\n\n#log4j.logger.java.sql.Statement = DEBUG\n\n# Console output\nlog4j.appender.stdout = org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.layout = org.apache.log4j.PatternLayout\nlog4j.appender.stdout.layout.ConversionPattern = %5p [%t] − %m%n\n"
},
{
"code": null,
"e": 47846,
"s": 47755,
"text": "You can find the complete documentation for Log4J from Apaches site − Log4J Documentation."
},
{
"code": null,
"e": 48048,
"s": 47846,
"text": "The following Java class is a very simple example that initializes and then uses the Log4J logging library for Java applications. We would use the above-mentioned property file which lies in CLASSPATH."
},
{
"code": null,
"e": 49414,
"s": 48048,
"text": "import org.apache.log4j.Logger;\n\nimport com.ibatis.common.resources.Resources;\nimport com.ibatis.sqlmap.client.SqlMapClient;\nimport com.ibatis.sqlmap.client.SqlMapClientBuilder;\n\nimport java.io.*;\nimport java.sql.SQLException;\nimport java.util.*;\n\npublic class IbatisUpdate{\n static Logger log = Logger.getLogger(IbatisUpdate.class.getName());\n\n public static void main(String[] args)\n throws IOException,SQLException{\n Reader rd = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);\n\n /* This would insert one record in Employee table. */\n log.info(\"Going to update record.....\");\n Employee rec = new Employee();\n rec.setId(1);\n rec.setFirstName( \"Roma\");\n smc.update(\"Employee.update\", rec );\n log.info(\"Record updated Successfully \");\n\n log.debug(\"Going to read records.....\");\n List <Employee> ems = (List<Employee>) \n smc.queryForList(\"Employee.getAll\", null);\n Employee em = null;\n\t\t\n for (Employee e : ems) {\n System.out.print(\" \" + e.getId());\n System.out.print(\" \" + e.getFirstName());\n System.out.print(\" \" + e.getLastName());\n System.out.print(\" \" + e.getSalary());\n em = e;\n System.out.println(\"\");\n }\n log.debug(\"Records Read Successfully \");\n }\n}"
},
{
"code": null,
"e": 49533,
"s": 49414,
"text": "First of all, make sure you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 49569,
"s": 49533,
"text": "Create Employee.xml as shown above."
},
{
"code": null,
"e": 49621,
"s": 49569,
"text": "Create Employee.java as shown above and compile it."
},
{
"code": null,
"e": 49677,
"s": 49621,
"text": "Create IbatisUpdate.java as shown above and compile it."
},
{
"code": null,
"e": 49717,
"s": 49677,
"text": "Create log4j.properties as shown above."
},
{
"code": null,
"e": 49765,
"s": 49717,
"text": "Execute IbatisUpdate binary to run the program."
},
{
"code": null,
"e": 49915,
"s": 49765,
"text": "You would get the following result. A record would be updated in the EMPLOYEE table and later, the same record would be read from the EMPLOYEE table."
},
{
"code": null,
"e": 50190,
"s": 49915,
"text": "DEBUG [main] - Created connection 28405330.\nDEBUG [main] - Returned connection 28405330 to pool.\nDEBUG [main] - Checked out connection 28405330 from pool.\nDEBUG [main] - Returned connection 28405330 to pool.\n 1 Roma Ali 5000\n 2 Zara Ali 5000\n 3 Zara Ali 5000\n"
},
{
"code": null,
"e": 50316,
"s": 50190,
"text": "In the above example, we used only info() method, however you can use any of the following methods as per your requirements −"
},
{
"code": null,
"e": 50524,
"s": 50316,
"text": "public void trace(Object message);\npublic void debug(Object message);\npublic void info(Object message);\npublic void warn(Object message);\npublic void error(Object message);\npublic void fatal(Object message);"
},
{
"code": null,
"e": 50671,
"s": 50524,
"text": "There are major differences between iBATIS and Hibernate. Both the solutions work well, given their specific domain. iBATIS is suggested in case −"
},
{
"code": null,
"e": 50743,
"s": 50671,
"text": "You want to create your own SQL's and you are willing to maintain them."
},
{
"code": null,
"e": 50796,
"s": 50743,
"text": "Your environment is driven by relational data model."
},
{
"code": null,
"e": 50846,
"s": 50796,
"text": "You have to work on existing and complex schemas."
},
{
"code": null,
"e": 50946,
"s": 50846,
"text": "Use Hibernate if the environment is driven by object model and needs to generate SQL automatically."
},
{
"code": null,
"e": 51123,
"s": 50946,
"text": "Both Hibernate and iBATIS are open source Object Relational Mapping (ORM) tools available in the industry. Use of each of these tools depends on the context you are using them."
},
{
"code": null,
"e": 51201,
"s": 51123,
"text": "The following table highlights the differences between iBATIS and Hibernate −"
},
{
"code": null,
"e": 51328,
"s": 51201,
"text": "Both Hibernate and iBATIS receive good support from the SPRING framework, so it should not be a problem to choose one of them."
},
{
"code": null,
"e": 51484,
"s": 51328,
"text": "iBATOR is a code generator for iBATIS. iBATOR introspects one or more database tables and generates iBATIS artifacts that can be used to access the tables."
},
{
"code": null,
"e": 51615,
"s": 51484,
"text": "Later you can write your custom SQL code or stored procedure to meet your requirements. iBATOR generates the following artifacts −"
},
{
"code": null,
"e": 51632,
"s": 51615,
"text": "SqlMap XML Files"
},
{
"code": null,
"e": 51697,
"s": 51632,
"text": "Java Classes to match the primary key and fields of the table(s)"
},
{
"code": null,
"e": 51747,
"s": 51697,
"text": "DAO Classes that use the above objects (optional)"
},
{
"code": null,
"e": 51933,
"s": 51747,
"text": "iBATOR can run as a standalone JAR file, or as an Ant task, or as an Eclipse plugin. This tutorial describes the simplest way of generating iBATIS configuration files from command line."
},
{
"code": null,
"e": 52118,
"s": 51933,
"text": "Download the standalone JAR if you are using an IDE other than Eclipse. The standalone JAR includes an Ant task to run iBATOR, or you can run iBATOR from the command line of Java code."
},
{
"code": null,
"e": 52166,
"s": 52118,
"text": "You can download zip file from Download iBATOR."
},
{
"code": null,
"e": 52214,
"s": 52166,
"text": "You can download zip file from Download iBATOR."
},
{
"code": null,
"e": 52273,
"s": 52214,
"text": "You can check online documentation − iBATOR Documentation."
},
{
"code": null,
"e": 52332,
"s": 52273,
"text": "You can check online documentation − iBATOR Documentation."
},
{
"code": null,
"e": 52368,
"s": 52332,
"text": "To run iBATOR, follow these steps −"
},
{
"code": null,
"e": 52470,
"s": 52368,
"text": "Create and fill a configuration file ibatorConfig.xml appropriately. At a minimum, you must specify −"
},
{
"code": null,
"e": 52547,
"s": 52470,
"text": "A <jdbcConnection> element to specify how to connect to the target database."
},
{
"code": null,
"e": 52624,
"s": 52547,
"text": "A <jdbcConnection> element to specify how to connect to the target database."
},
{
"code": null,
"e": 52746,
"s": 52624,
"text": "A <javaModelGenerator> element to specify the target package and the target project for the generated Java model objects."
},
{
"code": null,
"e": 52868,
"s": 52746,
"text": "A <javaModelGenerator> element to specify the target package and the target project for the generated Java model objects."
},
{
"code": null,
"e": 52982,
"s": 52868,
"text": "A <sqlMapGenerator> element to specify the target package and the target project for the generated SQL map files."
},
{
"code": null,
"e": 53096,
"s": 52982,
"text": "A <sqlMapGenerator> element to specify the target package and the target project for the generated SQL map files."
},
{
"code": null,
"e": 53297,
"s": 53096,
"text": "A <daoGenerator> element to specify the target package and the target project for the generated DAO interfaces and classes (you may omit the <daoGenerator> element if you don't wish to generate DAOs)."
},
{
"code": null,
"e": 53498,
"s": 53297,
"text": "A <daoGenerator> element to specify the target package and the target project for the generated DAO interfaces and classes (you may omit the <daoGenerator> element if you don't wish to generate DAOs)."
},
{
"code": null,
"e": 53536,
"s": 53498,
"text": "At least one database <table> element"
},
{
"code": null,
"e": 53574,
"s": 53536,
"text": "At least one database <table> element"
},
{
"code": null,
"e": 53676,
"s": 53574,
"text": "NOTE − See the XML Configuration File Reference page for an example of an iBATOR configuration file."
},
{
"code": null,
"e": 53757,
"s": 53676,
"text": "Save the file in a convenient location, for example, at: \\temp\\ibatorConfig.xml."
},
{
"code": null,
"e": 53807,
"s": 53757,
"text": "Now run iBATOR from the command line as follows −"
},
{
"code": null,
"e": 53875,
"s": 53807,
"text": "java -jar abator.jar -configfile \\temp\\abatorConfig.xml -overwrite\n"
},
{
"code": null,
"e": 54096,
"s": 53875,
"text": "It will tell iBATOR to run using your configuration file. It will also tell iBATOR to overwrite any existing Java files with the same name. If you want to save any existing Java files, then omit the −overwrite parameter."
},
{
"code": null,
"e": 54178,
"s": 54096,
"text": "If there is a conflict, iBATOR saves the newly generated file with a unique name."
},
{
"code": null,
"e": 54350,
"s": 54178,
"text": "After running iBATOR, you need to create or modify the standard iBATIS configuration files to make use of your newly generated code. This is explained in the next section."
},
{
"code": null,
"e": 54471,
"s": 54350,
"text": "After you run iBATOR, you need to create or modify other iBATIS configuration artifacts. The main tasks are as follows −"
},
{
"code": null,
"e": 54515,
"s": 54471,
"text": "Create or modify the SqlMapConfig.xml file."
},
{
"code": null,
"e": 54599,
"s": 54515,
"text": "Create or modify the dao.xml file (only if you are using the iBATIS DAO Framework)."
},
{
"code": null,
"e": 54640,
"s": 54599,
"text": "Each task is described in detail below −"
},
{
"code": null,
"e": 54839,
"s": 54640,
"text": "iBATIS uses an XML file, commonly named SqlMapConfig.xml, to specify information for a database connection, a transaction management scheme, and SQL map XML files that are used in an iBATIS session."
},
{
"code": null,
"e": 55020,
"s": 54839,
"text": "iBATOR cannot create this file for you because it knows nothing about your execution environment. However, some of the items in this file relate directly to iBATOR generated items."
},
{
"code": null,
"e": 55085,
"s": 55020,
"text": "iBATOR specific needs in the configuration file are as follows −"
},
{
"code": null,
"e": 55123,
"s": 55085,
"text": "Statement namespaces must be enabled."
},
{
"code": null,
"e": 55174,
"s": 55123,
"text": "iBATOR generated SQL Map XML files must be listed."
},
{
"code": null,
"e": 55392,
"s": 55174,
"text": "For example, suppose iBATOR has generated an SQL Map XML file called MyTable_SqlMap.xml, and that the file has been placed in the test.xml package of your project. The SqlMapConfig.xml file should have these entries −"
},
{
"code": null,
"e": 56026,
"s": 55392,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMapConfig PUBLIC \"-//ibatis.apache.org//DTD SQL Map Config 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-config-2.dtd\">\n\n<sqlMapConfig>\n <!-- Statement namespaces are required for Abator -->\n <settings useStatementNamespaces=\"true\" />\n\n <!-- Setup the transaction manager and data source that are\n appropriate for your environment\n -->\n\t\n <transactionManager type=\"...\">\n <dataSource type=\"...\">\n </dataSource>\n </transactionManager>\n\n <!-- SQL Map XML files should be listed here -->\n <sqlMap resource=\"test/xml/MyTable_SqlMap.xml\" />\n\n</sqlMapConfig>"
},
{
"code": null,
"e": 56205,
"s": 56026,
"text": "If there is more than one SQL Map XML file (as is quite common), then the files can be listed in any order with repeated <sqlMap> elements after the <transactionManager> element."
},
{
"code": null,
"e": 56284,
"s": 56205,
"text": "The iBATIS DAO framework is configured by an xml file commonly called dao.xml."
},
{
"code": null,
"e": 56449,
"s": 56284,
"text": "The iBATIS DAO framework uses this file to control the database connection information for DAOs, and also to list the DAO implementation classes and DAO interfaces."
},
{
"code": null,
"e": 56594,
"s": 56449,
"text": "In this file, you should specify the path to your SqlMapConfig.xml file, and all the iBATOR generated DAO interfaces and implementation classes."
},
{
"code": null,
"e": 56798,
"s": 56594,
"text": "For example, suppose iBATOR has generated a DAO interface called MyTableDAO and an implementation class called MyTableDAOImpl, and that the files have been placed in the test.dao package of your project."
},
{
"code": null,
"e": 56843,
"s": 56798,
"text": "The dao.xml file should have these entries −"
},
{
"code": null,
"e": 57371,
"s": 56843,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE daoConfig PUBLIC \"-//ibatis.apache.org//DTD DAO Configuration 2.0//EN\" \"http://ibatis.apache.org/dtd/dao-2.dtd\">\n\n<daoConfig>\n\n <context>\n\t\n <transactionManager type=\"SQLMAP\">\n <property name=\"SqlMapConfigResource\" value=\"test/SqlMapConfig.xml\"/>\n </transactionManager>\n\n <!-- DAO interfaces and implementations should be listed here -->\n <dao interface=\"test.dao.MyTableDAO\" implementation=\"test.dao.MyTableDAOImpl\" />\n </context>\n\t\n</daoConfig>"
},
{
"code": null,
"e": 57457,
"s": 57371,
"text": "NOTE − This step is required only if you generated DAOs for the iBATIS DAO framework."
},
{
"code": null,
"e": 57464,
"s": 57457,
"text": " Print"
},
{
"code": null,
"e": 57475,
"s": 57464,
"text": " Add Notes"
}
] |
Python Pandas - Descriptive Statistics | A large number of methods collectively compute descriptive statistics and other related operations on DataFrame. Most of these are aggregations like sum(), mean(), but some of them, like sumsum(), produce an object of the same size. Generally speaking, these methods take an axis argument, just like ndarray.{sum, std, ...}, but the axis can be specified by name or integer
DataFrame − “index” (axis=0, default), “columns” (axis=1)
DataFrame − “index” (axis=0, default), “columns” (axis=1)
Let us create a DataFrame and use this object throughout this chapter for all the operations.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df
Its output is as follows −
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
7 34 Lee 3.78
8 40 David 2.98
9 30 Gasper 4.80
10 51 Betina 4.10
11 46 Andres 3.65
Returns the sum of the values for the requested axis. By default, axis is index (axis=0).
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df.sum()
Its output is as follows −
Age 382
Name TomJamesRickyVinSteveSmithJackLeeDavidGasperBe...
Rating 44.92
dtype: object
Each individual column is added individually (Strings are appended).
This syntax will give the output as shown below.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df.sum(1)
Its output is as follows −
0 29.23
1 29.24
2 28.98
3 25.56
4 33.20
5 33.60
6 26.80
7 37.78
8 42.98
9 34.80
10 55.10
11 49.65
dtype: float64
Returns the average value
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df.mean()
Its output is as follows −
Age 31.833333
Rating 3.743333
dtype: float64
Returns the Bressel standard deviation of the numerical columns.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df.std()
Its output is as follows −
Age 9.232682
Rating 0.661628
dtype: float64
Let us now understand the functions under Descriptive Statistics in Python Pandas. The following table list down the important functions −
Note − Since DataFrame is a Heterogeneous data structure. Generic operations don’t work with all functions.
Functions like sum(), cumsum() work with both numeric and character (or) string data elements without any error. Though n practice, character aggregations are never used generally, these functions do not throw any exception.
Functions like sum(), cumsum() work with both numeric and character (or) string data elements without any error. Though n practice, character aggregations are never used generally, these functions do not throw any exception.
Functions like abs(), cumprod() throw exception when the DataFrame contains character or string data because such operations cannot be performed.
Functions like abs(), cumprod() throw exception when the DataFrame contains character or string data because such operations cannot be performed.
The describe() function computes a summary of statistics pertaining to the DataFrame columns.
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df.describe()
Its output is as follows −
Age Rating
count 12.000000 12.000000
mean 31.833333 3.743333
std 9.232682 0.661628
min 23.000000 2.560000
25% 25.000000 3.230000
50% 29.500000 3.790000
75% 35.500000 4.132500
max 51.000000 4.800000
This function gives the mean, std and IQR values. And, function excludes the character columns and given summary about numeric columns. 'include' is the argument which is used to pass necessary information regarding what columns need to be considered for summarizing. Takes the list of values; by default, 'number'.
object − Summarizes String columns
number − Summarizes Numeric columns
all − Summarizes all columns together (Should not pass it as a list value)
Now, use the following statement in the program and check the output −
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df.describe(include=['object'])
Its output is as follows −
Name
count 12
unique 12
top Ricky
freq 1
Now, use the following statement and check the output −
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
}
#Create a DataFrame
df = pd.DataFrame(d)
print df. describe(include='all')
Its output is as follows −
Age Name Rating
count 12.000000 12 12.000000
unique NaN 12 NaN
top NaN Ricky NaN
freq NaN 1 NaN
mean 31.833333 NaN 3.743333
std 9.232682 NaN 0.661628
min 23.000000 NaN 2.560000
25% 25.000000 NaN 3.230000
50% 29.500000 NaN 3.790000
75% 35.500000 NaN 4.132500
max 51.000000 NaN 4.800000
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2817,
"s": 2443,
"text": "A large number of methods collectively compute descriptive statistics and other related operations on DataFrame. Most of these are aggregations like sum(), mean(), but some of them, like sumsum(), produce an object of the same size. Generally speaking, these methods take an axis argument, just like ndarray.{sum, std, ...}, but the axis can be specified by name or integer"
},
{
"code": null,
"e": 2875,
"s": 2817,
"text": "DataFrame − “index” (axis=0, default), “columns” (axis=1)"
},
{
"code": null,
"e": 2933,
"s": 2875,
"text": "DataFrame − “index” (axis=0, default), “columns” (axis=1)"
},
{
"code": null,
"e": 3027,
"s": 2933,
"text": "Let us create a DataFrame and use this object throughout this chapter for all the operations."
},
{
"code": null,
"e": 3415,
"s": 3027,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df"
},
{
"code": null,
"e": 3442,
"s": 3415,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3730,
"s": 3442,
"text": " Age Name Rating\n0 25 Tom 4.23\n1 26 James 3.24\n2 25 Ricky 3.98\n3 23 Vin 2.56\n4 30 Steve 3.20\n5 29 Smith 4.60\n6 23 Jack 3.80\n7 34 Lee 3.78\n8 40 David 2.98\n9 30 Gasper 4.80\n10 51 Betina 4.10\n11 46 Andres 3.65\n"
},
{
"code": null,
"e": 3820,
"s": 3730,
"text": "Returns the sum of the values for the requested axis. By default, axis is index (axis=0)."
},
{
"code": null,
"e": 4216,
"s": 3820,
"text": "import pandas as pd\nimport numpy as np\n \n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df.sum()\n"
},
{
"code": null,
"e": 4243,
"s": 4216,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4435,
"s": 4243,
"text": "Age 382\nName TomJamesRickyVinSteveSmithJackLeeDavidGasperBe...\nRating 44.92\ndtype: object\n"
},
{
"code": null,
"e": 4504,
"s": 4435,
"text": "Each individual column is added individually (Strings are appended)."
},
{
"code": null,
"e": 4553,
"s": 4504,
"text": "This syntax will give the output as shown below."
},
{
"code": null,
"e": 4950,
"s": 4553,
"text": "import pandas as pd\nimport numpy as np\n \n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n \n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df.sum(1)"
},
{
"code": null,
"e": 4977,
"s": 4950,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5125,
"s": 4977,
"text": "0 29.23\n1 29.24\n2 28.98\n3 25.56\n4 33.20\n5 33.60\n6 26.80\n7 37.78\n8 42.98\n9 34.80\n10 55.10\n11 49.65\ndtype: float64\n"
},
{
"code": null,
"e": 5151,
"s": 5125,
"text": "Returns the average value"
},
{
"code": null,
"e": 5546,
"s": 5151,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df.mean()"
},
{
"code": null,
"e": 5573,
"s": 5546,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5629,
"s": 5573,
"text": "Age 31.833333\nRating 3.743333\ndtype: float64\n"
},
{
"code": null,
"e": 5694,
"s": 5629,
"text": "Returns the Bressel standard deviation of the numerical columns."
},
{
"code": null,
"e": 6088,
"s": 5694,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df.std()"
},
{
"code": null,
"e": 6115,
"s": 6088,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6169,
"s": 6115,
"text": "Age 9.232682\nRating 0.661628\ndtype: float64\n"
},
{
"code": null,
"e": 6308,
"s": 6169,
"text": "Let us now understand the functions under Descriptive Statistics in Python Pandas. The following table list down the important functions −"
},
{
"code": null,
"e": 6416,
"s": 6308,
"text": "Note − Since DataFrame is a Heterogeneous data structure. Generic operations don’t work with all functions."
},
{
"code": null,
"e": 6641,
"s": 6416,
"text": "Functions like sum(), cumsum() work with both numeric and character (or) string data elements without any error. Though n practice, character aggregations are never used generally, these functions do not throw any exception."
},
{
"code": null,
"e": 6866,
"s": 6641,
"text": "Functions like sum(), cumsum() work with both numeric and character (or) string data elements without any error. Though n practice, character aggregations are never used generally, these functions do not throw any exception."
},
{
"code": null,
"e": 7012,
"s": 6866,
"text": "Functions like abs(), cumprod() throw exception when the DataFrame contains character or string data because such operations cannot be performed."
},
{
"code": null,
"e": 7158,
"s": 7012,
"text": "Functions like abs(), cumprod() throw exception when the DataFrame contains character or string data because such operations cannot be performed."
},
{
"code": null,
"e": 7252,
"s": 7158,
"text": "The describe() function computes a summary of statistics pertaining to the DataFrame columns."
},
{
"code": null,
"e": 7651,
"s": 7252,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df.describe()"
},
{
"code": null,
"e": 7678,
"s": 7651,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7985,
"s": 7678,
"text": " Age Rating\ncount 12.000000 12.000000\nmean 31.833333 3.743333\nstd 9.232682 0.661628\nmin 23.000000 2.560000\n25% 25.000000 3.230000\n50% 29.500000 3.790000\n75% 35.500000 4.132500\nmax 51.000000 4.800000\n"
},
{
"code": null,
"e": 8301,
"s": 7985,
"text": "This function gives the mean, std and IQR values. And, function excludes the character columns and given summary about numeric columns. 'include' is the argument which is used to pass necessary information regarding what columns need to be considered for summarizing. Takes the list of values; by default, 'number'."
},
{
"code": null,
"e": 8336,
"s": 8301,
"text": "object − Summarizes String columns"
},
{
"code": null,
"e": 8372,
"s": 8336,
"text": "number − Summarizes Numeric columns"
},
{
"code": null,
"e": 8447,
"s": 8372,
"text": "all − Summarizes all columns together (Should not pass it as a list value)"
},
{
"code": null,
"e": 8518,
"s": 8447,
"text": "Now, use the following statement in the program and check the output −"
},
{
"code": null,
"e": 8935,
"s": 8518,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df.describe(include=['object'])"
},
{
"code": null,
"e": 8962,
"s": 8935,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 9038,
"s": 8962,
"text": " Name\ncount 12\nunique 12\ntop Ricky\nfreq 1\n"
},
{
"code": null,
"e": 9094,
"s": 9038,
"text": "Now, use the following statement and check the output −"
},
{
"code": null,
"e": 9507,
"s": 9094,
"text": "import pandas as pd\nimport numpy as np\n\n#Create a Dictionary of series\nd = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',\n 'Lee','David','Gasper','Betina','Andres']),\n 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),\n 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])\n}\n\n#Create a DataFrame\ndf = pd.DataFrame(d)\nprint df. describe(include='all')"
},
{
"code": null,
"e": 9534,
"s": 9507,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 10027,
"s": 9534,
"text": " Age Name Rating\ncount 12.000000 12 12.000000\nunique NaN 12 NaN\ntop NaN Ricky NaN\nfreq NaN 1 NaN\nmean 31.833333 NaN 3.743333\nstd 9.232682 NaN 0.661628\nmin 23.000000 NaN 2.560000\n25% 25.000000 NaN 3.230000\n50% 29.500000 NaN 3.790000\n75% 35.500000 NaN 4.132500\nmax 51.000000 NaN 4.800000\n"
},
{
"code": null,
"e": 10064,
"s": 10027,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 10080,
"s": 10064,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 10113,
"s": 10080,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10132,
"s": 10113,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10167,
"s": 10132,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 10189,
"s": 10167,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 10223,
"s": 10189,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 10251,
"s": 10223,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10286,
"s": 10251,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 10300,
"s": 10286,
"text": " Lets Kode It"
},
{
"code": null,
"e": 10333,
"s": 10300,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10350,
"s": 10333,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10357,
"s": 10350,
"text": " Print"
},
{
"code": null,
"e": 10368,
"s": 10357,
"text": " Add Notes"
}
] |
How to Set Border of Tkinter Label Widget? - GeeksforGeeks | 11 Dec, 2020
The task here is to draft a python program using Tkinter module to set borders of a label widget. A Tkinter label Widget is an Area that displays text or images. We can update this text at any point in time.
Import module
Create a window
Set a label widget with required attributes for border
Place this widget on the window created
Syntax: Label ( master, option, ... )
Parameters:
Master: This represents the parent window.
Option: There are so many options for labels like bg, fg, font, bd, etc
Now to set the border of the label we need to add two options to the label property:
borderwidth: It will represent the size of the border around the label. By default, borderwidth is 2 pixels. “bd” can also be used as a shorthand for borderwidth.
relief: It will Specify the look of a decorative border around the label. By default, it is FLAT. Other than Flat there are many more acceptable values like raised, ridge, solid, etc.
Given below is the implementation to set border and edit it as required.
Program 1: To set a border
Python3
# import tkinterfrom tkinter import * # Create Tk objectwindow = Tk() # Set the window titlewindow.title('With_Border') # set the window sizewindow.geometry('300x100') # take one Label widgetlabel = Label(window, text="WELCOME TO GFG", borderwidth=1, relief="solid") # place that label to windowlabel.grid(column=0, row=1, padx=100, pady=10)window.mainloop()
Output:
Program 2: to set the border and edit it as required.
Python3
# import tkinterfrom tkinter import * # Create Tk objectwindow = Tk() # Set the window titlewindow.title('GFG') # take Label widgetsA = Label(window, text="flat", width=10, height=2, borderwidth=3, relief="flat")B = Label(window, text="solid", width=10, height=2, borderwidth=3, relief="solid")C = Label(window, text="raised", width=10, height=2, borderwidth=3, relief="raised")D = Label(window, text="sunken", width=10, height=2, borderwidth=3, relief="sunken")E = Label(window, text="ridge", width=10, height=2, borderwidth=3, relief="ridge")F = Label(window, text="groove", width=10, height=2, borderwidth=3, relief="groove") # place that labels to windowA.grid(column=0, row=1, padx=100, pady=10)B.grid(column=0, row=2, padx=100, pady=10)C.grid(column=0, row=3, padx=100, pady=10)D.grid(column=0, row=4, padx=100, pady=10)E.grid(column=0, row=5, padx=100, pady=10)F.grid(column=0, row=6, padx=100, pady=10) window.mainloop()
Output:
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25927,
"s": 25899,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 26136,
"s": 25927,
"text": "The task here is to draft a python program using Tkinter module to set borders of a label widget. A Tkinter label Widget is an Area that displays text or images. We can update this text at any point in time. "
},
{
"code": null,
"e": 26150,
"s": 26136,
"text": "Import module"
},
{
"code": null,
"e": 26166,
"s": 26150,
"text": "Create a window"
},
{
"code": null,
"e": 26221,
"s": 26166,
"text": "Set a label widget with required attributes for border"
},
{
"code": null,
"e": 26261,
"s": 26221,
"text": "Place this widget on the window created"
},
{
"code": null,
"e": 26299,
"s": 26261,
"text": "Syntax: Label ( master, option, ... )"
},
{
"code": null,
"e": 26311,
"s": 26299,
"text": "Parameters:"
},
{
"code": null,
"e": 26354,
"s": 26311,
"text": "Master: This represents the parent window."
},
{
"code": null,
"e": 26426,
"s": 26354,
"text": "Option: There are so many options for labels like bg, fg, font, bd, etc"
},
{
"code": null,
"e": 26512,
"s": 26426,
"text": "Now to set the border of the label we need to add two options to the label property: "
},
{
"code": null,
"e": 26675,
"s": 26512,
"text": "borderwidth: It will represent the size of the border around the label. By default, borderwidth is 2 pixels. “bd” can also be used as a shorthand for borderwidth."
},
{
"code": null,
"e": 26859,
"s": 26675,
"text": "relief: It will Specify the look of a decorative border around the label. By default, it is FLAT. Other than Flat there are many more acceptable values like raised, ridge, solid, etc."
},
{
"code": null,
"e": 26932,
"s": 26859,
"text": "Given below is the implementation to set border and edit it as required."
},
{
"code": null,
"e": 26960,
"s": 26932,
"text": "Program 1: To set a border "
},
{
"code": null,
"e": 26968,
"s": 26960,
"text": "Python3"
},
{
"code": "# import tkinterfrom tkinter import * # Create Tk objectwindow = Tk() # Set the window titlewindow.title('With_Border') # set the window sizewindow.geometry('300x100') # take one Label widgetlabel = Label(window, text=\"WELCOME TO GFG\", borderwidth=1, relief=\"solid\") # place that label to windowlabel.grid(column=0, row=1, padx=100, pady=10)window.mainloop()",
"e": 27332,
"s": 26968,
"text": null
},
{
"code": null,
"e": 27340,
"s": 27332,
"text": "Output:"
},
{
"code": null,
"e": 27394,
"s": 27340,
"text": "Program 2: to set the border and edit it as required."
},
{
"code": null,
"e": 27402,
"s": 27394,
"text": "Python3"
},
{
"code": "# import tkinterfrom tkinter import * # Create Tk objectwindow = Tk() # Set the window titlewindow.title('GFG') # take Label widgetsA = Label(window, text=\"flat\", width=10, height=2, borderwidth=3, relief=\"flat\")B = Label(window, text=\"solid\", width=10, height=2, borderwidth=3, relief=\"solid\")C = Label(window, text=\"raised\", width=10, height=2, borderwidth=3, relief=\"raised\")D = Label(window, text=\"sunken\", width=10, height=2, borderwidth=3, relief=\"sunken\")E = Label(window, text=\"ridge\", width=10, height=2, borderwidth=3, relief=\"ridge\")F = Label(window, text=\"groove\", width=10, height=2, borderwidth=3, relief=\"groove\") # place that labels to windowA.grid(column=0, row=1, padx=100, pady=10)B.grid(column=0, row=2, padx=100, pady=10)C.grid(column=0, row=3, padx=100, pady=10)D.grid(column=0, row=4, padx=100, pady=10)E.grid(column=0, row=5, padx=100, pady=10)F.grid(column=0, row=6, padx=100, pady=10) window.mainloop()",
"e": 28390,
"s": 27402,
"text": null
},
{
"code": null,
"e": 28398,
"s": 28390,
"text": "Output:"
},
{
"code": null,
"e": 28413,
"s": 28398,
"text": "Python-tkinter"
},
{
"code": null,
"e": 28437,
"s": 28413,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28444,
"s": 28437,
"text": "Python"
},
{
"code": null,
"e": 28463,
"s": 28444,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28561,
"s": 28463,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28579,
"s": 28561,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28614,
"s": 28579,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28646,
"s": 28614,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28668,
"s": 28646,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28710,
"s": 28668,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28740,
"s": 28710,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28766,
"s": 28740,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28810,
"s": 28766,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28839,
"s": 28810,
"text": "*args and **kwargs in Python"
}
] |
HTML | DOM Input Date value Property - GeeksforGeeks | 03 Feb, 2022
The Input Date value property is used for setting or returning the value of the value attribute of a date field. The Input Date value attribute can be used for specifying a date for the date field.Syntax:
For returning the value property:
inputdateObject.value
For setting the value property:
inputdateObject.value = YYYY-MM-DD
Property Value:
YYYY-MM-DD :It is used to specify the date. YYYY: It specifies the year.MM: It specifies the month.DD: It specifies the day of the month.
YYYY: It specifies the year.
MM: It specifies the month.
DD: It specifies the day of the month.
Return Value: It returns a string value which specify the value of date for the date field.
Below program illustrates the Date value property :Setting a date for a datetime field.
html
<!DOCTYPE html><html> <head> <title>Input Date value Property in HTML</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date value Property</h2> <br> Date Of Birth: <input type="date" id="Test_Date"> <p>To set a date for the date field, double-click the "Set Date" button.</p> <button ondblclick="My_Date()">Set Date</button> <p id="test"></p> <script> function My_Date() { document.getElementById("Test_Date").value = "2019-02-04"; } </script> </body>
Output:
After clicking the button
Example-2: Below code retuens a date value property.
HTML
<!DOCTYPE html><html> <head> <title>Input Date value Property in HTML</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date value Property</h2> <br> Date Of Birth: <input type="date" id="Test_Date" value="2013-12-12"> <p>To return a date for the date field, double-click the "Set Date" button.</p> <button ondblclick="My_Date()">Return Date</button> <p id="test"></p> <script> function My_Date() { var g = document.getElementById("Test_Date").value; document.getElementById('test').innerHTML= g; } </script> </body>
Before:
After:
Supported Web Browsers:
Apple Safari
Internet Explorer
Firefox
Google Chrome
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ManasChhabra2
hritikbhatnagar2182
sumitgumber28
HTML-DOM
HTML
Web Technologies
HTML
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 ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26218,
"s": 26190,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 26425,
"s": 26218,
"text": "The Input Date value property is used for setting or returning the value of the value attribute of a date field. The Input Date value attribute can be used for specifying a date for the date field.Syntax: "
},
{
"code": null,
"e": 26461,
"s": 26425,
"text": "For returning the value property: "
},
{
"code": null,
"e": 26483,
"s": 26461,
"text": "inputdateObject.value"
},
{
"code": null,
"e": 26517,
"s": 26483,
"text": "For setting the value property: "
},
{
"code": null,
"e": 26552,
"s": 26517,
"text": "inputdateObject.value = YYYY-MM-DD"
},
{
"code": null,
"e": 26570,
"s": 26552,
"text": "Property Value: "
},
{
"code": null,
"e": 26708,
"s": 26570,
"text": "YYYY-MM-DD :It is used to specify the date. YYYY: It specifies the year.MM: It specifies the month.DD: It specifies the day of the month."
},
{
"code": null,
"e": 26737,
"s": 26708,
"text": "YYYY: It specifies the year."
},
{
"code": null,
"e": 26765,
"s": 26737,
"text": "MM: It specifies the month."
},
{
"code": null,
"e": 26804,
"s": 26765,
"text": "DD: It specifies the day of the month."
},
{
"code": null,
"e": 26897,
"s": 26804,
"text": "Return Value: It returns a string value which specify the value of date for the date field. "
},
{
"code": null,
"e": 26987,
"s": 26897,
"text": "Below program illustrates the Date value property :Setting a date for a datetime field. "
},
{
"code": null,
"e": 26992,
"s": 26987,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Input Date value Property in HTML</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date value Property</h2> <br> Date Of Birth: <input type=\"date\" id=\"Test_Date\"> <p>To set a date for the date field, double-click the \"Set Date\" button.</p> <button ondblclick=\"My_Date()\">Set Date</button> <p id=\"test\"></p> <script> function My_Date() { document.getElementById(\"Test_Date\").value = \"2019-02-04\"; } </script> </body>",
"e": 27718,
"s": 26992,
"text": null
},
{
"code": null,
"e": 27728,
"s": 27718,
"text": "Output: "
},
{
"code": null,
"e": 27756,
"s": 27728,
"text": "After clicking the button "
},
{
"code": null,
"e": 27810,
"s": 27756,
"text": "Example-2: Below code retuens a date value property. "
},
{
"code": null,
"e": 27815,
"s": 27810,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Input Date value Property in HTML</title> <style> h1 { color: green; } h2 { font-family: Impact; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>Input Date value Property</h2> <br> Date Of Birth: <input type=\"date\" id=\"Test_Date\" value=\"2013-12-12\"> <p>To return a date for the date field, double-click the \"Set Date\" button.</p> <button ondblclick=\"My_Date()\">Return Date</button> <p id=\"test\"></p> <script> function My_Date() { var g = document.getElementById(\"Test_Date\").value; document.getElementById('test').innerHTML= g; } </script> </body>",
"e": 28622,
"s": 27815,
"text": null
},
{
"code": null,
"e": 28630,
"s": 28622,
"text": "Before:"
},
{
"code": null,
"e": 28637,
"s": 28630,
"text": "After:"
},
{
"code": null,
"e": 28663,
"s": 28637,
"text": "Supported Web Browsers: "
},
{
"code": null,
"e": 28676,
"s": 28663,
"text": "Apple Safari"
},
{
"code": null,
"e": 28694,
"s": 28676,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28702,
"s": 28694,
"text": "Firefox"
},
{
"code": null,
"e": 28716,
"s": 28702,
"text": "Google Chrome"
},
{
"code": null,
"e": 28722,
"s": 28716,
"text": "Opera"
},
{
"code": null,
"e": 28861,
"s": 28724,
"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": 28875,
"s": 28861,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 28895,
"s": 28875,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 28909,
"s": 28895,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28918,
"s": 28909,
"text": "HTML-DOM"
},
{
"code": null,
"e": 28923,
"s": 28918,
"text": "HTML"
},
{
"code": null,
"e": 28940,
"s": 28923,
"text": "Web Technologies"
},
{
"code": null,
"e": 28945,
"s": 28940,
"text": "HTML"
},
{
"code": null,
"e": 29043,
"s": 28945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29091,
"s": 29043,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29115,
"s": 29091,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29156,
"s": 29115,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 29206,
"s": 29156,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29256,
"s": 29206,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 29296,
"s": 29256,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29329,
"s": 29296,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29374,
"s": 29329,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29417,
"s": 29374,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Authenticate Using GitHub on Android - GeeksforGeeks | 06 Jun, 2021
GitHub is where over 65 million developers shape the future of software, together. Contribute to the open-source community, manage your Git repositories, review code like a pro, track bugs and features, power your CI/CD and DevOps workflows, and secure code before you commit it. So in this article, we are going to discuss how to authenticate using GitHub in your Android App with the help of Firebase User Authentication.
Step 1:
Create a new project in android studio or open any existing project through with you want to authenticate a user by GitHub and add the firebase to that android application. Steps to add firebase in your application.
Step 2:
Go to your firebase console, go to your application then navigate to project settings and add fingerprint-like SHA1 of your connected application. To find SHA1 go to Gradle (right side of android-studio window ) > your-application-name > Tasks > Android > signingReport (double click on it)
Note: Make sure to add google-services.json in your application, otherwise, download it from the project settings of the firebase console and add it to your application.
Step 3:
Go back to your application in the firebase console, navigate to Authentication (left panel of firebase) then go to Sign-in-method enable GitHub provider.
Enable GitHub
Require Client ID & Client secret
Now, we need Client ID and Client Secret. For this register your app as a developer application on GitHub and get your app’s OAuth 2.0 Client ID and Client Secret. To register your app, write the application name, enter the app’s website homepage URL (here I’m giving the same URL as in the Authorization callback URL), and provide the application description in brief.
Register an app on GitHub
Note: Make sure your Firebase OAuth redirect URI (e.g. my-app-12345.firebaseapp.com/__/auth/handler) is set as your Authorization callback URL in your app’s settings page on your GitHub app’s config.
Get your authorizable callback URL as shown in the image below.
Get your authorization callback URL
Click Register application. You will get your Client ID and Client secret, copy and paste them in the firebase console (under sign-in-method) and click the save button to enable GitHub.
Step 4:
Come back to android studio. Add dependency for the Firebase Authentication Android library in your build.gradle (Module: your-application-name.app) by using the Firebase Android BoM .
dependencies {
// Import the BoM for the Firebase platform
implementation platform(‘com.google.firebase:firebase-bom:28.0.1’)
// Declare the dependency for the Firebase Authentication library
// When using the BoM, you don’t specify versions in Firebase library dependencies
implementation ‘com.google.firebase:firebase-auth-ktx’
}
By using the Firebase Android BoM, your app will always use compatible versions of the Firebase Android libraries.
Step 5: Working with the MainActivity file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <EditText android:id="@+id/githubId" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:hint="Enter your email associated with github" android:padding="8dp" android:textAlignment="center" android:textColor="#118016" /> <Button android:id="@+id/github_login_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="100dp" android:layout_marginTop="10dp" android:layout_marginEnd="100dp" android:layout_marginBottom="100dp" android:backgroundTint="#fff" android:drawableLeft="@drawable/github" android:drawablePadding="8dp" android:padding="8dp" android:text="@string/log_in_with_github" android:textAllCaps="false" android:textColor="#000" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Intentimport android.os.Bundleimport android.text.TextUtilsimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport com.google.android.gms.tasks.OnFailureListenerimport com.google.android.gms.tasks.OnSuccessListenerimport com.google.android.gms.tasks.Taskimport com.google.firebase.auth.AuthResultimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.FirebaseUserimport com.google.firebase.auth.OAuthProvider class MainActivity : AppCompatActivity() { private lateinit var firebaseUser: FirebaseUser private lateinit var loginBtn: Button private lateinit var githubEdit: EditText // firebaseAuth variable to be initialized later private lateinit var auth: FirebaseAuth // an instance of an OAuthProvider using its Builder // with the provider ID github.com private val provider = OAuthProvider.newBuilder("github.com") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) loginBtn = findViewById(R.id.github_login_btn) githubEdit = findViewById(R.id.githubId) // initializing auth auth = FirebaseAuth.getInstance() // Target specific email with login hint. provider.addCustomParameter("login", githubEdit.text.toString()) // Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. val scopes: ArrayList<String?> = object : ArrayList<String?>() { init { add("user:email") } } provider.scopes = scopes // call signInWithGithubProvider() method // after clicking login Button loginBtn.setOnClickListener { if (TextUtils.isEmpty(githubEdit.text.toString())) { Toast.makeText(this, "Enter your github id", Toast.LENGTH_LONG).show() } else { signInWithGithubProvider() } } } // To check if there is a pending result, call pendingAuthResult private fun signInWithGithubProvider() { // There's something already here! Finish the sign-in for your user. val pendingResultTask: Task<AuthResult>? = auth.pendingAuthResult if (pendingResultTask != null) { pendingResultTask .addOnSuccessListener { // User is signed in. Toast.makeText(this, "User exist", Toast.LENGTH_LONG).show() } .addOnFailureListener { // Handle failure. Toast.makeText(this, "Error : $it", Toast.LENGTH_LONG).show() } } else { auth.startActivityForSignInWithProvider( /* activity= */this, provider.build()) .addOnSuccessListener( OnSuccessListener<AuthResult?> { // User is signed in. // retrieve the current user firebaseUser = auth.currentUser!! // navigate to HomePageActivity after successful login val intent = Intent(this, HomePageActivity::class.java) // send github user name from MainActivity to HomePageActivity intent.putExtra("githubUserName", firebaseUser.displayName) this.startActivity(intent) Toast.makeText(this, "Login Successfully", Toast.LENGTH_LONG).show() }) .addOnFailureListener( OnFailureListener { // Handle failure. Toast.makeText(this, "Error : $it", Toast.LENGTH_LONG).show() }) } }}
Step 6: Create a new Empty Activity
Refer to this article Create New Activity in Android Studio and create an empty activity. Name the activity as HomePageActivity. Navigate to the app > res > layout > activity_home_page.xml and add the below code to that file. Below is the code for the activity_home_page.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".HomePageActivity"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:orientation="horizontal" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:id="@+id/headerId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="User Name :" android:textColor="#06590A" android:textSize="25sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/id" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_marginTop="10dp" android:hint="github Id" android:textAlignment="center" android:textSize="25sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </LinearLayout> <Button android:id="@+id/logOut" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="456dp" android:layout_marginBottom="20dp" android:gravity="center" android:text="Logout" android:textColor="#fff" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout" /> </androidx.constraintlayout.widget.ConstraintLayout>
Go to the HomePageActivity.kt file and refer to the following code. Below is the code for the HomePageActivity.kt file.
Kotlin
import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextView class HomePageActivity : AppCompatActivity() { var userName = "" private lateinit var githubUserName: TextView private lateinit var logoutBtn: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home_page) githubUserName = findViewById(R.id.id) logoutBtn = findViewById(R.id.logOut) userName = intent.getStringExtra("githubUserName")!! githubUserName.text = userName logoutBtn.setOnClickListener { val intent = Intent(this, MainActivity::class.java) this.startActivity(intent) } }}
Note: Don’t forget to Revoke all user tokens. This option will be shown when your application is ready and run once. Or may you see this option earlier?
Here is the final output.
Output:
Firebase
GitHub
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
Kotlin when expression | [
{
"code": null,
"e": 26517,
"s": 26489,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 26942,
"s": 26517,
"text": "GitHub is where over 65 million developers shape the future of software, together. Contribute to the open-source community, manage your Git repositories, review code like a pro, track bugs and features, power your CI/CD and DevOps workflows, and secure code before you commit it. So in this article, we are going to discuss how to authenticate using GitHub in your Android App with the help of Firebase User Authentication. "
},
{
"code": null,
"e": 26951,
"s": 26942,
"text": "Step 1: "
},
{
"code": null,
"e": 27167,
"s": 26951,
"text": "Create a new project in android studio or open any existing project through with you want to authenticate a user by GitHub and add the firebase to that android application. Steps to add firebase in your application."
},
{
"code": null,
"e": 27177,
"s": 27167,
"text": "Step 2: "
},
{
"code": null,
"e": 27468,
"s": 27177,
"text": "Go to your firebase console, go to your application then navigate to project settings and add fingerprint-like SHA1 of your connected application. To find SHA1 go to Gradle (right side of android-studio window ) > your-application-name > Tasks > Android > signingReport (double click on it)"
},
{
"code": null,
"e": 27638,
"s": 27468,
"text": "Note: Make sure to add google-services.json in your application, otherwise, download it from the project settings of the firebase console and add it to your application."
},
{
"code": null,
"e": 27646,
"s": 27638,
"text": "Step 3:"
},
{
"code": null,
"e": 27801,
"s": 27646,
"text": "Go back to your application in the firebase console, navigate to Authentication (left panel of firebase) then go to Sign-in-method enable GitHub provider."
},
{
"code": null,
"e": 27815,
"s": 27801,
"text": "Enable GitHub"
},
{
"code": null,
"e": 27849,
"s": 27815,
"text": "Require Client ID & Client secret"
},
{
"code": null,
"e": 28219,
"s": 27849,
"text": "Now, we need Client ID and Client Secret. For this register your app as a developer application on GitHub and get your app’s OAuth 2.0 Client ID and Client Secret. To register your app, write the application name, enter the app’s website homepage URL (here I’m giving the same URL as in the Authorization callback URL), and provide the application description in brief."
},
{
"code": null,
"e": 28245,
"s": 28219,
"text": "Register an app on GitHub"
},
{
"code": null,
"e": 28446,
"s": 28245,
"text": "Note: Make sure your Firebase OAuth redirect URI (e.g. my-app-12345.firebaseapp.com/__/auth/handler) is set as your Authorization callback URL in your app’s settings page on your GitHub app’s config. "
},
{
"code": null,
"e": 28510,
"s": 28446,
"text": "Get your authorizable callback URL as shown in the image below."
},
{
"code": null,
"e": 28546,
"s": 28510,
"text": "Get your authorization callback URL"
},
{
"code": null,
"e": 28734,
"s": 28546,
"text": "Click Register application. You will get your Client ID and Client secret, copy and paste them in the firebase console (under sign-in-method) and click the save button to enable GitHub. "
},
{
"code": null,
"e": 28742,
"s": 28734,
"text": "Step 4:"
},
{
"code": null,
"e": 28927,
"s": 28742,
"text": "Come back to android studio. Add dependency for the Firebase Authentication Android library in your build.gradle (Module: your-application-name.app) by using the Firebase Android BoM ."
},
{
"code": null,
"e": 28942,
"s": 28927,
"text": "dependencies {"
},
{
"code": null,
"e": 28989,
"s": 28942,
"text": " // Import the BoM for the Firebase platform"
},
{
"code": null,
"e": 29059,
"s": 28989,
"text": " implementation platform(‘com.google.firebase:firebase-bom:28.0.1’)"
},
{
"code": null,
"e": 29128,
"s": 29059,
"text": " // Declare the dependency for the Firebase Authentication library"
},
{
"code": null,
"e": 29214,
"s": 29128,
"text": " // When using the BoM, you don’t specify versions in Firebase library dependencies"
},
{
"code": null,
"e": 29272,
"s": 29214,
"text": " implementation ‘com.google.firebase:firebase-auth-ktx’"
},
{
"code": null,
"e": 29274,
"s": 29272,
"text": "}"
},
{
"code": null,
"e": 29389,
"s": 29274,
"text": "By using the Firebase Android BoM, your app will always use compatible versions of the Firebase Android libraries."
},
{
"code": null,
"e": 29432,
"s": 29389,
"text": "Step 5: Working with the MainActivity file"
},
{
"code": null,
"e": 29575,
"s": 29432,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 29579,
"s": 29575,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:orientation=\"vertical\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <EditText android:id=\"@+id/githubId\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"100dp\" android:hint=\"Enter your email associated with github\" android:padding=\"8dp\" android:textAlignment=\"center\" android:textColor=\"#118016\" /> <Button android:id=\"@+id/github_login_btn\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"100dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"100dp\" android:layout_marginBottom=\"100dp\" android:backgroundTint=\"#fff\" android:drawableLeft=\"@drawable/github\" android:drawablePadding=\"8dp\" android:padding=\"8dp\" android:text=\"@string/log_in_with_github\" android:textAllCaps=\"false\" android:textColor=\"#000\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 31427,
"s": 29579,
"text": null
},
{
"code": null,
"e": 31613,
"s": 31427,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 31620,
"s": 31613,
"text": "Kotlin"
},
{
"code": "import android.content.Intentimport android.os.Bundleimport android.text.TextUtilsimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport com.google.android.gms.tasks.OnFailureListenerimport com.google.android.gms.tasks.OnSuccessListenerimport com.google.android.gms.tasks.Taskimport com.google.firebase.auth.AuthResultimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.FirebaseUserimport com.google.firebase.auth.OAuthProvider class MainActivity : AppCompatActivity() { private lateinit var firebaseUser: FirebaseUser private lateinit var loginBtn: Button private lateinit var githubEdit: EditText // firebaseAuth variable to be initialized later private lateinit var auth: FirebaseAuth // an instance of an OAuthProvider using its Builder // with the provider ID github.com private val provider = OAuthProvider.newBuilder(\"github.com\") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) loginBtn = findViewById(R.id.github_login_btn) githubEdit = findViewById(R.id.githubId) // initializing auth auth = FirebaseAuth.getInstance() // Target specific email with login hint. provider.addCustomParameter(\"login\", githubEdit.text.toString()) // Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. val scopes: ArrayList<String?> = object : ArrayList<String?>() { init { add(\"user:email\") } } provider.scopes = scopes // call signInWithGithubProvider() method // after clicking login Button loginBtn.setOnClickListener { if (TextUtils.isEmpty(githubEdit.text.toString())) { Toast.makeText(this, \"Enter your github id\", Toast.LENGTH_LONG).show() } else { signInWithGithubProvider() } } } // To check if there is a pending result, call pendingAuthResult private fun signInWithGithubProvider() { // There's something already here! Finish the sign-in for your user. val pendingResultTask: Task<AuthResult>? = auth.pendingAuthResult if (pendingResultTask != null) { pendingResultTask .addOnSuccessListener { // User is signed in. Toast.makeText(this, \"User exist\", Toast.LENGTH_LONG).show() } .addOnFailureListener { // Handle failure. Toast.makeText(this, \"Error : $it\", Toast.LENGTH_LONG).show() } } else { auth.startActivityForSignInWithProvider( /* activity= */this, provider.build()) .addOnSuccessListener( OnSuccessListener<AuthResult?> { // User is signed in. // retrieve the current user firebaseUser = auth.currentUser!! // navigate to HomePageActivity after successful login val intent = Intent(this, HomePageActivity::class.java) // send github user name from MainActivity to HomePageActivity intent.putExtra(\"githubUserName\", firebaseUser.displayName) this.startActivity(intent) Toast.makeText(this, \"Login Successfully\", Toast.LENGTH_LONG).show() }) .addOnFailureListener( OnFailureListener { // Handle failure. Toast.makeText(this, \"Error : $it\", Toast.LENGTH_LONG).show() }) } }}",
"e": 35738,
"s": 31620,
"text": null
},
{
"code": null,
"e": 35775,
"s": 35738,
"text": "Step 6: Create a new Empty Activity "
},
{
"code": null,
"e": 36057,
"s": 35775,
"text": "Refer to this article Create New Activity in Android Studio and create an empty activity. Name the activity as HomePageActivity. Navigate to the app > res > layout > activity_home_page.xml and add the below code to that file. Below is the code for the activity_home_page.xml file. "
},
{
"code": null,
"e": 36061,
"s": 36057,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".HomePageActivity\"> <LinearLayout android:id=\"@+id/linearLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"10dp\" android:orientation=\"horizontal\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <TextView android:id=\"@+id/headerId\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:text=\"User Name :\" android:textColor=\"#06590A\" android:textSize=\"25sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/id\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:layout_marginTop=\"10dp\" android:hint=\"github Id\" android:textAlignment=\"center\" android:textSize=\"25sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </LinearLayout> <Button android:id=\"@+id/logOut\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"456dp\" android:layout_marginBottom=\"20dp\" android:gravity=\"center\" android:text=\"Logout\" android:textColor=\"#fff\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/linearLayout\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 38476,
"s": 36061,
"text": null
},
{
"code": null,
"e": 38597,
"s": 38476,
"text": "Go to the HomePageActivity.kt file and refer to the following code. Below is the code for the HomePageActivity.kt file. "
},
{
"code": null,
"e": 38604,
"s": 38597,
"text": "Kotlin"
},
{
"code": "import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextView class HomePageActivity : AppCompatActivity() { var userName = \"\" private lateinit var githubUserName: TextView private lateinit var logoutBtn: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home_page) githubUserName = findViewById(R.id.id) logoutBtn = findViewById(R.id.logOut) userName = intent.getStringExtra(\"githubUserName\")!! githubUserName.text = userName logoutBtn.setOnClickListener { val intent = Intent(this, MainActivity::class.java) this.startActivity(intent) } }}",
"e": 39425,
"s": 38604,
"text": null
},
{
"code": null,
"e": 39578,
"s": 39425,
"text": "Note: Don’t forget to Revoke all user tokens. This option will be shown when your application is ready and run once. Or may you see this option earlier?"
},
{
"code": null,
"e": 39604,
"s": 39578,
"text": "Here is the final output."
},
{
"code": null,
"e": 39612,
"s": 39604,
"text": "Output:"
},
{
"code": null,
"e": 39621,
"s": 39612,
"text": "Firebase"
},
{
"code": null,
"e": 39628,
"s": 39621,
"text": "GitHub"
},
{
"code": null,
"e": 39636,
"s": 39628,
"text": "Android"
},
{
"code": null,
"e": 39643,
"s": 39636,
"text": "Kotlin"
},
{
"code": null,
"e": 39651,
"s": 39643,
"text": "Android"
},
{
"code": null,
"e": 39749,
"s": 39651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39787,
"s": 39749,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 39826,
"s": 39787,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 39876,
"s": 39826,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 39902,
"s": 39876,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 39953,
"s": 39902,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 39972,
"s": 39953,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 39985,
"s": 39972,
"text": "Kotlin Array"
},
{
"code": null,
"e": 40027,
"s": 39985,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 40054,
"s": 40027,
"text": "Kotlin Setters and Getters"
}
] |
Calculus — The Mathematics of ‘Change’ | by Gaurav Goel | Towards Data Science | Data Science and Machine Learning have fueled up interest in mathematics. A lot of people who are ramping up their skills in ML/AI domain have realized the practical applications of mathematical concepts, for the first time in their lives. During my venture into AI/ML space, I realized how difficult, mathematical ideas (such as calculus and vector algebra) were made in school and college than they really were! I am assuming a lot of people share this feeling. This article is an attempt to explain calculus and its applications, in a fundamental way without using the infamous jargons and big dreaded calculus equations. I anticipate that this reading will unfold the beauty, simplicity, and magic of calculus and mathematics, in general. The idea is to make you will fall in love with it!
Human beings have one great quality — “Curiosity”. Curiosity drives humankind to observe and understand nature. Science can be, broadly called, the study of nature while mathematics is the language to express it.
The understanding or learning is often expressed as a mathematical function that captures the relationship between the entities or dimensions involved. e.g let's say you are driving a car. You are measuring the speed of the car as time is passing by. Some sample measurements can be as follows:
As seen, there is a relationship between speed and time. As time passes by, the speed of the car increases at a constant rate. Every minute, the speed of the car increases by 5 times. This relationship can be expressed as follows:
Speed is a Function of time
Speed = f(time)
S = 5* t
Visually, you can see that there is a linear relationship between speed and time
You can imagine that this relationship is actually representing the equation of a line:
y = mx + b
where m is the slope and b is the intercept of the line.
In our example, the equation becomes s = 5t + 0
Focus on this thing known as “Slope”. What does it represent? We know that as time goes by, the speed of the car is changing. By what factor is this changing? We can find out by checking how much speed has changed for a change in time. e.g between t = 1 and t =2, the speed has changed from 5 to 10. This can be written as:
When things change, a more useful measurement to make is “Rate of Change”. The rate of change gives us an idea of how much one quantity is dependent on the other. If the rate is more, there will be a large correlation between the quantities and vice-versa. (Now think of what you try to do via Machine Learning. Do you see a connection?)
In our case, if we divide the “change in speed” with “change in time”, it gives us the rate of change
This is the rate of change of speed with respect to change in time. For our example, this rate is constant. You can take other time intervals (e.g t=2 and t=5) and measure the change in speed (25–10). The rate is the same — 5
(25-10)/(5–2)
The rate of change is also known as slope or gradient. Notice that greater the rate of change, greater will be the inclination of the line (hence, greater the slope). Compare the slope of the orange and blue lines in the below graph:
What has this to do with calculus? In fact, this is calculus.
Calculus is the branch of mathematics that deals with study of change
Calculus helps in finding out the relationship between two variables (quantities) by measuring how one variable changes when there is a change in another variable and how these changes accumulate over time.
In our example above, the speed of the car is increasing at a constant rate. What will happen if this rate of change is not constant? What if the car is accelerating and the rate of change in speed is different every minute
How to measure the rate of change, in this case, because its different for different time periods? We can not define a single rate of change in speed for this kind of data.
You can notice that the rate of change of speed climbs up as time passes. The mathematical function that captures this relationship is not a straight line but its a “curved line”.
From our earlier example, we know that the slope or gradient of a straight line gives us the rate of change of the Y-axis variable (Speed) with respect to the X-axis variable(Time). The property of “straightness” means that the rate of change was constant.
But...
The property of “curviness” means that rate of change is not constant.
Here comes the beauty of calculus.......
What you can do is to imagine the curve as a collection of lots of “very small straight line segments”
We will now be calculating the slope of a “very small” line segment of the curve. This slope represents a “very small” change in speed with respect to a “very small” change in time.
Let's denote “very small” change in speed as “ds”.
Similarly a “very small” change in time as “dt”
The slope of this “very small” line segment is
It can be calculated as follows:
Note that since “dt” is already very small, so the below will become extremely small and hence can be neglected
Theoretically, we can make ds and dt infinitesimally small, so that this “very small” line segment” becomes a point. The rate of change or slope at this point or instant of time is actually a tangent to the curve.
So, the function and rate of change of this function at a particular instant, in our example, is
In calculus terminology, the process of finding out the rate of change of a variable with respect to another is known as “differentiation”. In other words, if
y = f(x)
then the process of finding out dy/dx is known as “differentiation” or “differentiating”. The ratio dy/dx is called “the differential coefficient of y with respect to x” or “derivative”. Remember, its nothing but the rate of change of y with respect to x.
Keep in mind — “dx” means a very small part of x
What if ‘y’ is a constant. What will be dy/dx in this case? It will be 0 as the value of y is not changing. It's a constant.
The most robust application of Calculus in Machine Learning is the Gradient Descent algorithm in Linear regression (and Neural Networks)
Linear regression involves using data to calculate a line that best fits that data, and then using that line to predict scores on one variable from another. Prediction is simply the process of estimating scores of the outcome (or dependent) variable based on the scores of the predictor (or independent) variable. To generate the regression line, we look for a line of best fit. A line that can explain the relationship between the independent and dependent variable(s), better is said to be the best-fit line. The difference between the observed value and the actual value gives the error. The formula to calculate this error is also called the cost function.
The line of best fit will be expressed mathematically as
Y = m.x + c
where m and c are the slope and intercept of the line respectively. These are the two coefficients that the gradient descent algorithm has to find out.
The error will depend upon the coefficients of the line. If the value of coefficients is not optimal, then the error will be more. The cost function or the amount of error of Linear regression model is dependent upon the value of coefficient chosen.
This is where the calculus is used. We can find the rate of change of error with respect to the different values of coefficients. The value for which the rate of change is minimum( i.e 0, the bottom of the curve) is the optimal value.
So differentiation is used to find the minimum point of the curve. This point gives the optimal value of the coefficient that was being looked for!
There is a second part to Calculus — Integration. It is simply, the reverse of Differentiation.
In differentiation, we break up things into smaller and smaller parts.
In integration, we accumulate or add up, all the smaller parts together. The symbol for integration is:
Whenever you see this symbol, just replace it in your mind by “Add Up all”.
What will be the sum of all small parts of x?
(There is an amazing book “Calculus Made Easy” by Silvanus P. Thompson which explains these concepts beautifully in detail)
Why are we doing it? Why integrate? The simple answer this —
There are many things that can not be understood until and unless you break them up into smaller parts, do some operation for each smaller part and then accumulate or add up the results.
Let us take a rectangle:
We know that area of a rectangle is Length * Width (y *x)
Can you prove it? Think in terms of calculus. Imagine a smaller rectangle by taking a small bit of width(dx).
The whole of rectangle can be thought of sum of all smaller rectangles where width is dx
So, now we have ‘x’ number of small rectangles, each with width dx and length as y.
If you imagine dx to be very very small, the mini rectangle will eventually be reduced to a line (width close to 0 and length as y). The whole rectangle is just a collection of ‘lines’ each of length ‘y’. How many lines? — x.
Total area = Length of Line1 + Length of Line 2 + .......+ Length of Line X
Area = Y * X
Learning (Human or Machine) is all about finding relationships between variables.If the change in the value of a variable is triggered by the change in the value of another variable, its often very useful to find out the rate of change. This rate actually is the measurement of the relationship between the two variables. In mathematical terms, its also known as slope or gradient. Calculus is the branch of mathematics to study “change”Differentiation is the process of finding out the rate of change of one variable with respect to the change in another variable. The ratio dy/dx represents this rate of change. Geometrically, it represents the slope of a tangent to function.In Machine Learning, the regression algorithms use the process of differentiation to measure the rate of change of error in the model with a change in the value of the coefficient chosen. The value of coefficient where this rate of change is 0, gives the optimal value.
Learning (Human or Machine) is all about finding relationships between variables.
If the change in the value of a variable is triggered by the change in the value of another variable, its often very useful to find out the rate of change. This rate actually is the measurement of the relationship between the two variables. In mathematical terms, its also known as slope or gradient. Calculus is the branch of mathematics to study “change”
Differentiation is the process of finding out the rate of change of one variable with respect to the change in another variable. The ratio dy/dx represents this rate of change. Geometrically, it represents the slope of a tangent to function.
In Machine Learning, the regression algorithms use the process of differentiation to measure the rate of change of error in the model with a change in the value of the coefficient chosen. The value of coefficient where this rate of change is 0, gives the optimal value.
Once you start realizing the intuition behind mathematical concepts, the whole way of thinking can change. Differentiation and Integration allow us to view the world as a set of small parts and the sum of these small parts.
You may also like below articles:
Why Data is represented as a Vector in Data Science?Discovering Mathematical MindsetHuman Learning vs Machine Learning
Why Data is represented as a Vector in Data Science?
Discovering Mathematical Mindset
Human Learning vs Machine Learning | [
{
"code": null,
"e": 966,
"s": 172,
"text": "Data Science and Machine Learning have fueled up interest in mathematics. A lot of people who are ramping up their skills in ML/AI domain have realized the practical applications of mathematical concepts, for the first time in their lives. During my venture into AI/ML space, I realized how difficult, mathematical ideas (such as calculus and vector algebra) were made in school and college than they really were! I am assuming a lot of people share this feeling. This article is an attempt to explain calculus and its applications, in a fundamental way without using the infamous jargons and big dreaded calculus equations. I anticipate that this reading will unfold the beauty, simplicity, and magic of calculus and mathematics, in general. The idea is to make you will fall in love with it!"
},
{
"code": null,
"e": 1179,
"s": 966,
"text": "Human beings have one great quality — “Curiosity”. Curiosity drives humankind to observe and understand nature. Science can be, broadly called, the study of nature while mathematics is the language to express it."
},
{
"code": null,
"e": 1474,
"s": 1179,
"text": "The understanding or learning is often expressed as a mathematical function that captures the relationship between the entities or dimensions involved. e.g let's say you are driving a car. You are measuring the speed of the car as time is passing by. Some sample measurements can be as follows:"
},
{
"code": null,
"e": 1705,
"s": 1474,
"text": "As seen, there is a relationship between speed and time. As time passes by, the speed of the car increases at a constant rate. Every minute, the speed of the car increases by 5 times. This relationship can be expressed as follows:"
},
{
"code": null,
"e": 1733,
"s": 1705,
"text": "Speed is a Function of time"
},
{
"code": null,
"e": 1749,
"s": 1733,
"text": "Speed = f(time)"
},
{
"code": null,
"e": 1758,
"s": 1749,
"text": "S = 5* t"
},
{
"code": null,
"e": 1839,
"s": 1758,
"text": "Visually, you can see that there is a linear relationship between speed and time"
},
{
"code": null,
"e": 1927,
"s": 1839,
"text": "You can imagine that this relationship is actually representing the equation of a line:"
},
{
"code": null,
"e": 1938,
"s": 1927,
"text": "y = mx + b"
},
{
"code": null,
"e": 1995,
"s": 1938,
"text": "where m is the slope and b is the intercept of the line."
},
{
"code": null,
"e": 2043,
"s": 1995,
"text": "In our example, the equation becomes s = 5t + 0"
},
{
"code": null,
"e": 2367,
"s": 2043,
"text": "Focus on this thing known as “Slope”. What does it represent? We know that as time goes by, the speed of the car is changing. By what factor is this changing? We can find out by checking how much speed has changed for a change in time. e.g between t = 1 and t =2, the speed has changed from 5 to 10. This can be written as:"
},
{
"code": null,
"e": 2705,
"s": 2367,
"text": "When things change, a more useful measurement to make is “Rate of Change”. The rate of change gives us an idea of how much one quantity is dependent on the other. If the rate is more, there will be a large correlation between the quantities and vice-versa. (Now think of what you try to do via Machine Learning. Do you see a connection?)"
},
{
"code": null,
"e": 2807,
"s": 2705,
"text": "In our case, if we divide the “change in speed” with “change in time”, it gives us the rate of change"
},
{
"code": null,
"e": 3033,
"s": 2807,
"text": "This is the rate of change of speed with respect to change in time. For our example, this rate is constant. You can take other time intervals (e.g t=2 and t=5) and measure the change in speed (25–10). The rate is the same — 5"
},
{
"code": null,
"e": 3047,
"s": 3033,
"text": "(25-10)/(5–2)"
},
{
"code": null,
"e": 3281,
"s": 3047,
"text": "The rate of change is also known as slope or gradient. Notice that greater the rate of change, greater will be the inclination of the line (hence, greater the slope). Compare the slope of the orange and blue lines in the below graph:"
},
{
"code": null,
"e": 3343,
"s": 3281,
"text": "What has this to do with calculus? In fact, this is calculus."
},
{
"code": null,
"e": 3413,
"s": 3343,
"text": "Calculus is the branch of mathematics that deals with study of change"
},
{
"code": null,
"e": 3620,
"s": 3413,
"text": "Calculus helps in finding out the relationship between two variables (quantities) by measuring how one variable changes when there is a change in another variable and how these changes accumulate over time."
},
{
"code": null,
"e": 3844,
"s": 3620,
"text": "In our example above, the speed of the car is increasing at a constant rate. What will happen if this rate of change is not constant? What if the car is accelerating and the rate of change in speed is different every minute"
},
{
"code": null,
"e": 4017,
"s": 3844,
"text": "How to measure the rate of change, in this case, because its different for different time periods? We can not define a single rate of change in speed for this kind of data."
},
{
"code": null,
"e": 4197,
"s": 4017,
"text": "You can notice that the rate of change of speed climbs up as time passes. The mathematical function that captures this relationship is not a straight line but its a “curved line”."
},
{
"code": null,
"e": 4454,
"s": 4197,
"text": "From our earlier example, we know that the slope or gradient of a straight line gives us the rate of change of the Y-axis variable (Speed) with respect to the X-axis variable(Time). The property of “straightness” means that the rate of change was constant."
},
{
"code": null,
"e": 4461,
"s": 4454,
"text": "But..."
},
{
"code": null,
"e": 4532,
"s": 4461,
"text": "The property of “curviness” means that rate of change is not constant."
},
{
"code": null,
"e": 4573,
"s": 4532,
"text": "Here comes the beauty of calculus......."
},
{
"code": null,
"e": 4676,
"s": 4573,
"text": "What you can do is to imagine the curve as a collection of lots of “very small straight line segments”"
},
{
"code": null,
"e": 4858,
"s": 4676,
"text": "We will now be calculating the slope of a “very small” line segment of the curve. This slope represents a “very small” change in speed with respect to a “very small” change in time."
},
{
"code": null,
"e": 4909,
"s": 4858,
"text": "Let's denote “very small” change in speed as “ds”."
},
{
"code": null,
"e": 4957,
"s": 4909,
"text": "Similarly a “very small” change in time as “dt”"
},
{
"code": null,
"e": 5004,
"s": 4957,
"text": "The slope of this “very small” line segment is"
},
{
"code": null,
"e": 5037,
"s": 5004,
"text": "It can be calculated as follows:"
},
{
"code": null,
"e": 5149,
"s": 5037,
"text": "Note that since “dt” is already very small, so the below will become extremely small and hence can be neglected"
},
{
"code": null,
"e": 5363,
"s": 5149,
"text": "Theoretically, we can make ds and dt infinitesimally small, so that this “very small” line segment” becomes a point. The rate of change or slope at this point or instant of time is actually a tangent to the curve."
},
{
"code": null,
"e": 5460,
"s": 5363,
"text": "So, the function and rate of change of this function at a particular instant, in our example, is"
},
{
"code": null,
"e": 5619,
"s": 5460,
"text": "In calculus terminology, the process of finding out the rate of change of a variable with respect to another is known as “differentiation”. In other words, if"
},
{
"code": null,
"e": 5628,
"s": 5619,
"text": "y = f(x)"
},
{
"code": null,
"e": 5884,
"s": 5628,
"text": "then the process of finding out dy/dx is known as “differentiation” or “differentiating”. The ratio dy/dx is called “the differential coefficient of y with respect to x” or “derivative”. Remember, its nothing but the rate of change of y with respect to x."
},
{
"code": null,
"e": 5933,
"s": 5884,
"text": "Keep in mind — “dx” means a very small part of x"
},
{
"code": null,
"e": 6058,
"s": 5933,
"text": "What if ‘y’ is a constant. What will be dy/dx in this case? It will be 0 as the value of y is not changing. It's a constant."
},
{
"code": null,
"e": 6195,
"s": 6058,
"text": "The most robust application of Calculus in Machine Learning is the Gradient Descent algorithm in Linear regression (and Neural Networks)"
},
{
"code": null,
"e": 6856,
"s": 6195,
"text": "Linear regression involves using data to calculate a line that best fits that data, and then using that line to predict scores on one variable from another. Prediction is simply the process of estimating scores of the outcome (or dependent) variable based on the scores of the predictor (or independent) variable. To generate the regression line, we look for a line of best fit. A line that can explain the relationship between the independent and dependent variable(s), better is said to be the best-fit line. The difference between the observed value and the actual value gives the error. The formula to calculate this error is also called the cost function."
},
{
"code": null,
"e": 6913,
"s": 6856,
"text": "The line of best fit will be expressed mathematically as"
},
{
"code": null,
"e": 6925,
"s": 6913,
"text": "Y = m.x + c"
},
{
"code": null,
"e": 7077,
"s": 6925,
"text": "where m and c are the slope and intercept of the line respectively. These are the two coefficients that the gradient descent algorithm has to find out."
},
{
"code": null,
"e": 7327,
"s": 7077,
"text": "The error will depend upon the coefficients of the line. If the value of coefficients is not optimal, then the error will be more. The cost function or the amount of error of Linear regression model is dependent upon the value of coefficient chosen."
},
{
"code": null,
"e": 7562,
"s": 7327,
"text": "This is where the calculus is used. We can find the rate of change of error with respect to the different values of coefficients. The value for which the rate of change is minimum( i.e 0, the bottom of the curve) is the optimal value."
},
{
"code": null,
"e": 7710,
"s": 7562,
"text": "So differentiation is used to find the minimum point of the curve. This point gives the optimal value of the coefficient that was being looked for!"
},
{
"code": null,
"e": 7806,
"s": 7710,
"text": "There is a second part to Calculus — Integration. It is simply, the reverse of Differentiation."
},
{
"code": null,
"e": 7877,
"s": 7806,
"text": "In differentiation, we break up things into smaller and smaller parts."
},
{
"code": null,
"e": 7981,
"s": 7877,
"text": "In integration, we accumulate or add up, all the smaller parts together. The symbol for integration is:"
},
{
"code": null,
"e": 8057,
"s": 7981,
"text": "Whenever you see this symbol, just replace it in your mind by “Add Up all”."
},
{
"code": null,
"e": 8103,
"s": 8057,
"text": "What will be the sum of all small parts of x?"
},
{
"code": null,
"e": 8227,
"s": 8103,
"text": "(There is an amazing book “Calculus Made Easy” by Silvanus P. Thompson which explains these concepts beautifully in detail)"
},
{
"code": null,
"e": 8288,
"s": 8227,
"text": "Why are we doing it? Why integrate? The simple answer this —"
},
{
"code": null,
"e": 8475,
"s": 8288,
"text": "There are many things that can not be understood until and unless you break them up into smaller parts, do some operation for each smaller part and then accumulate or add up the results."
},
{
"code": null,
"e": 8500,
"s": 8475,
"text": "Let us take a rectangle:"
},
{
"code": null,
"e": 8558,
"s": 8500,
"text": "We know that area of a rectangle is Length * Width (y *x)"
},
{
"code": null,
"e": 8668,
"s": 8558,
"text": "Can you prove it? Think in terms of calculus. Imagine a smaller rectangle by taking a small bit of width(dx)."
},
{
"code": null,
"e": 8757,
"s": 8668,
"text": "The whole of rectangle can be thought of sum of all smaller rectangles where width is dx"
},
{
"code": null,
"e": 8841,
"s": 8757,
"text": "So, now we have ‘x’ number of small rectangles, each with width dx and length as y."
},
{
"code": null,
"e": 9067,
"s": 8841,
"text": "If you imagine dx to be very very small, the mini rectangle will eventually be reduced to a line (width close to 0 and length as y). The whole rectangle is just a collection of ‘lines’ each of length ‘y’. How many lines? — x."
},
{
"code": null,
"e": 9143,
"s": 9067,
"text": "Total area = Length of Line1 + Length of Line 2 + .......+ Length of Line X"
},
{
"code": null,
"e": 9156,
"s": 9143,
"text": "Area = Y * X"
},
{
"code": null,
"e": 10104,
"s": 9156,
"text": "Learning (Human or Machine) is all about finding relationships between variables.If the change in the value of a variable is triggered by the change in the value of another variable, its often very useful to find out the rate of change. This rate actually is the measurement of the relationship between the two variables. In mathematical terms, its also known as slope or gradient. Calculus is the branch of mathematics to study “change”Differentiation is the process of finding out the rate of change of one variable with respect to the change in another variable. The ratio dy/dx represents this rate of change. Geometrically, it represents the slope of a tangent to function.In Machine Learning, the regression algorithms use the process of differentiation to measure the rate of change of error in the model with a change in the value of the coefficient chosen. The value of coefficient where this rate of change is 0, gives the optimal value."
},
{
"code": null,
"e": 10186,
"s": 10104,
"text": "Learning (Human or Machine) is all about finding relationships between variables."
},
{
"code": null,
"e": 10543,
"s": 10186,
"text": "If the change in the value of a variable is triggered by the change in the value of another variable, its often very useful to find out the rate of change. This rate actually is the measurement of the relationship between the two variables. In mathematical terms, its also known as slope or gradient. Calculus is the branch of mathematics to study “change”"
},
{
"code": null,
"e": 10785,
"s": 10543,
"text": "Differentiation is the process of finding out the rate of change of one variable with respect to the change in another variable. The ratio dy/dx represents this rate of change. Geometrically, it represents the slope of a tangent to function."
},
{
"code": null,
"e": 11055,
"s": 10785,
"text": "In Machine Learning, the regression algorithms use the process of differentiation to measure the rate of change of error in the model with a change in the value of the coefficient chosen. The value of coefficient where this rate of change is 0, gives the optimal value."
},
{
"code": null,
"e": 11279,
"s": 11055,
"text": "Once you start realizing the intuition behind mathematical concepts, the whole way of thinking can change. Differentiation and Integration allow us to view the world as a set of small parts and the sum of these small parts."
},
{
"code": null,
"e": 11313,
"s": 11279,
"text": "You may also like below articles:"
},
{
"code": null,
"e": 11432,
"s": 11313,
"text": "Why Data is represented as a Vector in Data Science?Discovering Mathematical MindsetHuman Learning vs Machine Learning"
},
{
"code": null,
"e": 11485,
"s": 11432,
"text": "Why Data is represented as a Vector in Data Science?"
},
{
"code": null,
"e": 11518,
"s": 11485,
"text": "Discovering Mathematical Mindset"
}
] |
Is digital root of N a prime? | Practice | GeeksforGeeks | Given a number N, you need to find if its digital root is prime or not. DigitalRoot of a number is the repetitive sum of its digits until we get a single-digit number.
Eg.DigitalRoot(191)=1+9+1=>11=>1+1=>2
Example 1:
Input:
N = 89
Output:
0
Explanation:
DigitalRoot(89)=>17=>1+7=>8; not a prime.
Example 2:
Input:
N = 12
Output:
1
Explanation:
DigitalRoot(12)=>1+2=>3; a prime number.
Your Task:
You don't need to read input or print anything. Your task is to complete the function digitalRoot() which takes an integer N as an input parameter and return 1 if its digital root is a prime number otherwise return 0.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 104
0
raghvendrapratap76992 months ago
class Solution{public: int digitalRoot(int n) { int sum=0,x,sum2=0,z; while(n!=0) { x=n%10; sum=sum+x; n=n/10; } if(sum<10) { if(sum==2 || sum==3) return true; if(sum==5 || sum==7) return true; } else { while(sum!=0) { z=sum%10; sum2=sum2+z; sum=sum/10; } if(sum2==2 || sum2==3) return true; if(sum2==5 || sum2==7 ) return true; if (sum2==11) return true; } return false; } };
0
pranjal pandey10 months ago
pranjal pandey
https://uploads.disquscdn.c...
0
pranjal pandey
This comment was deleted.
0
pranjal pandey10 months ago
pranjal pandey
IF ANYONE GET O(1) solution PLEASE TELL.
bool isPrime(int m){ if(m==1)return false; if(m==2)return true; for(int i=2;i*i<m;i++){ if(m%i="=0){" return="" false;="" break;}="" }="" return="" true;="" }="" int="" digital_root(int="" n){="" if(n<10)return="" n;="" int="" x="n%10;" return="" digital_root(x+n="" 10);="" }="" int="" digitalroot(int="" n)="" {="" int="" m="digital_Root(N);" return="" isprime(m);="" }="">
0
pranjal pandey
This comment was deleted.
0
Yash Patil2 years ago
Yash Patil
public static void main (String[] args) {Scanner sc1 =new Scanner(System.in);int test=sc1.nextInt();while(test!=0){ int num=sc1.nextInt(); int temp=num; int k=1,sum=0; while(temp!=0) { sum+=(temp%10); temp/=10; } if((sum*k)%9==0) { System.out.println(0); } else { if(isPrime(((sum*k)%9))) { System.out.println(1); } else { System.out.println(0); } } test--;}}public static boolean isPrime(int num){ if(num==0||num==1) { return false; } for(int i=2;i*i<=num;i++) { if(num%i==0) { return false; } } return true;}
0
Shashwat Sharma2 years ago
Shashwat Sharma
0.01 sec....#include <iostream>using namespace std;
int main() {//codeint t; cin>>t;while(t-->0){ int sum=0,cnt=0,n; cin>>n; while(n>0 || sum>9) { if(n==0) { n=sum; sum=0; } sum+=n%10; n/=10; } for(int i=1;i<=sum;i++) { if(sum%i==0) cnt++; } if(cnt==2) cout<<"1"<<endl; else="" cout<<"0"<<endl;="" }="" return="" 0;="" }="">
0
Govind Kumar2 years ago
Govind Kumar
0
Ayush Mishra2 years ago
Ayush Mishra
/*package whatever //do not write package name here */
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) {Scanner sc= new Scanner(System.in);int n=sc.nextInt(); while (n-->0){ sc.nextLine(); int a= sc.nextInt(); int sum=0,x=0; while (a!=0) { x=a % 10; sum=sum+x; a/=10; if (sum>=10 && a==0) { a=sum; sum=0; } } int length=0; for (int i=2;i<sum;i++) {="" if="" (sum="" %="" i="=0)" {="" length++;="" }="" }="" if="" (length="=0" &&="" sum!="1)" {="" system.out.println("1");="" }="" else="" if(sum="=1" ||="" length="">0) { System.out.println("0"); }}}}
0
nandini2 years ago
nandini
please help me.my o/p is correct but then also its giving wrong.https://ide.geeksforgeeks.o...
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": 432,
"s": 226,
"text": "Given a number N, you need to find if its digital root is prime or not. DigitalRoot of a number is the repetitive sum of its digits until we get a single-digit number.\nEg.DigitalRoot(191)=1+9+1=>11=>1+1=>2"
},
{
"code": null,
"e": 443,
"s": 432,
"text": "Example 1:"
},
{
"code": null,
"e": 522,
"s": 443,
"text": "Input:\nN = 89\nOutput:\n0\nExplanation:\nDigitalRoot(89)=>17=>1+7=>8; not a prime."
},
{
"code": null,
"e": 533,
"s": 522,
"text": "Example 2:"
},
{
"code": null,
"e": 611,
"s": 533,
"text": "Input:\nN = 12\nOutput:\n1\nExplanation:\nDigitalRoot(12)=>1+2=>3; a prime number."
},
{
"code": null,
"e": 905,
"s": 611,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function digitalRoot() which takes an integer N as an input parameter and return 1 if its digital root is a prime number otherwise return 0.\n\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 932,
"s": 905,
"text": "Constraints:\n1 <= N <= 104"
},
{
"code": null,
"e": 934,
"s": 932,
"text": "0"
},
{
"code": null,
"e": 967,
"s": 934,
"text": "raghvendrapratap76992 months ago"
},
{
"code": null,
"e": 1641,
"s": 969,
"text": "class Solution{public: int digitalRoot(int n) { int sum=0,x,sum2=0,z; while(n!=0) { x=n%10; sum=sum+x; n=n/10; } if(sum<10) { if(sum==2 || sum==3) return true; if(sum==5 || sum==7) return true; } else { while(sum!=0) { z=sum%10; sum2=sum2+z; sum=sum/10; } if(sum2==2 || sum2==3) return true; if(sum2==5 || sum2==7 ) return true; if (sum2==11) return true; } return false; } };"
},
{
"code": null,
"e": 1643,
"s": 1641,
"text": "0"
},
{
"code": null,
"e": 1671,
"s": 1643,
"text": "pranjal pandey10 months ago"
},
{
"code": null,
"e": 1686,
"s": 1671,
"text": "pranjal pandey"
},
{
"code": null,
"e": 1717,
"s": 1686,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 1719,
"s": 1717,
"text": "0"
},
{
"code": null,
"e": 1734,
"s": 1719,
"text": "pranjal pandey"
},
{
"code": null,
"e": 1760,
"s": 1734,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1762,
"s": 1760,
"text": "0"
},
{
"code": null,
"e": 1790,
"s": 1762,
"text": "pranjal pandey10 months ago"
},
{
"code": null,
"e": 1805,
"s": 1790,
"text": "pranjal pandey"
},
{
"code": null,
"e": 1846,
"s": 1805,
"text": "IF ANYONE GET O(1) solution PLEASE TELL."
},
{
"code": null,
"e": 2240,
"s": 1846,
"text": "bool isPrime(int m){ if(m==1)return false; if(m==2)return true; for(int i=2;i*i<m;i++){ if(m%i=\"=0){\" return=\"\" false;=\"\" break;}=\"\" }=\"\" return=\"\" true;=\"\" }=\"\" int=\"\" digital_root(int=\"\" n){=\"\" if(n<10)return=\"\" n;=\"\" int=\"\" x=\"n%10;\" return=\"\" digital_root(x+n=\"\" 10);=\"\" }=\"\" int=\"\" digitalroot(int=\"\" n)=\"\" {=\"\" int=\"\" m=\"digital_Root(N);\" return=\"\" isprime(m);=\"\" }=\"\">"
},
{
"code": null,
"e": 2242,
"s": 2240,
"text": "0"
},
{
"code": null,
"e": 2257,
"s": 2242,
"text": "pranjal pandey"
},
{
"code": null,
"e": 2283,
"s": 2257,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2285,
"s": 2283,
"text": "0"
},
{
"code": null,
"e": 2307,
"s": 2285,
"text": "Yash Patil2 years ago"
},
{
"code": null,
"e": 2318,
"s": 2307,
"text": "Yash Patil"
},
{
"code": null,
"e": 3013,
"s": 2318,
"text": "public static void main (String[] args) {Scanner sc1 =new Scanner(System.in);int test=sc1.nextInt();while(test!=0){ int num=sc1.nextInt(); int temp=num; int k=1,sum=0; while(temp!=0) { sum+=(temp%10); temp/=10; } if((sum*k)%9==0) { System.out.println(0); } else { if(isPrime(((sum*k)%9))) { System.out.println(1); } else { System.out.println(0); } } test--;}}public static boolean isPrime(int num){ if(num==0||num==1) { return false; } for(int i=2;i*i<=num;i++) { if(num%i==0) { return false; } } return true;}"
},
{
"code": null,
"e": 3015,
"s": 3013,
"text": "0"
},
{
"code": null,
"e": 3042,
"s": 3015,
"text": "Shashwat Sharma2 years ago"
},
{
"code": null,
"e": 3058,
"s": 3042,
"text": "Shashwat Sharma"
},
{
"code": null,
"e": 3110,
"s": 3058,
"text": "0.01 sec....#include <iostream>using namespace std;"
},
{
"code": null,
"e": 3488,
"s": 3110,
"text": "int main() {//codeint t; cin>>t;while(t-->0){ int sum=0,cnt=0,n; cin>>n; while(n>0 || sum>9) { if(n==0) { n=sum; sum=0; } sum+=n%10; n/=10; } for(int i=1;i<=sum;i++) { if(sum%i==0) cnt++; } if(cnt==2) cout<<\"1\"<<endl; else=\"\" cout<<\"0\"<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">"
},
{
"code": null,
"e": 3490,
"s": 3488,
"text": "0"
},
{
"code": null,
"e": 3514,
"s": 3490,
"text": "Govind Kumar2 years ago"
},
{
"code": null,
"e": 3527,
"s": 3514,
"text": "Govind Kumar"
},
{
"code": null,
"e": 3529,
"s": 3527,
"text": "0"
},
{
"code": null,
"e": 3553,
"s": 3529,
"text": "Ayush Mishra2 years ago"
},
{
"code": null,
"e": 3566,
"s": 3553,
"text": "Ayush Mishra"
},
{
"code": null,
"e": 3621,
"s": 3566,
"text": "/*package whatever //do not write package name here */"
},
{
"code": null,
"e": 3677,
"s": 3621,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 4277,
"s": 3677,
"text": "class GFG {public static void main (String[] args) {Scanner sc= new Scanner(System.in);int n=sc.nextInt(); while (n-->0){ sc.nextLine(); int a= sc.nextInt(); int sum=0,x=0; while (a!=0) { x=a % 10; sum=sum+x; a/=10; if (sum>=10 && a==0) { a=sum; sum=0; } } int length=0; for (int i=2;i<sum;i++) {=\"\" if=\"\" (sum=\"\" %=\"\" i=\"=0)\" {=\"\" length++;=\"\" }=\"\" }=\"\" if=\"\" (length=\"=0\" &&=\"\" sum!=\"1)\" {=\"\" system.out.println(\"1\");=\"\" }=\"\" else=\"\" if(sum=\"=1\" ||=\"\" length=\"\">0) { System.out.println(\"0\"); }}}}"
},
{
"code": null,
"e": 4279,
"s": 4277,
"text": "0"
},
{
"code": null,
"e": 4298,
"s": 4279,
"text": "nandini2 years ago"
},
{
"code": null,
"e": 4306,
"s": 4298,
"text": "nandini"
},
{
"code": null,
"e": 4401,
"s": 4306,
"text": "please help me.my o/p is correct but then also its giving wrong.https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 4547,
"s": 4401,
"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": 4583,
"s": 4547,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4593,
"s": 4583,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4603,
"s": 4593,
"text": "\nContest\n"
},
{
"code": null,
"e": 4666,
"s": 4603,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4814,
"s": 4666,
"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": 5022,
"s": 4814,
"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": 5128,
"s": 5022,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Is it possible to rename _id field after MongoDB group aggregation? | Yes, it is possible to rename using aggregation. Let us first create a collection with documents
> db.renameIdDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a1760353decbc2fc927c5")
}
> db.renameIdDemo.insertOne({"StudentName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a1765353decbc2fc927c6")
}
> db.renameIdDemo.insertOne({"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a176b353decbc2fc927c7")
}
Following is the query to display all documents from a collection with the help of find() method
> db.renameIdDemo.find();
This will produce the following output
{ "_id" : ObjectId("5c9a1760353decbc2fc927c5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c9a1765353decbc2fc927c6"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c9a176b353decbc2fc927c7"), "StudentName" : "David" }
Following is the query to rename _id field:
> db.renameIdDemo.aggregate({ $project: {
... _id: 0,
... mainId: "$_id",
... count: 1,
... sum: 1
... }
... }
... );
This will produce the following output. We have renamed _id to mainId;
{ "mainId" : ObjectId("5c9a1760353decbc2fc927c5") }
{ "mainId" : ObjectId("5c9a1765353decbc2fc927c6") }
{ "mainId" : ObjectId("5c9a176b353decbc2fc927c7") } | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "Yes, it is possible to rename using aggregation. Let us first create a collection with documents"
},
{
"code": null,
"e": 1577,
"s": 1159,
"text": "> db.renameIdDemo.insertOne({\"StudentName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9a1760353decbc2fc927c5\")\n}\n> db.renameIdDemo.insertOne({\"StudentName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9a1765353decbc2fc927c6\")\n}\n> db.renameIdDemo.insertOne({\"StudentName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9a176b353decbc2fc927c7\")\n}"
},
{
"code": null,
"e": 1674,
"s": 1577,
"text": "Following is the query to display all documents from a collection with the help of find() method"
},
{
"code": null,
"e": 1700,
"s": 1674,
"text": "> db.renameIdDemo.find();"
},
{
"code": null,
"e": 1739,
"s": 1700,
"text": "This will produce the following output"
},
{
"code": null,
"e": 1962,
"s": 1739,
"text": "{ \"_id\" : ObjectId(\"5c9a1760353decbc2fc927c5\"), \"StudentName\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5c9a1765353decbc2fc927c6\"), \"StudentName\" : \"Robert\" }\n{ \"_id\" : ObjectId(\"5c9a176b353decbc2fc927c7\"), \"StudentName\" : \"David\" }"
},
{
"code": null,
"e": 2006,
"s": 1962,
"text": "Following is the query to rename _id field:"
},
{
"code": null,
"e": 2136,
"s": 2006,
"text": "> db.renameIdDemo.aggregate({ $project: {\n... _id: 0,\n... mainId: \"$_id\",\n... count: 1,\n... sum: 1\n... }\n... }\n... );"
},
{
"code": null,
"e": 2207,
"s": 2136,
"text": "This will produce the following output. We have renamed _id to mainId;"
},
{
"code": null,
"e": 2363,
"s": 2207,
"text": "{ \"mainId\" : ObjectId(\"5c9a1760353decbc2fc927c5\") }\n{ \"mainId\" : ObjectId(\"5c9a1765353decbc2fc927c6\") }\n{ \"mainId\" : ObjectId(\"5c9a176b353decbc2fc927c7\") }"
}
] |
find_element_by_id() driver method - Selenium Python - GeeksforGeeks | 07 Dec, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_id() is discussed in this article. With this strategy, the first element with the id attribute value matching the location will be returned. If no element has a matching id attribute, a NoSuchElementException will be raised.Syntax –
driver.find_element_by_id("id_of_element")
Example – For instance, consider this page source:
html
<html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="password" type="password" /> <input name="continue" type="submit" value="Login" /> </form> </body><html>
Now after you have created a driver, you can grab an element using –
login_form = driver.find_element_by_id('loginForm')
Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its id “gsc-i-id2”. Create a file called run.py to demonstrate find_element_by_id method –
Python3
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_id("gsc-i-id2") # print complete elementprint(element)
Now run using –
Python run.py
First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below. Browser Output –
Terminal Output –
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }
NaveenArora
simmytarika5
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26169,
"s": 26141,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 27059,
"s": 26169,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_id() is discussed in this article. With this strategy, the first element with the id attribute value matching the location will be returned. If no element has a matching id attribute, a NoSuchElementException will be raised.Syntax – "
},
{
"code": null,
"e": 27102,
"s": 27059,
"text": "driver.find_element_by_id(\"id_of_element\")"
},
{
"code": null,
"e": 27155,
"s": 27102,
"text": "Example – For instance, consider this page source: "
},
{
"code": null,
"e": 27160,
"s": 27155,
"text": "html"
},
{
"code": "<html> <body> <form id=\"loginForm\"> <input name=\"username\" type=\"text\" /> <input name=\"password\" type=\"password\" /> <input name=\"continue\" type=\"submit\" value=\"Login\" /> </form> </body><html>",
"e": 27360,
"s": 27160,
"text": null
},
{
"code": null,
"e": 27431,
"s": 27360,
"text": "Now after you have created a driver, you can grab an element using – "
},
{
"code": null,
"e": 27483,
"s": 27431,
"text": "login_form = driver.find_element_by_id('loginForm')"
},
{
"code": null,
"e": 27732,
"s": 27485,
"text": "Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its id “gsc-i-id2”. Create a file called run.py to demonstrate find_element_by_id method – "
},
{
"code": null,
"e": 27740,
"s": 27732,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_id(\"gsc-i-id2\") # print complete elementprint(element)",
"e": 28105,
"s": 27740,
"text": null
},
{
"code": null,
"e": 28123,
"s": 28105,
"text": "Now run using – "
},
{
"code": null,
"e": 28137,
"s": 28123,
"text": "Python run.py"
},
{
"code": null,
"e": 28279,
"s": 28137,
"text": "First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below. Browser Output – "
},
{
"code": null,
"e": 28299,
"s": 28279,
"text": "Terminal Output – "
},
{
"code": null,
"e": 28642,
"s": 28303,
"text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } "
},
{
"code": null,
"e": 28658,
"s": 28646,
"text": "NaveenArora"
},
{
"code": null,
"e": 28671,
"s": 28658,
"text": "simmytarika5"
},
{
"code": null,
"e": 28687,
"s": 28671,
"text": "Python-selenium"
},
{
"code": null,
"e": 28696,
"s": 28687,
"text": "selenium"
},
{
"code": null,
"e": 28703,
"s": 28696,
"text": "Python"
},
{
"code": null,
"e": 28801,
"s": 28703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28819,
"s": 28801,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28854,
"s": 28819,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28886,
"s": 28854,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28908,
"s": 28886,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28950,
"s": 28908,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28980,
"s": 28950,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29006,
"s": 28980,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29050,
"s": 29006,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29079,
"s": 29050,
"text": "*args and **kwargs in Python"
}
] |
Python | Numpy matrix.tobytes() - GeeksforGeeks | 29 May, 2019
With the help of Numpy matrix.tobytes() method, we can find the byte code for the matrix by using the matrix.tobytes() method.
Syntax : matrix.tobytes()Return : Return byte code for matrix
Example #1 :In this example we can see that by using matrix.tobytes() method we are able to find the byte code for the given matrix.
# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]') # applying matrix.tobytes() methodgeek = gfg.tobytes() print(geek)
b’\x04\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00′
Example #2 :
# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]') # applying matrix.tobytes() methodgeek = gfg.tobytes() print(geek)
b’\x04\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00′
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 25800,
"s": 25673,
"text": "With the help of Numpy matrix.tobytes() method, we can find the byte code for the matrix by using the matrix.tobytes() method."
},
{
"code": null,
"e": 25862,
"s": 25800,
"text": "Syntax : matrix.tobytes()Return : Return byte code for matrix"
},
{
"code": null,
"e": 25995,
"s": 25862,
"text": "Example #1 :In this example we can see that by using matrix.tobytes() method we are able to find the byte code for the given matrix."
},
{
"code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]') # applying matrix.tobytes() methodgeek = gfg.tobytes() print(geek)",
"e": 26206,
"s": 25995,
"text": null
},
{
"code": null,
"e": 26338,
"s": 26206,
"text": "b’\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00′"
},
{
"code": null,
"e": 26351,
"s": 26338,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]') # applying matrix.tobytes() methodgeek = gfg.tobytes() print(geek)",
"e": 26577,
"s": 26351,
"text": null
},
{
"code": null,
"e": 26867,
"s": 26577,
"text": "b’\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\t\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00′"
},
{
"code": null,
"e": 26896,
"s": 26867,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 26909,
"s": 26896,
"text": "Python-numpy"
},
{
"code": null,
"e": 26916,
"s": 26909,
"text": "Python"
},
{
"code": null,
"e": 27014,
"s": 26916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27032,
"s": 27014,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27067,
"s": 27032,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27099,
"s": 27067,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27141,
"s": 27099,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27167,
"s": 27141,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27196,
"s": 27167,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27240,
"s": 27196,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27277,
"s": 27240,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27319,
"s": 27277,
"text": "Check if element exists in list in Python"
}
] |
Feature engineering and ensembled models for the top 10 in Kaggle “Housing Prices Competition” | by Gabriel Naya | Towards Data Science | Kaggle1 is one of the most significant online communities of data scientists and machine learners. Within Kaggle, it is common to find competitions, where different users generate prediction models and submit their results to be position according to the score, in the leaderboard.
The competition that supports the online courses that every beginner performs is “Housing Prices Competition for Kaggle Learn Users” .
A global and learning-oriented competence, therefore, the material circulating on the web is profuse, even for those looking well can be found directly with complete codes of excellent models that come very close to 1% on the scoreboard.
This article is base on the code exposed by Sandeep Kumar in Kaggle. This code was our most important starting point in the competition. While this code alone is not enough to reach the top 10, it uses many exciting techniques. To the methods used there, we have added others that have made the difference to position our model in the top 10.
Because every detail counts when you start trying to improve within 1%, you need to be very methodical and thorough in handling data engineering as well as model parameters.
The dataset has 1460 rows of houses with their corresponding 79 features and the target variable: the price of each house. There is also a test set with 1459 other houses.
In this article, we are going to work them unified for the different techniques that we are going to apply and separating them before realizing the final prediction to raise the results.
The workflow with the dataset will then be
a) Import the train_features and test_features data.
b) Save and remove the index (Id) and prepare train_features without the objective variable
c) Create a data frame “features” that joint them
d) Perform data engineering
e) After finished in data engineering work, split again in X_train and X_test the datasets.
f) Make the models, fit, and prediction
g) If we apply any transformation to the target variable (Y), we must invert this transformation over the prediction.
h) Submit results
We are facing a regression exercise, and we must calculate the selling price of each house, of each row of the dataset.
Our objective then is the column SalePrice, first, let’s see its general behavior:
train['SalePrice'].describe()
Let’s now see its practice in any model using it directly, or applying the logarithm to it.
So we see the improvement is significant going down from 12934 to 8458 if we change the model training, taking as a result of the logarithm of the target variable instead of ‘SalePrice’ directly.
“The purpose of the correlation is to examine the direction and strength of the association between two quantitative variables. Thus we will know the intensity of the relationship between them and whether, as the value of one variable increases, the value of the other variable increases or decreases.”2
If you want to know more about the incidence of the correlation of variables and the target variable, you can review this previous issue3 for a detailed analysis.
We are going to create a data frame with the numeric columns and apply the Pandas “corr()” method to them and evaluate the SalePrice target:
data_corr = train.select_dtypes(include=[np.number])data_corr.head()
corr = data_corr.corr()corr.head(20)corr.sort_values(['SalePrice'], ascending=False, inplace=True)corr['SalePrice']
Here we have an ordered list of variables related to the target variable, the increase in model precision may be thought to decrease as we use variables less and less correlated to the target variable.
“... Outliers significantly affect the process of estimating statistics (e.g., the average and standard deviation of a sample), resulting in overestimated or underestimated values. Therefore, the results of data analysis are considerably dependent on the ways in which the missing values and outliers are processed...”4
In the article from which this quotation is token, excellent concepts about the treatment of outliers’ values can be found in-depth.
Let’s take as an example one of the variables that have the highest incidence in its correlation with a price: GrLivArea.
To visualize outliers, we usually use boxplots.
Here an excellent article about the use of boxplot and outliers detection5 , and his main features:
Box plots have box from LQ to UQ, with median marked
They portray a five-number graphical summary of the data Minimum, LQ, Median, UQ, Maximum
Helps us to get an idea on the data distribution
Helps us to identify the outliers easily
25% of the population is below first quartile,
75% of the population is below third quartile
If the box is pushed to one side and some values are far away from the box then it’s a clear indication of outliers
We perform a check on any model, using the entire training set, cutting the Outliers > 4500 and cutting the Outliers > 4000, obtaining the following values
The difference in performance between cutting at 4000 or 4500 does not seem significant; however, the improvement in accuracy when slice GrLivArea registers greater than 4500 is considerable.
In principle and on the training data, it would seem a suitable strategy. Still, it is necessary to look for a balance between what is slice in the entry of the model since it can generate overfitting or take away possibilities of generalization to our model.
If we deploy null values in the data frame before and after these operations with this code, we are going to obtain graphs as in the following image.
import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(12, 6))sns.heatmap(features.isnull())plt.show()
Remember that all null values must be clear before entering a model.
Many of these data we can already know that we are not going to precise them or that the attempt to fill the null values is not viable for them; we apply the drop of the column directly.
features.drop(['Street'], axis=1, inplace=True)features.drop(['Fence'], axis=1, inplace=True)
Everyday use for filling in missing data is to fill it in with “None” or “zero,” depending on the type of data.
Let’s see here two examples to assign the most frequent value (Pandas mode function) or how to apply the amount of the average of the whole column or a cluster of it.
These examples are only for illustrative purposes; you can apply any Pandas function and make the grouping by any attribute that you want to make the cluster. It can also be used to create new features of the “cluster” type.
Example a: Application of the most frequent MSZoning value, grouped for each MSSubClass
features['MSZoning'] = features.groupby('MSSubClass')['MSZoning'].transform(lambda x: x.fillna(x.mode()[0]))
Example b: Application of the mean value of LotFrontage, grouped for each Neighborhood
features['LotFrontage'] = features.groupby('Neighborhood')['LotFrontage'].transform(lambda x: x.fillna(x.median()))
Example c: Apply the most frequent amount to complete your features
features['Exterior1st'] = features['Exterior1st'].fillna(features['Exterior1st'].mode()[0])
Finally, we must make sure that there is no value left with null so we can apply a fill to None or zero depending on the type of column:
objects = [col for col in features.columns if features[col].dtype == "object"]features.update(features[objects].fillna('None'))numerics = [col for col in features.columns if features[col].dtype in np.number]features.update(features[numerics].fillna(0))
You can create new variables to add specific information that helps the model define the data sets, or to simplify the model by creating averages, sums, or Boolean variables.
Each of these variables must be carefully selected, and the impact on the model must be measured to see whether or not it adds quality to the result, and in the case of being used to “simplify” if the loss of eliminated columns does not affect the accuracy of the model.
features['CondTot'] = (features['Condition1'] + features['Condition2']) / 2features['OverTot'] = features['OverallQual'] + features['OverallCond']features['TotalSF'] = features['TotalBsmtSF'] + features['1stFlrSF'] + features['2ndFlrSF']features['haspool'] = features['PoolArea'].apply(lambda x: 1 if x > 0 else 0)
For normally distributed data, the skewness should be about 0. For unimodal continuous distributions, a skewness value > 0 means that there is more weight in the right tail of the distribution. The function skewtest can be used to determine if the skewness value is close enough to 0, statistically speaking.5
We use the Scipy.boxcoxp1 6 that compute the Box-Cox transformation of 1 + x. The Box-Cox transformation computed by boxcox1p is:
y = ((1+x)**lmbda - 1) / lmbda if lmbda != 0log(1+x) if lmbda == 0Returns nan if x < -1. Returns -inf if x == -1 and lmbda < 0.
For getting the lambda value to input in boxcoxp1, we use boxcox_normmax(features[ind)) from Scipy, that Compute optimal Box-Cox transform parameter for input data7
This transformation can be done only on features that have all their positive values; if you need to do a conversion on elements with negative values, see the reference note8 .
from scipy.stats import skewfrom scipy.special import boxcox1pfrom scipy.stats import boxcox_normmaxnumerics = [col for col in features.columns if features[col].dtype in np.number]skew_f = features[numerics].apply(lambda x: skew(x)).sort_values(ascending=False)highest_skew = skew_f[skew_f > 0.5]highest_skew
skew_idx = highest_skew.indexfor ind in skew_idx: features[ind] = boxcox1p(features[ind], boxcox_normmax(features[ind))features[highest_skew.index].head()
When creating variables related to the target variable, it is necessary to do them only on the train data set and then try to take them to the test dataset, since there we do not know the value of the target variable “Y”.
This type of variables with which we have added a significant improvement in the leaderboard of the competition
For example, we can calculate the price per square meter, linked to each neighborhood or class of housing, then we first figure it in the train set:
train['Sqr'] = train['SalePrice'] / train['LotArea']train['Sqr'] = train.groupby('Neighborhood')['Sqr'].transform(lambda x: x.median())
Then we make a dictionary with the prices for each neighborhood:
d = {}for indice_fila, x_train in train.iterrows(): d.update({x_train['Neighborhood']:x_train['Sqr']})
And finally, we created the feature in the test dataset
test['Sqr'] = 0.00for indice, x_test in test.iterrows(): test.loc[test.index == indice ,'Sqr'] = d[x_test['Neighborhood']]
“What one hot encoding does is, it takes a column which has categorical data, which has been label encoded and then splits the column into multiple columns. The numbers are replaced by “1” and “0”, depending on which column has what value... ” 9
Categorizing object features can be very convenient, the discussion of which columns to use to apply OHE to them is broad and their limits diffuse, since each different value within the column will be transformed into a new dimension of the matrix input to the model. Sometimes it may be convenient to create a new feature that groups different values to reduce dimensionality, for example, a set of neighborhoods that have similar characteristics and prices.
Some numeric columns, we may want to categorize them, for which it is convenient to change the type to string since finally, we will apply get_dummies to all the columns of type object.
features['MSSubClass'] = features['MSSubClass'].apply(str)features['MoSold'] = features['MoSold'].astype(str) final_features = pd.get_dummies(features).reset_index(drop=True)
“The dummy variable trap manifests itself directly from one-hot-encoding applied on categorical variables ... size of one-hot vectors is equal to the number of unique values that a categorical column takes up and each such vector contains exactly one ‘1’ in it. This ingests multicollinearity into our dataset ... “10
In other words, when performing the transformation, the set of features of the added OHE is aligned to the target variable, and therefore any column is usually removed. In our model, we have not applied this technique.
Sandeep Kumar’s original work includes at the end of feature engineering and applying get_dummies, a code that looks for those columns that have a lot of zero values (above 99.94%), which are drop.
This technique indirectly mitigates in categorized variables the effect of the dummy variable trap and also avoids including in the model columns that by the impact of the content of the categorization are irrelevant for a model that seeks to extract the main characteristics and generalize them.
overfit = []for i in X.columns: counts = X[i].value_counts() zeros = counts.iloc[0] if zeros / len(X) * 100 > 99.94: overfit.append(i)overfit = list(overfit)overfit.append('MSZoning_C (all)')overfit
X = X.drop(overfit, axis=1).copy()
The regression algorithms have had no problem supporting the columns after categorization, so except in strictly inconvenient cases, it does not seem necessary or even a good idea to remove them. However, this is only one approach; at the end of this article, we will see other approaches to the problem very different, and as much or even more useful.
In this case, then, it is not necessary to reduce the dimensionality of the model since training time with different algorithms is not a problem, and brute force does not seem a bad strategy.
“Ensemble models give us excellent performance and work in a wide variety of problems. They’re easier to train than other types of techniques, requiring less data with better results. In machine learning, ensemble models are the norm. Even if you aren’t using them, your competitors are ... Ensemble models are comprised of several weak models that aren’t so great themselves, known as weak learners. When you combine them, they fill in each other’s weaknesses and render better performance than they would when deployed alone.”11
The competition metric is the Mean Absolute Error (MAE).
For the initial measurement, RMSE and CV_RMSE used.
Because the CV_RMSE is negative, to apply the square root, it is necessary to flip it.12
def rmsle(y, y_pred): return np.sqrt(mean_squared_error(y, y_pred))def cv_rmse(model): rmse = np.sqrt(-cross_val_score(model, X, y, scoring="neg_mean_squared_error", cv=kfolds)) return rmse
It is an example of one of the original models used by Sandeep Kumar, where we can see lots of hyperparameters uses:
gbr = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,max_depth=4, max_features='sqrt', min_samples_leaf=15, min_samples_split=10, loss='huber', random_state=42)
In the same operation that we carried out for the GBR model, we can carry it out with other different regression models. Then in a function, we assign them an incidence coefficient on the total value, in such a way that the ratios add up to 1.
Sandeep Kumar blend models:
def blend_models_predict(X): return ((0.1 * elastic_model_full_data.predict(X)) + \(0.1 * lasso_model_full_data.predict(X)) + \(0.1 * ridge_model_full_data.predict(X)) + \(0.1 * svr_model_full_data.predict(X)) + \(0.1 * gbr_model_full_data.predict(X)) + \(0.15 * xgb_model_full_data.predict(X)) + \(0.1 * lgb_model_full_data.predict(X)) + \(0.25 * stack_gen_model.predict(np.array(X))))
Mi blend model:
def blend_models_predict(X=X): return ((0.10 * elastic_model_full_data.predict(X)) +(0.05 * lasso_model_full_data.predict(X)) +(0.05 * ridge_model_full_data.predict(X)) +(0.05 * svr_model_full_data.predict(X)) +(0.20 * gbr_model_full_data.predict(X)) +(0.20 * xgb_model_full_data.predict(X)) +(0.10 * lgb_model_full_data.predict(X)) +(0.25 * stack_gen_model.predict(np.array(X))))
We were able to use other models, such as linear regressor, tree regressors, etc. The importance assigned to each model depends on the confidence we have in the algorithm on the test dataset, sometimes algorithms such as GBR, XGB, or LGB work very well in the fit but fall by overfitting to use them in the test set. On the other hand, models like SVR or RIDGE tend to have less precision but are more stable.
When we managed to place our model in the top 10 of the world competition and to know that our knowledge was very scarce, with the desire to go for more but feeling on a plateau, I contacted Adam Suwik who was in the #3 at the time, and still remains there in the top positions:
Very kindly Adam agreed to share the approach of his model in a very illustrative post.
We transcribe here some of the most significant passages for this article:
“... This is no secret knowledge, only simple logical thinking (although specialist knowledge in the subject would be very helpful too).
Adjusting the data to the model — most likely Linear Regression will be the # 1 choice. Unfortunately, most of the data does not make much sense and may adversely affect the result. For example, quality — it is not the case that excellent quality of a small house and a large villa has the same value — it should rather be replaced by “size in square feet in exellent quality”. And it seems to me that most of the data should be prepared in such a way — combined with the size of a plot, house area, basement area, pool size, etc.
Combining data / simplifying the model — that’s what I use a lot. The world is not that complicated. In this case, it seems to me that 3 features would be enough — how big the house is?, how nice it is? how comfortable is it?, maybe a few additional ones like a swimming pool, an additional garage space, etc. ...
Dropping data — I use it a lot too. If I do not see value or think that the information is contained elsewhere, or if I have somehow engineered data, I drop whatever I can. Some expertise would be pretty useful here, but using just common sense, much of the data that seems to have an impact is really secondary. Nobody builds a luxury home on cheap foundations and viceversa ...
Clusters — not always the same rules apply to entire populations, if I am able to isolate a large group of similar cases, I will build a separate model for them. From life experience — if you look at the price per square foot you will notice that for smaller apartments it is definitely bigger.
And I probably could describe a few other things, but it all comes down to one thing — analyze all the data carefully and think about how to engineer them to fit the model you use. I believe in one principle: “garbage in, garbage out”. What quality of data you provide, the quality of result you will get...
NaN’s. Unfortunately, the answer is just as above — there are no secrets — do whatever seems to make sense. I like “0”, “none”, I really like my own predictions, I hate the average, it’s like admitting to the lack of any idea and just minimizing cost of assumed mistakes...”
It is another approach, and there are many more approaches to the web. To be in 1% of any competition is in itself a good enough model and a sign that we are on the right way.
We have seen how important it is to start a job supported in the preliminary work that others have shared, in this case, the transfer learning of the Sandeep Kumar model. Thanks him!
This previous transfer learning gave us a floor and essential knowledge from which to start, much more elaborated and refined than the experience that a rookie takes from online courses.
Then, after many hours of effort and systematic tests, we saw the impact of each technique on the different variables to make decisions about the engineering features and the ensemble of models.
One day I got that idea that makes the difference, being distracted the head still thinking, the idea was to calculate the value of square feet based on a given concept, and the satisfaction of having reached that top ten was an incredible moment.
The objective of this Kaggle competition is to learn
This post aimed to transmit the techniques that you can use if you are stuck until the mud in the game as I was a few months ago hopefully, help you get on an exact path towards improving your model, or maybe help you light that little lamp that makes the difference.
I will be grateful for comments and reports if something could be doing better.
[1] Kaggle is an online community of data scientists and machine learners, owned by Google LLC . Kaggle allows users to find and publish data sets, explore and build models in a web-based data-science environment, work with other data scientists and machine learning engineers, and enter competitions to solve data science challenges. Kaggle got its start by offering machine learning competitions and now also offers a public data platform, a cloud-based workbench for data science, and short form AI education. On 8 March 2017, Google announced that they were acquiring Kaggle.
[2] https://www.google.com/url?sa=t&source=web&rct=j&url=https://personal.us.es/vararey/adatos2/correlacion.pdf&ved=2ahUKEwiaytLbhqnlAhUGLLkGHeL2B24QFjAMegQIBxAB&usg=AOvVaw1mijaxh5F0qXIXMpeadD5j
[3] Incidence of correlation and time features in a regression model
[4] Statistical data preparation: management of missing values and outliers
“... There are basically three methods for treating outliers in a data set. One method is to remove outliers as a means of trimming the data set. Another method involves replacing the values of outliers or reducing the influence of outliers through outlier weight adjustments. The third method is used to estimate the values of outliers using robust techniques.
Trimming: Under this approach, a data set that excludes outliers is analyzed. The trimmed estimators such as mean decrease the variance in the data and cause a bias based on under- or overestimation. Given that the outliers are also observed values, excluding them from the analysis makes this approach inadequate for the treatment of outliers.
Winsorization: This approach involves modifying the weights of outliers or replacing the values being tested for outliers with expected values. The weight modification method allows weight modification without discarding or replacing the values of outliers, limiting the influence of the outliers. The value modification method allows the replacement of the values of outliers with the largest or second smallest value in observations excluding outliers.
Robust estimation method: When the nature of the population distributions is known, this approach is considered appropriate because it produces estimators robust to outliers, and estimators are consistent. In the recent years, many studies have proposed a variety of statistical models for robust estimation; however, their applications are sluggish due to complicated methodological aspects. “
[5] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html
[6] https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.boxcox1p.html
[7]https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.boxcox_normmax.html?highlight=normmax#scipy.stats.boxcox_normmax
[8] https://www.kaggle.com/rtatman/data-cleaning-challenge-scale-and-normalize-data
“One thing you can do is add a fixed value that’s just bigger than your smallest negative to make all your value normal. Another normalization method is the Johnson Transformation, which can handle negative values.
[9] https://towardsdatascience.com/choosing-the-right-encoding-method-label-vs-onehot-encoder-a4434493149b
[10] https://towardsdatascience.com/one-hot-encoding-multicollinearity-and-the-dummy-variable-trap-b5840be3c41a
[11] https://medium.com/@ODSC/ensemble-models-demystified-c871d5ee7793
[12] https://github.com/scikit-learn/scikit-learn/issues/2439
The Mean Square Error returned by sklearn.cross_validation.cross_val_score is always a negative. While being a designed decision so that the output of this function can be used for maximization given some hyperparameters, it’s extremely confusing when using cross_val_score directly. At least I asked myself how a the mean of a square can possibly be negative and thought that cross_val_score was not working correctly or did not use the supplied metric. Only after digging in the sklearn source code I realized that the sign was flipped.
This behavior is mentioned in make_scorer in scorer.py, however it’s not mentioned in cross_val_score and I think it should be, because otherwise it makes people think that cross_val_score is not working correctly | [
{
"code": null,
"e": 453,
"s": 171,
"text": "Kaggle1 is one of the most significant online communities of data scientists and machine learners. Within Kaggle, it is common to find competitions, where different users generate prediction models and submit their results to be position according to the score, in the leaderboard."
},
{
"code": null,
"e": 588,
"s": 453,
"text": "The competition that supports the online courses that every beginner performs is “Housing Prices Competition for Kaggle Learn Users” ."
},
{
"code": null,
"e": 826,
"s": 588,
"text": "A global and learning-oriented competence, therefore, the material circulating on the web is profuse, even for those looking well can be found directly with complete codes of excellent models that come very close to 1% on the scoreboard."
},
{
"code": null,
"e": 1169,
"s": 826,
"text": "This article is base on the code exposed by Sandeep Kumar in Kaggle. This code was our most important starting point in the competition. While this code alone is not enough to reach the top 10, it uses many exciting techniques. To the methods used there, we have added others that have made the difference to position our model in the top 10."
},
{
"code": null,
"e": 1343,
"s": 1169,
"text": "Because every detail counts when you start trying to improve within 1%, you need to be very methodical and thorough in handling data engineering as well as model parameters."
},
{
"code": null,
"e": 1515,
"s": 1343,
"text": "The dataset has 1460 rows of houses with their corresponding 79 features and the target variable: the price of each house. There is also a test set with 1459 other houses."
},
{
"code": null,
"e": 1702,
"s": 1515,
"text": "In this article, we are going to work them unified for the different techniques that we are going to apply and separating them before realizing the final prediction to raise the results."
},
{
"code": null,
"e": 1745,
"s": 1702,
"text": "The workflow with the dataset will then be"
},
{
"code": null,
"e": 1798,
"s": 1745,
"text": "a) Import the train_features and test_features data."
},
{
"code": null,
"e": 1890,
"s": 1798,
"text": "b) Save and remove the index (Id) and prepare train_features without the objective variable"
},
{
"code": null,
"e": 1940,
"s": 1890,
"text": "c) Create a data frame “features” that joint them"
},
{
"code": null,
"e": 1968,
"s": 1940,
"text": "d) Perform data engineering"
},
{
"code": null,
"e": 2060,
"s": 1968,
"text": "e) After finished in data engineering work, split again in X_train and X_test the datasets."
},
{
"code": null,
"e": 2100,
"s": 2060,
"text": "f) Make the models, fit, and prediction"
},
{
"code": null,
"e": 2218,
"s": 2100,
"text": "g) If we apply any transformation to the target variable (Y), we must invert this transformation over the prediction."
},
{
"code": null,
"e": 2236,
"s": 2218,
"text": "h) Submit results"
},
{
"code": null,
"e": 2356,
"s": 2236,
"text": "We are facing a regression exercise, and we must calculate the selling price of each house, of each row of the dataset."
},
{
"code": null,
"e": 2439,
"s": 2356,
"text": "Our objective then is the column SalePrice, first, let’s see its general behavior:"
},
{
"code": null,
"e": 2469,
"s": 2439,
"text": "train['SalePrice'].describe()"
},
{
"code": null,
"e": 2561,
"s": 2469,
"text": "Let’s now see its practice in any model using it directly, or applying the logarithm to it."
},
{
"code": null,
"e": 2757,
"s": 2561,
"text": "So we see the improvement is significant going down from 12934 to 8458 if we change the model training, taking as a result of the logarithm of the target variable instead of ‘SalePrice’ directly."
},
{
"code": null,
"e": 3061,
"s": 2757,
"text": "“The purpose of the correlation is to examine the direction and strength of the association between two quantitative variables. Thus we will know the intensity of the relationship between them and whether, as the value of one variable increases, the value of the other variable increases or decreases.”2"
},
{
"code": null,
"e": 3224,
"s": 3061,
"text": "If you want to know more about the incidence of the correlation of variables and the target variable, you can review this previous issue3 for a detailed analysis."
},
{
"code": null,
"e": 3365,
"s": 3224,
"text": "We are going to create a data frame with the numeric columns and apply the Pandas “corr()” method to them and evaluate the SalePrice target:"
},
{
"code": null,
"e": 3434,
"s": 3365,
"text": "data_corr = train.select_dtypes(include=[np.number])data_corr.head()"
},
{
"code": null,
"e": 3550,
"s": 3434,
"text": "corr = data_corr.corr()corr.head(20)corr.sort_values(['SalePrice'], ascending=False, inplace=True)corr['SalePrice']"
},
{
"code": null,
"e": 3752,
"s": 3550,
"text": "Here we have an ordered list of variables related to the target variable, the increase in model precision may be thought to decrease as we use variables less and less correlated to the target variable."
},
{
"code": null,
"e": 4072,
"s": 3752,
"text": "“... Outliers significantly affect the process of estimating statistics (e.g., the average and standard deviation of a sample), resulting in overestimated or underestimated values. Therefore, the results of data analysis are considerably dependent on the ways in which the missing values and outliers are processed...”4"
},
{
"code": null,
"e": 4205,
"s": 4072,
"text": "In the article from which this quotation is token, excellent concepts about the treatment of outliers’ values can be found in-depth."
},
{
"code": null,
"e": 4327,
"s": 4205,
"text": "Let’s take as an example one of the variables that have the highest incidence in its correlation with a price: GrLivArea."
},
{
"code": null,
"e": 4375,
"s": 4327,
"text": "To visualize outliers, we usually use boxplots."
},
{
"code": null,
"e": 4475,
"s": 4375,
"text": "Here an excellent article about the use of boxplot and outliers detection5 , and his main features:"
},
{
"code": null,
"e": 4528,
"s": 4475,
"text": "Box plots have box from LQ to UQ, with median marked"
},
{
"code": null,
"e": 4618,
"s": 4528,
"text": "They portray a five-number graphical summary of the data Minimum, LQ, Median, UQ, Maximum"
},
{
"code": null,
"e": 4667,
"s": 4618,
"text": "Helps us to get an idea on the data distribution"
},
{
"code": null,
"e": 4708,
"s": 4667,
"text": "Helps us to identify the outliers easily"
},
{
"code": null,
"e": 4755,
"s": 4708,
"text": "25% of the population is below first quartile,"
},
{
"code": null,
"e": 4801,
"s": 4755,
"text": "75% of the population is below third quartile"
},
{
"code": null,
"e": 4917,
"s": 4801,
"text": "If the box is pushed to one side and some values are far away from the box then it’s a clear indication of outliers"
},
{
"code": null,
"e": 5073,
"s": 4917,
"text": "We perform a check on any model, using the entire training set, cutting the Outliers > 4500 and cutting the Outliers > 4000, obtaining the following values"
},
{
"code": null,
"e": 5265,
"s": 5073,
"text": "The difference in performance between cutting at 4000 or 4500 does not seem significant; however, the improvement in accuracy when slice GrLivArea registers greater than 4500 is considerable."
},
{
"code": null,
"e": 5525,
"s": 5265,
"text": "In principle and on the training data, it would seem a suitable strategy. Still, it is necessary to look for a balance between what is slice in the entry of the model since it can generate overfitting or take away possibilities of generalization to our model."
},
{
"code": null,
"e": 5675,
"s": 5525,
"text": "If we deploy null values in the data frame before and after these operations with this code, we are going to obtain graphs as in the following image."
},
{
"code": null,
"e": 5795,
"s": 5675,
"text": "import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(12, 6))sns.heatmap(features.isnull())plt.show()"
},
{
"code": null,
"e": 5864,
"s": 5795,
"text": "Remember that all null values must be clear before entering a model."
},
{
"code": null,
"e": 6051,
"s": 5864,
"text": "Many of these data we can already know that we are not going to precise them or that the attempt to fill the null values is not viable for them; we apply the drop of the column directly."
},
{
"code": null,
"e": 6145,
"s": 6051,
"text": "features.drop(['Street'], axis=1, inplace=True)features.drop(['Fence'], axis=1, inplace=True)"
},
{
"code": null,
"e": 6257,
"s": 6145,
"text": "Everyday use for filling in missing data is to fill it in with “None” or “zero,” depending on the type of data."
},
{
"code": null,
"e": 6424,
"s": 6257,
"text": "Let’s see here two examples to assign the most frequent value (Pandas mode function) or how to apply the amount of the average of the whole column or a cluster of it."
},
{
"code": null,
"e": 6649,
"s": 6424,
"text": "These examples are only for illustrative purposes; you can apply any Pandas function and make the grouping by any attribute that you want to make the cluster. It can also be used to create new features of the “cluster” type."
},
{
"code": null,
"e": 6737,
"s": 6649,
"text": "Example a: Application of the most frequent MSZoning value, grouped for each MSSubClass"
},
{
"code": null,
"e": 6846,
"s": 6737,
"text": "features['MSZoning'] = features.groupby('MSSubClass')['MSZoning'].transform(lambda x: x.fillna(x.mode()[0]))"
},
{
"code": null,
"e": 6933,
"s": 6846,
"text": "Example b: Application of the mean value of LotFrontage, grouped for each Neighborhood"
},
{
"code": null,
"e": 7049,
"s": 6933,
"text": "features['LotFrontage'] = features.groupby('Neighborhood')['LotFrontage'].transform(lambda x: x.fillna(x.median()))"
},
{
"code": null,
"e": 7117,
"s": 7049,
"text": "Example c: Apply the most frequent amount to complete your features"
},
{
"code": null,
"e": 7209,
"s": 7117,
"text": "features['Exterior1st'] = features['Exterior1st'].fillna(features['Exterior1st'].mode()[0])"
},
{
"code": null,
"e": 7346,
"s": 7209,
"text": "Finally, we must make sure that there is no value left with null so we can apply a fill to None or zero depending on the type of column:"
},
{
"code": null,
"e": 7599,
"s": 7346,
"text": "objects = [col for col in features.columns if features[col].dtype == \"object\"]features.update(features[objects].fillna('None'))numerics = [col for col in features.columns if features[col].dtype in np.number]features.update(features[numerics].fillna(0))"
},
{
"code": null,
"e": 7774,
"s": 7599,
"text": "You can create new variables to add specific information that helps the model define the data sets, or to simplify the model by creating averages, sums, or Boolean variables."
},
{
"code": null,
"e": 8045,
"s": 7774,
"text": "Each of these variables must be carefully selected, and the impact on the model must be measured to see whether or not it adds quality to the result, and in the case of being used to “simplify” if the loss of eliminated columns does not affect the accuracy of the model."
},
{
"code": null,
"e": 8360,
"s": 8045,
"text": "features['CondTot'] = (features['Condition1'] + features['Condition2']) / 2features['OverTot'] = features['OverallQual'] + features['OverallCond']features['TotalSF'] = features['TotalBsmtSF'] + features['1stFlrSF'] + features['2ndFlrSF']features['haspool'] = features['PoolArea'].apply(lambda x: 1 if x > 0 else 0)"
},
{
"code": null,
"e": 8670,
"s": 8360,
"text": "For normally distributed data, the skewness should be about 0. For unimodal continuous distributions, a skewness value > 0 means that there is more weight in the right tail of the distribution. The function skewtest can be used to determine if the skewness value is close enough to 0, statistically speaking.5"
},
{
"code": null,
"e": 8800,
"s": 8670,
"text": "We use the Scipy.boxcoxp1 6 that compute the Box-Cox transformation of 1 + x. The Box-Cox transformation computed by boxcox1p is:"
},
{
"code": null,
"e": 8952,
"s": 8800,
"text": "y = ((1+x)**lmbda - 1) / lmbda if lmbda != 0log(1+x) if lmbda == 0Returns nan if x < -1. Returns -inf if x == -1 and lmbda < 0."
},
{
"code": null,
"e": 9117,
"s": 8952,
"text": "For getting the lambda value to input in boxcoxp1, we use boxcox_normmax(features[ind)) from Scipy, that Compute optimal Box-Cox transform parameter for input data7"
},
{
"code": null,
"e": 9294,
"s": 9117,
"text": "This transformation can be done only on features that have all their positive values; if you need to do a conversion on elements with negative values, see the reference note8 ."
},
{
"code": null,
"e": 9604,
"s": 9294,
"text": "from scipy.stats import skewfrom scipy.special import boxcox1pfrom scipy.stats import boxcox_normmaxnumerics = [col for col in features.columns if features[col].dtype in np.number]skew_f = features[numerics].apply(lambda x: skew(x)).sort_values(ascending=False)highest_skew = skew_f[skew_f > 0.5]highest_skew"
},
{
"code": null,
"e": 9762,
"s": 9604,
"text": "skew_idx = highest_skew.indexfor ind in skew_idx: features[ind] = boxcox1p(features[ind], boxcox_normmax(features[ind))features[highest_skew.index].head()"
},
{
"code": null,
"e": 9984,
"s": 9762,
"text": "When creating variables related to the target variable, it is necessary to do them only on the train data set and then try to take them to the test dataset, since there we do not know the value of the target variable “Y”."
},
{
"code": null,
"e": 10096,
"s": 9984,
"text": "This type of variables with which we have added a significant improvement in the leaderboard of the competition"
},
{
"code": null,
"e": 10245,
"s": 10096,
"text": "For example, we can calculate the price per square meter, linked to each neighborhood or class of housing, then we first figure it in the train set:"
},
{
"code": null,
"e": 10381,
"s": 10245,
"text": "train['Sqr'] = train['SalePrice'] / train['LotArea']train['Sqr'] = train.groupby('Neighborhood')['Sqr'].transform(lambda x: x.median())"
},
{
"code": null,
"e": 10446,
"s": 10381,
"text": "Then we make a dictionary with the prices for each neighborhood:"
},
{
"code": null,
"e": 10552,
"s": 10446,
"text": "d = {}for indice_fila, x_train in train.iterrows(): d.update({x_train['Neighborhood']:x_train['Sqr']})"
},
{
"code": null,
"e": 10608,
"s": 10552,
"text": "And finally, we created the feature in the test dataset"
},
{
"code": null,
"e": 10734,
"s": 10608,
"text": "test['Sqr'] = 0.00for indice, x_test in test.iterrows(): test.loc[test.index == indice ,'Sqr'] = d[x_test['Neighborhood']]"
},
{
"code": null,
"e": 10980,
"s": 10734,
"text": "“What one hot encoding does is, it takes a column which has categorical data, which has been label encoded and then splits the column into multiple columns. The numbers are replaced by “1” and “0”, depending on which column has what value... ” 9"
},
{
"code": null,
"e": 11440,
"s": 10980,
"text": "Categorizing object features can be very convenient, the discussion of which columns to use to apply OHE to them is broad and their limits diffuse, since each different value within the column will be transformed into a new dimension of the matrix input to the model. Sometimes it may be convenient to create a new feature that groups different values to reduce dimensionality, for example, a set of neighborhoods that have similar characteristics and prices."
},
{
"code": null,
"e": 11626,
"s": 11440,
"text": "Some numeric columns, we may want to categorize them, for which it is convenient to change the type to string since finally, we will apply get_dummies to all the columns of type object."
},
{
"code": null,
"e": 11801,
"s": 11626,
"text": "features['MSSubClass'] = features['MSSubClass'].apply(str)features['MoSold'] = features['MoSold'].astype(str) final_features = pd.get_dummies(features).reset_index(drop=True)"
},
{
"code": null,
"e": 12119,
"s": 11801,
"text": "“The dummy variable trap manifests itself directly from one-hot-encoding applied on categorical variables ... size of one-hot vectors is equal to the number of unique values that a categorical column takes up and each such vector contains exactly one ‘1’ in it. This ingests multicollinearity into our dataset ... “10"
},
{
"code": null,
"e": 12338,
"s": 12119,
"text": "In other words, when performing the transformation, the set of features of the added OHE is aligned to the target variable, and therefore any column is usually removed. In our model, we have not applied this technique."
},
{
"code": null,
"e": 12536,
"s": 12338,
"text": "Sandeep Kumar’s original work includes at the end of feature engineering and applying get_dummies, a code that looks for those columns that have a lot of zero values (above 99.94%), which are drop."
},
{
"code": null,
"e": 12833,
"s": 12536,
"text": "This technique indirectly mitigates in categorized variables the effect of the dummy variable trap and also avoids including in the model columns that by the impact of the content of the categorization are irrelevant for a model that seeks to extract the main characteristics and generalize them."
},
{
"code": null,
"e": 13047,
"s": 12833,
"text": "overfit = []for i in X.columns: counts = X[i].value_counts() zeros = counts.iloc[0] if zeros / len(X) * 100 > 99.94: overfit.append(i)overfit = list(overfit)overfit.append('MSZoning_C (all)')overfit"
},
{
"code": null,
"e": 13082,
"s": 13047,
"text": "X = X.drop(overfit, axis=1).copy()"
},
{
"code": null,
"e": 13435,
"s": 13082,
"text": "The regression algorithms have had no problem supporting the columns after categorization, so except in strictly inconvenient cases, it does not seem necessary or even a good idea to remove them. However, this is only one approach; at the end of this article, we will see other approaches to the problem very different, and as much or even more useful."
},
{
"code": null,
"e": 13627,
"s": 13435,
"text": "In this case, then, it is not necessary to reduce the dimensionality of the model since training time with different algorithms is not a problem, and brute force does not seem a bad strategy."
},
{
"code": null,
"e": 14158,
"s": 13627,
"text": "“Ensemble models give us excellent performance and work in a wide variety of problems. They’re easier to train than other types of techniques, requiring less data with better results. In machine learning, ensemble models are the norm. Even if you aren’t using them, your competitors are ... Ensemble models are comprised of several weak models that aren’t so great themselves, known as weak learners. When you combine them, they fill in each other’s weaknesses and render better performance than they would when deployed alone.”11"
},
{
"code": null,
"e": 14215,
"s": 14158,
"text": "The competition metric is the Mean Absolute Error (MAE)."
},
{
"code": null,
"e": 14267,
"s": 14215,
"text": "For the initial measurement, RMSE and CV_RMSE used."
},
{
"code": null,
"e": 14356,
"s": 14267,
"text": "Because the CV_RMSE is negative, to apply the square root, it is necessary to flip it.12"
},
{
"code": null,
"e": 14555,
"s": 14356,
"text": "def rmsle(y, y_pred): return np.sqrt(mean_squared_error(y, y_pred))def cv_rmse(model): rmse = np.sqrt(-cross_val_score(model, X, y, scoring=\"neg_mean_squared_error\", cv=kfolds)) return rmse"
},
{
"code": null,
"e": 14672,
"s": 14555,
"text": "It is an example of one of the original models used by Sandeep Kumar, where we can see lots of hyperparameters uses:"
},
{
"code": null,
"e": 14850,
"s": 14672,
"text": "gbr = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,max_depth=4, max_features='sqrt', min_samples_leaf=15, min_samples_split=10, loss='huber', random_state=42)"
},
{
"code": null,
"e": 15094,
"s": 14850,
"text": "In the same operation that we carried out for the GBR model, we can carry it out with other different regression models. Then in a function, we assign them an incidence coefficient on the total value, in such a way that the ratios add up to 1."
},
{
"code": null,
"e": 15122,
"s": 15094,
"text": "Sandeep Kumar blend models:"
},
{
"code": null,
"e": 15511,
"s": 15122,
"text": "def blend_models_predict(X): return ((0.1 * elastic_model_full_data.predict(X)) + \\(0.1 * lasso_model_full_data.predict(X)) + \\(0.1 * ridge_model_full_data.predict(X)) + \\(0.1 * svr_model_full_data.predict(X)) + \\(0.1 * gbr_model_full_data.predict(X)) + \\(0.15 * xgb_model_full_data.predict(X)) + \\(0.1 * lgb_model_full_data.predict(X)) + \\(0.25 * stack_gen_model.predict(np.array(X))))"
},
{
"code": null,
"e": 15527,
"s": 15511,
"text": "Mi blend model:"
},
{
"code": null,
"e": 15911,
"s": 15527,
"text": "def blend_models_predict(X=X): return ((0.10 * elastic_model_full_data.predict(X)) +(0.05 * lasso_model_full_data.predict(X)) +(0.05 * ridge_model_full_data.predict(X)) +(0.05 * svr_model_full_data.predict(X)) +(0.20 * gbr_model_full_data.predict(X)) +(0.20 * xgb_model_full_data.predict(X)) +(0.10 * lgb_model_full_data.predict(X)) +(0.25 * stack_gen_model.predict(np.array(X))))"
},
{
"code": null,
"e": 16321,
"s": 15911,
"text": "We were able to use other models, such as linear regressor, tree regressors, etc. The importance assigned to each model depends on the confidence we have in the algorithm on the test dataset, sometimes algorithms such as GBR, XGB, or LGB work very well in the fit but fall by overfitting to use them in the test set. On the other hand, models like SVR or RIDGE tend to have less precision but are more stable."
},
{
"code": null,
"e": 16600,
"s": 16321,
"text": "When we managed to place our model in the top 10 of the world competition and to know that our knowledge was very scarce, with the desire to go for more but feeling on a plateau, I contacted Adam Suwik who was in the #3 at the time, and still remains there in the top positions:"
},
{
"code": null,
"e": 16688,
"s": 16600,
"text": "Very kindly Adam agreed to share the approach of his model in a very illustrative post."
},
{
"code": null,
"e": 16763,
"s": 16688,
"text": "We transcribe here some of the most significant passages for this article:"
},
{
"code": null,
"e": 16900,
"s": 16763,
"text": "“... This is no secret knowledge, only simple logical thinking (although specialist knowledge in the subject would be very helpful too)."
},
{
"code": null,
"e": 17431,
"s": 16900,
"text": "Adjusting the data to the model — most likely Linear Regression will be the # 1 choice. Unfortunately, most of the data does not make much sense and may adversely affect the result. For example, quality — it is not the case that excellent quality of a small house and a large villa has the same value — it should rather be replaced by “size in square feet in exellent quality”. And it seems to me that most of the data should be prepared in such a way — combined with the size of a plot, house area, basement area, pool size, etc."
},
{
"code": null,
"e": 17745,
"s": 17431,
"text": "Combining data / simplifying the model — that’s what I use a lot. The world is not that complicated. In this case, it seems to me that 3 features would be enough — how big the house is?, how nice it is? how comfortable is it?, maybe a few additional ones like a swimming pool, an additional garage space, etc. ..."
},
{
"code": null,
"e": 18125,
"s": 17745,
"text": "Dropping data — I use it a lot too. If I do not see value or think that the information is contained elsewhere, or if I have somehow engineered data, I drop whatever I can. Some expertise would be pretty useful here, but using just common sense, much of the data that seems to have an impact is really secondary. Nobody builds a luxury home on cheap foundations and viceversa ..."
},
{
"code": null,
"e": 18420,
"s": 18125,
"text": "Clusters — not always the same rules apply to entire populations, if I am able to isolate a large group of similar cases, I will build a separate model for them. From life experience — if you look at the price per square foot you will notice that for smaller apartments it is definitely bigger."
},
{
"code": null,
"e": 18728,
"s": 18420,
"text": "And I probably could describe a few other things, but it all comes down to one thing — analyze all the data carefully and think about how to engineer them to fit the model you use. I believe in one principle: “garbage in, garbage out”. What quality of data you provide, the quality of result you will get..."
},
{
"code": null,
"e": 19003,
"s": 18728,
"text": "NaN’s. Unfortunately, the answer is just as above — there are no secrets — do whatever seems to make sense. I like “0”, “none”, I really like my own predictions, I hate the average, it’s like admitting to the lack of any idea and just minimizing cost of assumed mistakes...”"
},
{
"code": null,
"e": 19179,
"s": 19003,
"text": "It is another approach, and there are many more approaches to the web. To be in 1% of any competition is in itself a good enough model and a sign that we are on the right way."
},
{
"code": null,
"e": 19362,
"s": 19179,
"text": "We have seen how important it is to start a job supported in the preliminary work that others have shared, in this case, the transfer learning of the Sandeep Kumar model. Thanks him!"
},
{
"code": null,
"e": 19549,
"s": 19362,
"text": "This previous transfer learning gave us a floor and essential knowledge from which to start, much more elaborated and refined than the experience that a rookie takes from online courses."
},
{
"code": null,
"e": 19744,
"s": 19549,
"text": "Then, after many hours of effort and systematic tests, we saw the impact of each technique on the different variables to make decisions about the engineering features and the ensemble of models."
},
{
"code": null,
"e": 19992,
"s": 19744,
"text": "One day I got that idea that makes the difference, being distracted the head still thinking, the idea was to calculate the value of square feet based on a given concept, and the satisfaction of having reached that top ten was an incredible moment."
},
{
"code": null,
"e": 20045,
"s": 19992,
"text": "The objective of this Kaggle competition is to learn"
},
{
"code": null,
"e": 20313,
"s": 20045,
"text": "This post aimed to transmit the techniques that you can use if you are stuck until the mud in the game as I was a few months ago hopefully, help you get on an exact path towards improving your model, or maybe help you light that little lamp that makes the difference."
},
{
"code": null,
"e": 20393,
"s": 20313,
"text": "I will be grateful for comments and reports if something could be doing better."
},
{
"code": null,
"e": 20973,
"s": 20393,
"text": "[1] Kaggle is an online community of data scientists and machine learners, owned by Google LLC . Kaggle allows users to find and publish data sets, explore and build models in a web-based data-science environment, work with other data scientists and machine learning engineers, and enter competitions to solve data science challenges. Kaggle got its start by offering machine learning competitions and now also offers a public data platform, a cloud-based workbench for data science, and short form AI education. On 8 March 2017, Google announced that they were acquiring Kaggle."
},
{
"code": null,
"e": 21168,
"s": 20973,
"text": "[2] https://www.google.com/url?sa=t&source=web&rct=j&url=https://personal.us.es/vararey/adatos2/correlacion.pdf&ved=2ahUKEwiaytLbhqnlAhUGLLkGHeL2B24QFjAMegQIBxAB&usg=AOvVaw1mijaxh5F0qXIXMpeadD5j"
},
{
"code": null,
"e": 21237,
"s": 21168,
"text": "[3] Incidence of correlation and time features in a regression model"
},
{
"code": null,
"e": 21313,
"s": 21237,
"text": "[4] Statistical data preparation: management of missing values and outliers"
},
{
"code": null,
"e": 21675,
"s": 21313,
"text": "“... There are basically three methods for treating outliers in a data set. One method is to remove outliers as a means of trimming the data set. Another method involves replacing the values of outliers or reducing the influence of outliers through outlier weight adjustments. The third method is used to estimate the values of outliers using robust techniques."
},
{
"code": null,
"e": 22020,
"s": 21675,
"text": "Trimming: Under this approach, a data set that excludes outliers is analyzed. The trimmed estimators such as mean decrease the variance in the data and cause a bias based on under- or overestimation. Given that the outliers are also observed values, excluding them from the analysis makes this approach inadequate for the treatment of outliers."
},
{
"code": null,
"e": 22475,
"s": 22020,
"text": "Winsorization: This approach involves modifying the weights of outliers or replacing the values being tested for outliers with expected values. The weight modification method allows weight modification without discarding or replacing the values of outliers, limiting the influence of the outliers. The value modification method allows the replacement of the values of outliers with the largest or second smallest value in observations excluding outliers."
},
{
"code": null,
"e": 22870,
"s": 22475,
"text": "Robust estimation method: When the nature of the population distributions is known, this approach is considered appropriate because it produces estimators robust to outliers, and estimators are consistent. In the recent years, many studies have proposed a variety of statistical models for robust estimation; however, their applications are sluggish due to complicated methodological aspects. “"
},
{
"code": null,
"e": 22949,
"s": 22870,
"text": "[5] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html"
},
{
"code": null,
"e": 23034,
"s": 22949,
"text": "[6] https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.boxcox1p.html"
},
{
"code": null,
"e": 23167,
"s": 23034,
"text": "[7]https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.boxcox_normmax.html?highlight=normmax#scipy.stats.boxcox_normmax"
},
{
"code": null,
"e": 23251,
"s": 23167,
"text": "[8] https://www.kaggle.com/rtatman/data-cleaning-challenge-scale-and-normalize-data"
},
{
"code": null,
"e": 23466,
"s": 23251,
"text": "“One thing you can do is add a fixed value that’s just bigger than your smallest negative to make all your value normal. Another normalization method is the Johnson Transformation, which can handle negative values."
},
{
"code": null,
"e": 23573,
"s": 23466,
"text": "[9] https://towardsdatascience.com/choosing-the-right-encoding-method-label-vs-onehot-encoder-a4434493149b"
},
{
"code": null,
"e": 23685,
"s": 23573,
"text": "[10] https://towardsdatascience.com/one-hot-encoding-multicollinearity-and-the-dummy-variable-trap-b5840be3c41a"
},
{
"code": null,
"e": 23756,
"s": 23685,
"text": "[11] https://medium.com/@ODSC/ensemble-models-demystified-c871d5ee7793"
},
{
"code": null,
"e": 23818,
"s": 23756,
"text": "[12] https://github.com/scikit-learn/scikit-learn/issues/2439"
},
{
"code": null,
"e": 24357,
"s": 23818,
"text": "The Mean Square Error returned by sklearn.cross_validation.cross_val_score is always a negative. While being a designed decision so that the output of this function can be used for maximization given some hyperparameters, it’s extremely confusing when using cross_val_score directly. At least I asked myself how a the mean of a square can possibly be negative and thought that cross_val_score was not working correctly or did not use the supplied metric. Only after digging in the sklearn source code I realized that the sign was flipped."
}
] |
Choose and Swap | Practice | GeeksforGeeks | You are given a string s of lower case english alphabets. You can choose any two characters in the string and replace all the occurences of the first character with the second character and replace all the occurences of the second character with the first character. Your aim is to find the lexicographically smallest string that can be obtained by doing this operation at most once.
Example 1:
Input:
A = "ccad"
Output: "aacd"
Explanation:
In ccad, we choose a and c and after
doing the replacement operation once we get,
aacd and this is the lexicographically
smallest string possible.
Example 2:
Input:
A = "abba"
Output: "abba"
Explanation:
In abba, we can get baab after doing the
replacement operation once for a and b
but that is not lexicographically smaller
than abba. So, the answer is abba.
Your Task:
You don't need to read input or print anything. Your task is to complete the function chooseandswap() which takes the string A as input parameters and returns the lexicographically smallest string that is possible after doing the operation at most once.
Expected Time Complexity: O(|A|) length of the string A
Expected Auxiliary Space: O(1)
Constraints:
1<= |A| <=105
0
anutiger2 days ago
int arr[26];
int md = INT_MAX - 1;
for(int i = 0 ; i <26 ; i++){
arr[i] = md;
}
for(int i = 0 ; i < a.length() ; i ++){
if(arr[a[i] - 'a'] == md){
arr[a[i] - 'a'] = i;
}
}
int swap1 = -1;
int swap2 = -1;
for(int i = 0; i < 26 ; i ++){
if(arr[i] == md) continue;
for(int j = i + 1; j < 26 ; j ++){
if(arr[j] < arr[i]){
if(swap1 == -1){
swap1 = arr[i]; swap2 = arr[j];
}
else{
if(swap2 > arr[j]){
swap2 = arr[j];
}
}
}
}
if(swap1 != -1){
break;
}
}
if(swap1 == INT_MAX){
return a;
}
char c1 = a[swap1];
char c2 = a[swap2];
for(int i = 0 ; i < a.length() ; i ++){
if(a[i] == c1){
a[i] = c2;
}
else if(a[i] == c2){
a[i] = c1;
}
}
return a;
}
0
bhaskarmaheshwari82 weeks ago
//refer this video https://www.youtube.com/watch?v=AiDrMFMxxnQ vector<int> vec(26,-1); int n=str.size(); for(int i=0;i<n;i++) { if(vec[str[i]-'a']==-1) vec[str[i]-'a']=i; } int i; char ch,ch1; for( i=0;i<n;i++) { bool flag=0; for(int j=0;j<str[i]-'a';j++) { if(vec[j]>vec[str[i]-'a']) { ch=j+'a'; ch1=str[i]; flag=1; break; } } if(flag) break; } if(i<n) { for(int j=0;j<n;j++) { if(str[j]==ch) str[j]=ch1; else if(str[j]==ch1) str[j]=ch; } } return str; }
+1
rp212 weeks ago
Concise code, you'd like to see!
int FI[26]; memset(FI, -1, 26 << 2); int n = s.size(); for(int i = 0; i < n; i++){ if(FI[s[i] - 'a'] == -1){ FI[s[i] - 'a'] = i; } } for(int i = 0; i < n; i++){ for(int j = 0; j < (s[i] - 'a'); j++){ if(FI[j] > i){ int x = s[i]; int y = 'a' + j; for(int i = 0; i < n; i++){ if(s[i] == x){ s[i] = y; } else if(s[i] == y){ s[i] = x; } } return s; } } } return s; }
-1
neerajchatterjee23013 weeks ago
string chooseandswap(string s){ int n = s.size(); if(n == 1) return s; int hash[26]; memset(hash, -1, sizeof(hash)); for(int i=0; i<n; i++){ if(hash[s[i] - 'a'] == -1){ hash[s[i] - 'a'] = i; } } int idx1 = -1, idx2 = -1; bool flg = 0; for(int i=0; i<n; i++){ int ch = s[i]; for(int j = 0; j<26; j++){ if(hash[j] > i){ if(j < ch-'a'){ idx1 = i; idx2 = hash[j]; flg = 1; break; } } } if(flg) break; } if(idx1 == -1 and idx2 == -1) return s; char ch1 = s[idx1]; char ch2 = s[idx2]; for(int i=0; i<n; i++){ if(s[i] == ch1) s[i] = ch2; else if(s[i] == ch2) s[i] = ch1; } return s; }
0
18pa1a04771 month ago
python o(n) time o(1) space
class Solution:
def chooseandswap (self, A):
arr=[]
for l in range(26):
arr.append(0)
for k in A:
arr[ord(k)-ord("a")]=arr[ord(k)-ord("a")]+1
# ct=[arr[0]]
# for l in range(1,26):
# ct.append(ct[-1]+arr[l])
ans={}
for ch in A:
f=False
for l in range(ord(ch)-ord("a")):
if arr[l]>0:
ans[chr(ord("a")+l)]=ch
ans[ch]=chr(ord("a")+l)
f=True
break
arr[ord(ch)-ord("a")]=0
if f:
break
st=""
for l in A:
if l in ans:
st=st+ans[l]
else:
st=st+l
return st
0
mdaman700751 month ago
T.C:- O(n)
S.C:- O(1)
string chooseandswap(string a){ vector<int> m(123,-1); int n=a.length(); for(int i=0;i<n;i++){ if(m[a[i]]==-1) m[a[i]]=i; } char ch='\0',ch2='\0'; for(int i=0;i<n;i++){ for(int j=97;j<a[i];j++){ if(m[char(j)]>m[a[i]]){ ch=a[i]; ch2=j; break; } } if(ch) break; } if(ch){ for(int k=0;k<n;k++){ if(a[k]==ch) a[k]=ch2; else if(a[k]==ch2) a[k]=ch; } } return a; }
0
ashutosh441 month ago
Java solution:
class Solution{ String chooseandswap(String a){ int n = a.length(); int[] c = new int[26]; Arrays.fill(c,-1); for(int i=0;i<n;i++){ if(c[a.charAt(i)-'a']==-1){ c[a.charAt(i)-'a'] = i; } } char s = '&'; char e = '&'; for(int i=0;i<n;i++){ char ct = a.charAt(i); int id = a.charAt(i)-'a';
for(int j=0;j<id;j++){ if(c[j]>-1 && c[j] > c[id]){ s = ct; e = (char)(j+'a'); break; } } if(s!='&' && e!='&'){ break; } } StringBuilder t = new StringBuilder(a); for(int i=0;i<n;i++){ if(t.charAt(i)==s){ t.setCharAt(i,e); }else if(t.charAt(i)==e){ t.setCharAt(i,s); } } return String.valueOf(t); }}
-6
itsmohitmk991 month ago
Java - O(N logN))
class Solution{
String chooseandswap(String str){
int n = str.length();
TreeSet<Character> set = new TreeSet<>();
for(int i = 0; i < str.length() ; i++){
set.add(str.charAt(i));
}
Iterator it = set.iterator();
HashMap<Character , Integer> map = new HashMap<>();
char curr = (char)it.next();
char c1 = '1' , c2 = '1';
for(int i = 0 ; i< n ; i++){
if(str.charAt(i) == curr){
map.put(str.charAt(i) , 1);
if(it.hasNext())
curr = (char)it.next();
}
else if(map.containsKey(str.charAt(i))){
continue;
}
else{
c1 = str.charAt(i);
c2 = curr;
break;
}
}
if(c1 == '1')
return str;
StringBuilder sb = new StringBuilder();
for(int i = 0; i< n ; i++){
char ch = str.charAt(i);
if(ch == c1){
sb.append(c2);
}
else if(ch == c2){
sb.append(c1);
}
else{
sb.append(ch);
}
}
return sb.toString();
}
}
0
rahulmallick11151 month ago
Time Complexity : O(N)
Space Complexity : O(1)
string chooseandswap(string a){
int found[26] = {0};
char max_so_far = CHAR_MIN ;
char smallest = CHAR_MAX ;
for(int i = 0 ; i < a.size() ; ++i){
if(found[a[i] - 'a'] == 0 && a[i] < max_so_far){
for(int j = i ; j < a.size() ; ++j){
if(found[a[j] - 'a'] == 0){
smallest = min(smallest , a[j]) ;
}
found[a[j] - 'a'] = 1 ;
}
for(int j = i - 1 ; j >= 0 ; --j){
if(a[j] > smallest){
max_so_far = a[j] ;
}
}
break;
}
max_so_far = max(max_so_far , a[i]);
found[a[i] - 'a'] = 1 ;
}
if(max_so_far != CHAR_MIN && smallest != CHAR_MAX){
for(int i = 0 ; i < a.size() ; ++i){
if(a[i] == max_so_far){
a[i] = smallest ;
}
else if(a[i] == smallest){
a[i] = max_so_far ;
}
}
}
return a;
}
0
akkiashu6805371 month ago
#can any one help me out from this-why my output is always changing? . I think i am not aware of some of the property of dictionary(mapping) which is continuously changing here .
#actually this code is done in O(k*n) or we can say O(n) in space time complexity. Pls help me out from this with this code.
def isequal(self,x,y): for i in range(len(x)): if x[i]!=y[i]: return False return True def chooseandswap (self, A): # code here d={} for i in A: if i not in d: d[i]=1 else: d[i]+=1 k=[ch for ch in d.keys()] k1=[ch for ch in d.keys()] k1.sort() if self.isequal(k1,k): return A ans='' v=[i for i in d.values()] for i in range(len(v)): temp=k1[i]*v[i] ans+=temp return ans
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": 622,
"s": 238,
"text": "You are given a string s of lower case english alphabets. You can choose any two characters in the string and replace all the occurences of the first character with the second character and replace all the occurences of the second character with the first character. Your aim is to find the lexicographically smallest string that can be obtained by doing this operation at most once."
},
{
"code": null,
"e": 633,
"s": 622,
"text": "Example 1:"
},
{
"code": null,
"e": 829,
"s": 633,
"text": "Input:\nA = \"ccad\"\nOutput: \"aacd\"\nExplanation:\nIn ccad, we choose a and c and after \ndoing the replacement operation once we get, \naacd and this is the lexicographically\nsmallest string possible. "
},
{
"code": null,
"e": 842,
"s": 831,
"text": "Example 2:"
},
{
"code": null,
"e": 1049,
"s": 842,
"text": "Input:\nA = \"abba\"\nOutput: \"abba\"\nExplanation:\nIn abba, we can get baab after doing the \nreplacement operation once for a and b \nbut that is not lexicographically smaller \nthan abba. So, the answer is abba. "
},
{
"code": null,
"e": 1405,
"s": 1049,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function chooseandswap() which takes the string A as input parameters and returns the lexicographically smallest string that is possible after doing the operation at most once.\n\nExpected Time Complexity: O(|A|) length of the string A\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1434,
"s": 1407,
"text": "Constraints:\n1<= |A| <=105"
},
{
"code": null,
"e": 1438,
"s": 1436,
"text": "0"
},
{
"code": null,
"e": 1457,
"s": 1438,
"text": "anutiger2 days ago"
},
{
"code": null,
"e": 2692,
"s": 1457,
"text": " int arr[26];\n int md = INT_MAX - 1;\n for(int i = 0 ; i <26 ; i++){\n arr[i] = md;\n }\n for(int i = 0 ; i < a.length() ; i ++){\n if(arr[a[i] - 'a'] == md){\n arr[a[i] - 'a'] = i;\n }\n \n }\n int swap1 = -1;\n int swap2 = -1;\n for(int i = 0; i < 26 ; i ++){\n if(arr[i] == md) continue;\n for(int j = i + 1; j < 26 ; j ++){\n if(arr[j] < arr[i]){\n if(swap1 == -1){\n swap1 = arr[i]; swap2 = arr[j];\n }\n else{\n if(swap2 > arr[j]){\n swap2 = arr[j];\n } \n }\n }\n }\n if(swap1 != -1){\n break;\n }\n }\n if(swap1 == INT_MAX){\n return a;\n }\n char c1 = a[swap1];\n char c2 = a[swap2];\n for(int i = 0 ; i < a.length() ; i ++){\n if(a[i] == c1){\n a[i] = c2;\n }\n else if(a[i] == c2){\n a[i] = c1;\n }\n }\n return a;\n }"
},
{
"code": null,
"e": 2694,
"s": 2692,
"text": "0"
},
{
"code": null,
"e": 2724,
"s": 2694,
"text": "bhaskarmaheshwari82 weeks ago"
},
{
"code": null,
"e": 3600,
"s": 2724,
"text": " //refer this video https://www.youtube.com/watch?v=AiDrMFMxxnQ vector<int> vec(26,-1); int n=str.size(); for(int i=0;i<n;i++) { if(vec[str[i]-'a']==-1) vec[str[i]-'a']=i; } int i; char ch,ch1; for( i=0;i<n;i++) { bool flag=0; for(int j=0;j<str[i]-'a';j++) { if(vec[j]>vec[str[i]-'a']) { ch=j+'a'; ch1=str[i]; flag=1; break; } } if(flag) break; } if(i<n) { for(int j=0;j<n;j++) { if(str[j]==ch) str[j]=ch1; else if(str[j]==ch1) str[j]=ch; } } return str; } "
},
{
"code": null,
"e": 3603,
"s": 3600,
"text": "+1"
},
{
"code": null,
"e": 3619,
"s": 3603,
"text": "rp212 weeks ago"
},
{
"code": null,
"e": 3652,
"s": 3619,
"text": "Concise code, you'd like to see!"
},
{
"code": null,
"e": 4372,
"s": 3654,
"text": " int FI[26]; memset(FI, -1, 26 << 2); int n = s.size(); for(int i = 0; i < n; i++){ if(FI[s[i] - 'a'] == -1){ FI[s[i] - 'a'] = i; } } for(int i = 0; i < n; i++){ for(int j = 0; j < (s[i] - 'a'); j++){ if(FI[j] > i){ int x = s[i]; int y = 'a' + j; for(int i = 0; i < n; i++){ if(s[i] == x){ s[i] = y; } else if(s[i] == y){ s[i] = x; } } return s; } } } return s; }"
},
{
"code": null,
"e": 4375,
"s": 4372,
"text": "-1"
},
{
"code": null,
"e": 4407,
"s": 4375,
"text": "neerajchatterjee23013 weeks ago"
},
{
"code": null,
"e": 5402,
"s": 4407,
"text": "string chooseandswap(string s){ int n = s.size(); if(n == 1) return s; int hash[26]; memset(hash, -1, sizeof(hash)); for(int i=0; i<n; i++){ if(hash[s[i] - 'a'] == -1){ hash[s[i] - 'a'] = i; } } int idx1 = -1, idx2 = -1; bool flg = 0; for(int i=0; i<n; i++){ int ch = s[i]; for(int j = 0; j<26; j++){ if(hash[j] > i){ if(j < ch-'a'){ idx1 = i; idx2 = hash[j]; flg = 1; break; } } } if(flg) break; } if(idx1 == -1 and idx2 == -1) return s; char ch1 = s[idx1]; char ch2 = s[idx2]; for(int i=0; i<n; i++){ if(s[i] == ch1) s[i] = ch2; else if(s[i] == ch2) s[i] = ch1; } return s; }"
},
{
"code": null,
"e": 5404,
"s": 5402,
"text": "0"
},
{
"code": null,
"e": 5426,
"s": 5404,
"text": "18pa1a04771 month ago"
},
{
"code": null,
"e": 6238,
"s": 5426,
"text": "python o(n) time o(1) space\nclass Solution:\n def chooseandswap (self, A):\n arr=[]\n for l in range(26):\n arr.append(0)\n for k in A:\n arr[ord(k)-ord(\"a\")]=arr[ord(k)-ord(\"a\")]+1\n # ct=[arr[0]]\n # for l in range(1,26):\n # ct.append(ct[-1]+arr[l])\n ans={}\n for ch in A:\n f=False\n for l in range(ord(ch)-ord(\"a\")):\n if arr[l]>0:\n ans[chr(ord(\"a\")+l)]=ch\n ans[ch]=chr(ord(\"a\")+l)\n f=True\n break\n arr[ord(ch)-ord(\"a\")]=0\n if f:\n break\n st=\"\"\n for l in A:\n if l in ans:\n st=st+ans[l]\n else:\n st=st+l\n return st"
},
{
"code": null,
"e": 6242,
"s": 6240,
"text": "0"
},
{
"code": null,
"e": 6265,
"s": 6242,
"text": "mdaman700751 month ago"
},
{
"code": null,
"e": 6278,
"s": 6267,
"text": "T.C:- O(n)"
},
{
"code": null,
"e": 6290,
"s": 6278,
"text": "S.C:- O(1) "
},
{
"code": null,
"e": 6972,
"s": 6292,
"text": " string chooseandswap(string a){ vector<int> m(123,-1); int n=a.length(); for(int i=0;i<n;i++){ if(m[a[i]]==-1) m[a[i]]=i; } char ch='\\0',ch2='\\0'; for(int i=0;i<n;i++){ for(int j=97;j<a[i];j++){ if(m[char(j)]>m[a[i]]){ ch=a[i]; ch2=j; break; } } if(ch) break; } if(ch){ for(int k=0;k<n;k++){ if(a[k]==ch) a[k]=ch2; else if(a[k]==ch2) a[k]=ch; } } return a; }"
},
{
"code": null,
"e": 6974,
"s": 6972,
"text": "0"
},
{
"code": null,
"e": 6996,
"s": 6974,
"text": "ashutosh441 month ago"
},
{
"code": null,
"e": 7011,
"s": 6996,
"text": "Java solution:"
},
{
"code": null,
"e": 7404,
"s": 7013,
"text": "class Solution{ String chooseandswap(String a){ int n = a.length(); int[] c = new int[26]; Arrays.fill(c,-1); for(int i=0;i<n;i++){ if(c[a.charAt(i)-'a']==-1){ c[a.charAt(i)-'a'] = i; } } char s = '&'; char e = '&'; for(int i=0;i<n;i++){ char ct = a.charAt(i); int id = a.charAt(i)-'a';"
},
{
"code": null,
"e": 7957,
"s": 7404,
"text": " for(int j=0;j<id;j++){ if(c[j]>-1 && c[j] > c[id]){ s = ct; e = (char)(j+'a'); break; } } if(s!='&' && e!='&'){ break; } } StringBuilder t = new StringBuilder(a); for(int i=0;i<n;i++){ if(t.charAt(i)==s){ t.setCharAt(i,e); }else if(t.charAt(i)==e){ t.setCharAt(i,s); } } return String.valueOf(t); }}"
},
{
"code": null,
"e": 7960,
"s": 7957,
"text": "-6"
},
{
"code": null,
"e": 7984,
"s": 7960,
"text": "itsmohitmk991 month ago"
},
{
"code": null,
"e": 8002,
"s": 7984,
"text": "Java - O(N logN))"
},
{
"code": null,
"e": 9339,
"s": 8004,
"text": "class Solution{\n String chooseandswap(String str){\n int n = str.length();\n \n TreeSet<Character> set = new TreeSet<>();\n for(int i = 0; i < str.length() ; i++){\n set.add(str.charAt(i));\n }\n \n Iterator it = set.iterator();\n HashMap<Character , Integer> map = new HashMap<>();\n \n char curr = (char)it.next();\n char c1 = '1' , c2 = '1';\n \n \n for(int i = 0 ; i< n ; i++){\n if(str.charAt(i) == curr){\n map.put(str.charAt(i) , 1);\n if(it.hasNext())\n curr = (char)it.next();\n }\n else if(map.containsKey(str.charAt(i))){\n continue;\n }\n else{\n c1 = str.charAt(i);\n c2 = curr;\n break;\n }\n }\n \n if(c1 == '1')\n return str;\n \n StringBuilder sb = new StringBuilder();\n \n for(int i = 0; i< n ; i++){\n char ch = str.charAt(i);\n if(ch == c1){\n sb.append(c2);\n }\n else if(ch == c2){\n sb.append(c1);\n }\n else{\n sb.append(ch);\n }\n }\n \n return sb.toString();\n }\n \n}"
},
{
"code": null,
"e": 9341,
"s": 9339,
"text": "0"
},
{
"code": null,
"e": 9369,
"s": 9341,
"text": "rahulmallick11151 month ago"
},
{
"code": null,
"e": 9396,
"s": 9369,
"text": "Time Complexity : O(N)"
},
{
"code": null,
"e": 9423,
"s": 9396,
"text": "Space Complexity : O(1)"
},
{
"code": null,
"e": 10570,
"s": 9423,
"text": "string chooseandswap(string a){\n int found[26] = {0};\n char max_so_far = CHAR_MIN ;\n char smallest = CHAR_MAX ;\n for(int i = 0 ; i < a.size() ; ++i){\n if(found[a[i] - 'a'] == 0 && a[i] < max_so_far){\n for(int j = i ; j < a.size() ; ++j){\n if(found[a[j] - 'a'] == 0){\n smallest = min(smallest , a[j]) ;\n }\n found[a[j] - 'a'] = 1 ;\n }\n for(int j = i - 1 ; j >= 0 ; --j){\n if(a[j] > smallest){\n max_so_far = a[j] ;\n }\n }\n break;\n }\n max_so_far = max(max_so_far , a[i]);\n found[a[i] - 'a'] = 1 ;\n }\n if(max_so_far != CHAR_MIN && smallest != CHAR_MAX){\n for(int i = 0 ; i < a.size() ; ++i){\n if(a[i] == max_so_far){\n a[i] = smallest ;\n }\n else if(a[i] == smallest){\n a[i] = max_so_far ;\n }\n }\n }\n return a;\n }"
},
{
"code": null,
"e": 10572,
"s": 10570,
"text": "0"
},
{
"code": null,
"e": 10598,
"s": 10572,
"text": "akkiashu6805371 month ago"
},
{
"code": null,
"e": 10779,
"s": 10598,
"text": "#can any one help me out from this-why my output is always changing? . I think i am not aware of some of the property of dictionary(mapping) which is continuously changing here ."
},
{
"code": null,
"e": 10905,
"s": 10779,
"text": "#actually this code is done in O(k*n) or we can say O(n) in space time complexity. Pls help me out from this with this code."
},
{
"code": null,
"e": 11505,
"s": 10905,
"text": "def isequal(self,x,y): for i in range(len(x)): if x[i]!=y[i]: return False return True def chooseandswap (self, A): # code here d={} for i in A: if i not in d: d[i]=1 else: d[i]+=1 k=[ch for ch in d.keys()] k1=[ch for ch in d.keys()] k1.sort() if self.isequal(k1,k): return A ans='' v=[i for i in d.values()] for i in range(len(v)): temp=k1[i]*v[i] ans+=temp return ans "
},
{
"code": null,
"e": 11651,
"s": 11505,
"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": 11687,
"s": 11651,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11697,
"s": 11687,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11707,
"s": 11697,
"text": "\nContest\n"
},
{
"code": null,
"e": 11770,
"s": 11707,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11918,
"s": 11770,
"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": 12126,
"s": 11918,
"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": 12232,
"s": 12126,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C++ Algorithm Library - copy() Function | The C++ function std::algorithm::copy() copies a range of elements to a new location.
Following is the declaration for std::algorithm::copy() function form std::algorithm header.
template <class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
first − Input iterators to the initial positions in a sequence.
first − Input iterators to the initial positions in a sequence.
last − Input iterators to the final positions in a sequence.
last − Input iterators to the final positions in a sequence.
result − Output iterator to the initial position in the new sequence.
result − Output iterator to the initial position in the new sequence.
Returns an iterator to the end of the destination range where elements have been copied.
Throws an exception if either element assignment or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear in the distance between first to last.
The following example shows the usage of std::algorithm::copy() function.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2(5);
copy(v1.begin(), v1.end(), v2.begin());
cout << "Vector v2 contains following elements" << endl;
for (auto it = v2.begin(); it != v2.end(); ++it)
cout << *it << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
Vector v2 contains following elements
1
2
3
4
5
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2689,
"s": 2603,
"text": "The C++ function std::algorithm::copy() copies a range of elements to a new location."
},
{
"code": null,
"e": 2782,
"s": 2689,
"text": "Following is the declaration for std::algorithm::copy() function form std::algorithm header."
},
{
"code": null,
"e": 2922,
"s": 2782,
"text": "template <class InputIterator, class OutputIterator>\nOutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);\n"
},
{
"code": null,
"e": 2986,
"s": 2922,
"text": "first − Input iterators to the initial positions in a sequence."
},
{
"code": null,
"e": 3050,
"s": 2986,
"text": "first − Input iterators to the initial positions in a sequence."
},
{
"code": null,
"e": 3111,
"s": 3050,
"text": "last − Input iterators to the final positions in a sequence."
},
{
"code": null,
"e": 3172,
"s": 3111,
"text": "last − Input iterators to the final positions in a sequence."
},
{
"code": null,
"e": 3242,
"s": 3172,
"text": "result − Output iterator to the initial position in the new sequence."
},
{
"code": null,
"e": 3312,
"s": 3242,
"text": "result − Output iterator to the initial position in the new sequence."
},
{
"code": null,
"e": 3401,
"s": 3312,
"text": "Returns an iterator to the end of the destination range where elements have been copied."
},
{
"code": null,
"e": 3499,
"s": 3401,
"text": "Throws an exception if either element assignment or an operation on an iterator throws exception."
},
{
"code": null,
"e": 3561,
"s": 3499,
"text": "Please note that invalid parameters cause undefined behavior."
},
{
"code": null,
"e": 3607,
"s": 3561,
"text": "Linear in the distance between first to last."
},
{
"code": null,
"e": 3681,
"s": 3607,
"text": "The following example shows the usage of std::algorithm::copy() function."
},
{
"code": null,
"e": 4040,
"s": 3681,
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v1 = {1, 2, 3, 4, 5};\n vector<int> v2(5);\n\n copy(v1.begin(), v1.end(), v2.begin());\n\n cout << \"Vector v2 contains following elements\" << endl;\n\n for (auto it = v2.begin(); it != v2.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 4123,
"s": 4040,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 4172,
"s": 4123,
"text": "Vector v2 contains following elements\n1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 4179,
"s": 4172,
"text": " Print"
},
{
"code": null,
"e": 4190,
"s": 4179,
"text": " Add Notes"
}
] |
My Java Setup in Visual Studio Code | by Ryan Gleason | Towards Data Science | Launch a simple Java application after setting up a local development environment.
We are going to keep this as short and as simple as possible. You will be able to get Java code up and running in your VSCode environment in less than five minutes.
These are the tools we will be installing:
Visual Studio Code
Java Development Kit (JDK)
Java Extensions to enhance our environment
Let’s get started!
Download the stable build from Visual Studio Code.
This is a very easy download. Microsoft has done a good job of simplifying the installation process for this application.
This process has been automated like you wouldn’t believe.
We are going to navigate to this site: https://code.visualstudio.com/docs/languages/java and then scroll down to where you see “Download Visual Studio Code Java Pack Installer”
This installer is going to take care of all Java-related packages that are required for you to get started with Java development.
Hit the “Install” button and it will take a couple of seconds to complete.
Once we have the JDK installed, we can install the Extension Pack. These are tools that will enhance our project. It adds things like autocomplete, a dependency viewer, Maven support, a debugger, test runner, etc.
On the VSCode site we were just on, scroll down until you see this:
Click the Install the Java Extension Pack button.
Once this Extension Pack has been successfully installed you will be brought to a screen that looks like this:
We are going to follow the directions and create a new file. Inside this file we are going to put the following code:
class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World."); }}
When you click the “Run” button (or hit F5) you should see this output in the console:
Note: If you have a space anywhere in your path. For example, if this was my path: C:\Users\Ryan Gleason\Documents\...
A quick solution is to switch your default terminal to Powershell.
Type Ctrl + Shift + P to open up your command palette, enter Terminal: Select Default Shell and choose the Powershell option.
And that’s it. You are now ready to build something amazing using Java in VSCode! | [
{
"code": null,
"e": 255,
"s": 172,
"text": "Launch a simple Java application after setting up a local development environment."
},
{
"code": null,
"e": 420,
"s": 255,
"text": "We are going to keep this as short and as simple as possible. You will be able to get Java code up and running in your VSCode environment in less than five minutes."
},
{
"code": null,
"e": 463,
"s": 420,
"text": "These are the tools we will be installing:"
},
{
"code": null,
"e": 482,
"s": 463,
"text": "Visual Studio Code"
},
{
"code": null,
"e": 509,
"s": 482,
"text": "Java Development Kit (JDK)"
},
{
"code": null,
"e": 552,
"s": 509,
"text": "Java Extensions to enhance our environment"
},
{
"code": null,
"e": 571,
"s": 552,
"text": "Let’s get started!"
},
{
"code": null,
"e": 622,
"s": 571,
"text": "Download the stable build from Visual Studio Code."
},
{
"code": null,
"e": 744,
"s": 622,
"text": "This is a very easy download. Microsoft has done a good job of simplifying the installation process for this application."
},
{
"code": null,
"e": 803,
"s": 744,
"text": "This process has been automated like you wouldn’t believe."
},
{
"code": null,
"e": 980,
"s": 803,
"text": "We are going to navigate to this site: https://code.visualstudio.com/docs/languages/java and then scroll down to where you see “Download Visual Studio Code Java Pack Installer”"
},
{
"code": null,
"e": 1110,
"s": 980,
"text": "This installer is going to take care of all Java-related packages that are required for you to get started with Java development."
},
{
"code": null,
"e": 1185,
"s": 1110,
"text": "Hit the “Install” button and it will take a couple of seconds to complete."
},
{
"code": null,
"e": 1399,
"s": 1185,
"text": "Once we have the JDK installed, we can install the Extension Pack. These are tools that will enhance our project. It adds things like autocomplete, a dependency viewer, Maven support, a debugger, test runner, etc."
},
{
"code": null,
"e": 1467,
"s": 1399,
"text": "On the VSCode site we were just on, scroll down until you see this:"
},
{
"code": null,
"e": 1517,
"s": 1467,
"text": "Click the Install the Java Extension Pack button."
},
{
"code": null,
"e": 1628,
"s": 1517,
"text": "Once this Extension Pack has been successfully installed you will be brought to a screen that looks like this:"
},
{
"code": null,
"e": 1746,
"s": 1628,
"text": "We are going to follow the directions and create a new file. Inside this file we are going to put the following code:"
},
{
"code": null,
"e": 1851,
"s": 1746,
"text": "class HelloWorld { public static void main(String[] args) { System.out.println(\"Hello, World.\"); }}"
},
{
"code": null,
"e": 1938,
"s": 1851,
"text": "When you click the “Run” button (or hit F5) you should see this output in the console:"
},
{
"code": null,
"e": 2057,
"s": 1938,
"text": "Note: If you have a space anywhere in your path. For example, if this was my path: C:\\Users\\Ryan Gleason\\Documents\\..."
},
{
"code": null,
"e": 2124,
"s": 2057,
"text": "A quick solution is to switch your default terminal to Powershell."
},
{
"code": null,
"e": 2250,
"s": 2124,
"text": "Type Ctrl + Shift + P to open up your command palette, enter Terminal: Select Default Shell and choose the Powershell option."
}
] |
Program to calculate Area Of Octagon | 21 Jun, 2022
A regular octagon is a closed figure with sides of the same length and internal angles of the same size. It has eight lines of reflective symmetry and rotational symmetry of order 8. The internal angle at each vertex of a regular octagon is 135°. The central angle is 45°.Properties :
Convex polygon, Equilateral polygon, Isogonal figure, Isotoxal figure, Cyclic.
Formula :
Area : 2 × (side length)2 × (1+sqrt(2))
Examples :
Input : side = 3
Output : Area of Regular Octagon = 43.4558
Input : side = 4
Output : Area of Regular Octagon = 77.2548
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find area of octagon#include <bits/stdc++.h>using namespace std; // Utility functiondouble areaOctagon(double side){ return (float)(2 * (1 + sqrt(2)) * side * side);} // Driver Codeint main(){ double side = 4; cout << "Area of Regular Octagon = " << areaOctagon(side) << endl; return 0;}
// Java Program to find// area of Octagon.import java.io.*; class GFG{ // utility function static double areaOctagon(double side) { return (float)(2 * (1 + Math.sqrt(2)) * side * side); } // driver code public static void main(String arg[]) { double side = 4; System.out.print("Area of Regular Octagon = " + areaOctagon(side)); }} // This code is contributed by Anant Agarwal.
# Python3 program to# find area of octagon import math # Utility functiondef areaOctagon(side): return (2 * (1 + (math.sqrt(2))) * side * side) # Driver functionside = 4print("Area of Regular Octagon =", round(areaOctagon(side), 4)) # This code is contributed# by Azkia Anam.
// C# Program to find// area of Octagon.using System; class GFG{ // utility function static double areaOctagon(double side) { return (float)(2 * (1 + Math.Sqrt(2)) * side * side); } // Driver code public static void Main() { double side = 4; Console.WriteLine("Area of Regular Octagon = " + areaOctagon(side)); }} // This code is contributed by vt_m.
<?php// PHP program to find area of octagon // Utility functionfunction areaOctagon( $side){ return (2 * (1 + sqrt(2)) * $side * $side);} // Driver Code $side = 4;echo("Area of Regular Octagon = ");echo(areaOctagon($side)); // This code is contributed by vt_m.?>
<script> // Javascript program to find area of octagon // Utility functionfunction areaOctagon(side){ return (2 * (1 + Math.sqrt(2)) * side * side);} // Driver Code let side = 4; document.write("Area of Regular Octagon = " + areaOctagon(side) + "<br>"); // This code is contributed by Mayank Tyagi</script>
Output :
Area of Regular Octagon = 77.25
Time complexity : O(1) Auxiliary Space : O(1)
vt_m
mayanktyagi1709
krishnav4
area-volume-programs
Geometric
Mathematical
School Programming
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 315,
"s": 28,
"text": "A regular octagon is a closed figure with sides of the same length and internal angles of the same size. It has eight lines of reflective symmetry and rotational symmetry of order 8. The internal angle at each vertex of a regular octagon is 135°. The central angle is 45°.Properties : "
},
{
"code": null,
"e": 394,
"s": 315,
"text": "Convex polygon, Equilateral polygon, Isogonal figure, Isotoxal figure, Cyclic."
},
{
"code": null,
"e": 408,
"s": 396,
"text": "Formula : "
},
{
"code": null,
"e": 448,
"s": 408,
"text": "Area : 2 × (side length)2 × (1+sqrt(2))"
},
{
"code": null,
"e": 461,
"s": 448,
"text": "Examples : "
},
{
"code": null,
"e": 582,
"s": 461,
"text": "Input : side = 3\nOutput : Area of Regular Octagon = 43.4558\n\nInput : side = 4\nOutput : Area of Regular Octagon = 77.2548"
},
{
"code": null,
"e": 590,
"s": 586,
"text": "C++"
},
{
"code": null,
"e": 595,
"s": 590,
"text": "Java"
},
{
"code": null,
"e": 603,
"s": 595,
"text": "Python3"
},
{
"code": null,
"e": 606,
"s": 603,
"text": "C#"
},
{
"code": null,
"e": 610,
"s": 606,
"text": "PHP"
},
{
"code": null,
"e": 621,
"s": 610,
"text": "Javascript"
},
{
"code": "// CPP program to find area of octagon#include <bits/stdc++.h>using namespace std; // Utility functiondouble areaOctagon(double side){ return (float)(2 * (1 + sqrt(2)) * side * side);} // Driver Codeint main(){ double side = 4; cout << \"Area of Regular Octagon = \" << areaOctagon(side) << endl; return 0;}",
"e": 965,
"s": 621,
"text": null
},
{
"code": "// Java Program to find// area of Octagon.import java.io.*; class GFG{ // utility function static double areaOctagon(double side) { return (float)(2 * (1 + Math.sqrt(2)) * side * side); } // driver code public static void main(String arg[]) { double side = 4; System.out.print(\"Area of Regular Octagon = \" + areaOctagon(side)); }} // This code is contributed by Anant Agarwal.",
"e": 1441,
"s": 965,
"text": null
},
{
"code": "# Python3 program to# find area of octagon import math # Utility functiondef areaOctagon(side): return (2 * (1 + (math.sqrt(2))) * side * side) # Driver functionside = 4print(\"Area of Regular Octagon =\", round(areaOctagon(side), 4)) # This code is contributed# by Azkia Anam.",
"e": 1726,
"s": 1441,
"text": null
},
{
"code": "// C# Program to find// area of Octagon.using System; class GFG{ // utility function static double areaOctagon(double side) { return (float)(2 * (1 + Math.Sqrt(2)) * side * side); } // Driver code public static void Main() { double side = 4; Console.WriteLine(\"Area of Regular Octagon = \" + areaOctagon(side)); }} // This code is contributed by vt_m.",
"e": 2171,
"s": 1726,
"text": null
},
{
"code": "<?php// PHP program to find area of octagon // Utility functionfunction areaOctagon( $side){ return (2 * (1 + sqrt(2)) * $side * $side);} // Driver Code $side = 4;echo(\"Area of Regular Octagon = \");echo(areaOctagon($side)); // This code is contributed by vt_m.?>",
"e": 2448,
"s": 2171,
"text": null
},
{
"code": "<script> // Javascript program to find area of octagon // Utility functionfunction areaOctagon(side){ return (2 * (1 + Math.sqrt(2)) * side * side);} // Driver Code let side = 4; document.write(\"Area of Regular Octagon = \" + areaOctagon(side) + \"<br>\"); // This code is contributed by Mayank Tyagi</script>",
"e": 2786,
"s": 2448,
"text": null
},
{
"code": null,
"e": 2797,
"s": 2786,
"text": "Output : "
},
{
"code": null,
"e": 2829,
"s": 2797,
"text": "Area of Regular Octagon = 77.25"
},
{
"code": null,
"e": 2875,
"s": 2829,
"text": "Time complexity : O(1) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 2880,
"s": 2875,
"text": "vt_m"
},
{
"code": null,
"e": 2896,
"s": 2880,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 2906,
"s": 2896,
"text": "krishnav4"
},
{
"code": null,
"e": 2927,
"s": 2906,
"text": "area-volume-programs"
},
{
"code": null,
"e": 2937,
"s": 2927,
"text": "Geometric"
},
{
"code": null,
"e": 2950,
"s": 2937,
"text": "Mathematical"
},
{
"code": null,
"e": 2969,
"s": 2950,
"text": "School Programming"
},
{
"code": null,
"e": 2982,
"s": 2969,
"text": "Mathematical"
},
{
"code": null,
"e": 2992,
"s": 2982,
"text": "Geometric"
}
] |
The implementation of import in Python (importlib) | The importlib package provides the implementation of the import statement in Python source code portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python.
This package also exposes components to implement import, making it easier for users to create their own custom objects (known as an importer) to participate in the import process.
The importlib package has an important function named as import_module()
This function imports a module programmatically. Name of module is first parameter to the function. Optional second parameter specifies package name if any.
This function invalidates the internal caches of finders. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module’s existence.
This function reloads a previously imported module. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
Example:
Create two Python scripts named module1.py and module2.py having same code as below:
#module1
def main():
print ('module imported', __name__)
return
if __name__=='__main__':
main()
We now import these modules dynamically using importlib package.
>>> import importlib
>>> mod=importlib.import_module('module1')
>>> mod.__name__
'module1'
>>> mod=importlib.import_module('module2')
>>> mod.__name__
'module2'
>>> mod.main()
module imported module2
>>>
The importlib package contains following submodules:
This module contains all of the core abstract base classes used by import. Some subclasses of the core abstract base classes are also provided to help in implementing the core ABCs
This module leverages Python’s import system to provide access to resources within packages.
This module contains the various objects that help import find and load modules.
This module has utility code for importers. It contains the various objects that help in the construction of an importer. Following important functions are defined in it.
This function find the specifications for a module, relative to the specified package name. If name is for a submodule (contains a dot), the parent module is automatically imported. Name and package work the same as for import_module().
Create a new module based on spec and spec.loader.create_module.
import importlib.util
def check_module(mod):
spec = importlib.util.find_spec(mod)
if spec is None:
print('Module: {} not found'.format(mod))
return None
else:
print('Module: {} can be imported!'.format(mod))
return spec
def import_module(spec):
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
if __name__ == '__main__':
spec = check_module('notamodule')
spec = check_module('module1')
if spec:
mod = import_module(spec)
mod.main()
Module: notamodule not found
Module: module1 can be imported!
module imported module1 | [
{
"code": null,
"e": 1327,
"s": 1062,
"text": "The importlib package provides the implementation of the import statement in Python source code portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python."
},
{
"code": null,
"e": 1508,
"s": 1327,
"text": "This package also exposes components to implement import, making it easier for users to create their own custom objects (known as an importer) to participate in the import process."
},
{
"code": null,
"e": 1581,
"s": 1508,
"text": "The importlib package has an important function named as import_module()"
},
{
"code": null,
"e": 1738,
"s": 1581,
"text": "This function imports a module programmatically. Name of module is first parameter to the function. Optional second parameter specifies package name if any."
},
{
"code": null,
"e": 1959,
"s": 1738,
"text": "This function invalidates the internal caches of finders. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module’s existence."
},
{
"code": null,
"e": 2169,
"s": 1959,
"text": "This function reloads a previously imported module. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter."
},
{
"code": null,
"e": 2178,
"s": 2169,
"text": "Example:"
},
{
"code": null,
"e": 2263,
"s": 2178,
"text": "Create two Python scripts named module1.py and module2.py having same code as below:"
},
{
"code": null,
"e": 2368,
"s": 2263,
"text": "#module1\ndef main():\n print ('module imported', __name__)\n return\nif __name__=='__main__':\n main()"
},
{
"code": null,
"e": 2433,
"s": 2368,
"text": "We now import these modules dynamically using importlib package."
},
{
"code": null,
"e": 2637,
"s": 2433,
"text": ">>> import importlib\n>>> mod=importlib.import_module('module1')\n>>> mod.__name__\n'module1'\n>>> mod=importlib.import_module('module2')\n>>> mod.__name__\n'module2'\n>>> mod.main()\nmodule imported module2\n>>>"
},
{
"code": null,
"e": 2690,
"s": 2637,
"text": "The importlib package contains following submodules:"
},
{
"code": null,
"e": 2871,
"s": 2690,
"text": "This module contains all of the core abstract base classes used by import. Some subclasses of the core abstract base classes are also provided to help in implementing the core ABCs"
},
{
"code": null,
"e": 2964,
"s": 2871,
"text": "This module leverages Python’s import system to provide access to resources within packages."
},
{
"code": null,
"e": 3045,
"s": 2964,
"text": "This module contains the various objects that help import find and load modules."
},
{
"code": null,
"e": 3216,
"s": 3045,
"text": "This module has utility code for importers. It contains the various objects that help in the construction of an importer. Following important functions are defined in it."
},
{
"code": null,
"e": 3453,
"s": 3216,
"text": "This function find the specifications for a module, relative to the specified package name. If name is for a submodule (contains a dot), the parent module is automatically imported. Name and package work the same as for import_module()."
},
{
"code": null,
"e": 3518,
"s": 3453,
"text": "Create a new module based on spec and spec.loader.create_module."
},
{
"code": null,
"e": 4060,
"s": 3518,
"text": "import importlib.util\ndef check_module(mod):\n spec = importlib.util.find_spec(mod)\n if spec is None:\n print('Module: {} not found'.format(mod))\n return None\n else:\n print('Module: {} can be imported!'.format(mod))\n return spec\n def import_module(spec):\n mod = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(mod)\n return mod\nif __name__ == '__main__':\n spec = check_module('notamodule')\n spec = check_module('module1')\n if spec:\n mod = import_module(spec)\n mod.main()"
},
{
"code": null,
"e": 4146,
"s": 4060,
"text": "Module: notamodule not found\nModule: module1 can be imported!\nmodule imported module1"
}
] |
How to Remove Duplicate Values from Slice in Golang? - GeeksforGeeks | 05 Aug, 2021
An array is a data structure. Similarly, in Golang we have slice which is more flexible, powerful, lightweight and convenient than array. As slice is more flexible than array therefore, its flexibility is determined in terms of its size. Just like an array, it has indexing value and length but its size is not fixed. When we declare a slice we do not specify the size of it. Syntax:
[]mySlice;
OR
[]mySlice{};
OR
[]mySlice{input1, input2, .........input n}
Moreover, a slice and an array are connected with each other, in a slice, there is a referencing to an underlying array. And in a slice, we can store duplicate elements.Example: Here, we will see how to remove the duplicate elements from slice. We have defined a function where we are passing the slice values and using the map function we are checking the duplicates and removing them.
C
// Golang program to remove duplicate// values from Slicepackage main import ( "fmt") func removeDuplicateValues(intSlice []int) []int { keys := make(map[int]bool) list := []int{} // If the key(values of the slice) is not equal // to the already present value in new slice (list) // then we append it. else we jump on another element. for _, entry := range intSlice { if _, value := keys[entry]; !value { keys[entry] = true list = append(list, entry) } } return list} func main() { // Assigning values to the slice intSliceValues := []int{1,2,3,4,5,2,3,5,7,9,6,7} // Printing original value of slice fmt.Println(intSliceValues) // Calling function where we // are removing the duplicates removeDuplicateValuesSlice := removeDuplicateValues(intSliceValues) // Printing the filtered slice // without duplicates fmt.Println(removeDuplicateValuesSlice)}
Output:
[1 2 3 4 5 2 3 5 7 9 6 7]
[1 2 3 4 5 7 9 6]
Explanation:
From the main function, we have declared a slice. Also we have print the original value of the slice.
We have defined a function where we are passing the slice original values and checking the duplicates.
Logic for duplicate check : For this we have defined another slice and assigning the first values by checking if the value already exists in the new slice or not. It returns the slice without duplicates.
We are calling removeDuplicateValues function from main function where the return slice from the function is printed.
Golang-Slices
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
How to Split a String in Golang?
Arrays in Go
Golang Maps
Slices in Golang
How to compare times in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
How to Parse JSON in Golang?
Different Ways to Find the Type of Variable in Golang | [
{
"code": null,
"e": 24470,
"s": 24442,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 24855,
"s": 24470,
"text": "An array is a data structure. Similarly, in Golang we have slice which is more flexible, powerful, lightweight and convenient than array. As slice is more flexible than array therefore, its flexibility is determined in terms of its size. Just like an array, it has indexing value and length but its size is not fixed. When we declare a slice we do not specify the size of it. Syntax: "
},
{
"code": null,
"e": 24930,
"s": 24855,
"text": "[]mySlice;\n OR\n[]mySlice{};\nOR\n[]mySlice{input1, input2, .........input n}"
},
{
"code": null,
"e": 25318,
"s": 24930,
"text": "Moreover, a slice and an array are connected with each other, in a slice, there is a referencing to an underlying array. And in a slice, we can store duplicate elements.Example: Here, we will see how to remove the duplicate elements from slice. We have defined a function where we are passing the slice values and using the map function we are checking the duplicates and removing them. "
},
{
"code": null,
"e": 25320,
"s": 25318,
"text": "C"
},
{
"code": "// Golang program to remove duplicate// values from Slicepackage main import ( \"fmt\") func removeDuplicateValues(intSlice []int) []int { keys := make(map[int]bool) list := []int{} // If the key(values of the slice) is not equal // to the already present value in new slice (list) // then we append it. else we jump on another element. for _, entry := range intSlice { if _, value := keys[entry]; !value { keys[entry] = true list = append(list, entry) } } return list} func main() { // Assigning values to the slice intSliceValues := []int{1,2,3,4,5,2,3,5,7,9,6,7} // Printing original value of slice fmt.Println(intSliceValues) // Calling function where we // are removing the duplicates removeDuplicateValuesSlice := removeDuplicateValues(intSliceValues) // Printing the filtered slice // without duplicates fmt.Println(removeDuplicateValuesSlice)}",
"e": 26268,
"s": 25320,
"text": null
},
{
"code": null,
"e": 26277,
"s": 26268,
"text": "Output: "
},
{
"code": null,
"e": 26321,
"s": 26277,
"text": "[1 2 3 4 5 2 3 5 7 9 6 7]\n[1 2 3 4 5 7 9 6]"
},
{
"code": null,
"e": 26335,
"s": 26321,
"text": "Explanation: "
},
{
"code": null,
"e": 26437,
"s": 26335,
"text": "From the main function, we have declared a slice. Also we have print the original value of the slice."
},
{
"code": null,
"e": 26540,
"s": 26437,
"text": "We have defined a function where we are passing the slice original values and checking the duplicates."
},
{
"code": null,
"e": 26744,
"s": 26540,
"text": "Logic for duplicate check : For this we have defined another slice and assigning the first values by checking if the value already exists in the new slice or not. It returns the slice without duplicates."
},
{
"code": null,
"e": 26862,
"s": 26744,
"text": "We are calling removeDuplicateValues function from main function where the return slice from the function is printed."
},
{
"code": null,
"e": 26878,
"s": 26864,
"text": "Golang-Slices"
},
{
"code": null,
"e": 26885,
"s": 26878,
"text": "Picked"
},
{
"code": null,
"e": 26897,
"s": 26885,
"text": "Go Language"
},
{
"code": null,
"e": 26995,
"s": 26897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27046,
"s": 26995,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27079,
"s": 27046,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27092,
"s": 27079,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27104,
"s": 27092,
"text": "Golang Maps"
},
{
"code": null,
"e": 27121,
"s": 27104,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27153,
"s": 27121,
"text": "How to compare times in Golang?"
},
{
"code": null,
"e": 27185,
"s": 27153,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 27207,
"s": 27185,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 27236,
"s": 27207,
"text": "How to Parse JSON in Golang?"
}
] |
Convert Text Image to Hand Written Text Image using Python - GeeksforGeeks | 29 Jun, 2021
In this article, we are going to see how to convert text images to handwritten text images using PyWhatkit, Pillow, and Tesseract in Python.
Pytesseract: Sometimes known as Python-tesseract, is a Python-based optical character recognition (OCR) program. It can read and recognize text in photos, license plates, and other documents. To interpret the words from the provided image, we’ll utilize the tesseract software.
pip install pytesseract
Pywhatkit: It is a library that may be used for a variety of things, including sending WhatsApp messages, watching YouTube videos, searching Google, and writing handwritten text.
pip install pywhatkit
Pillow: This module adds more features, operates on all major operating systems, and has Python 3 support. It supports a broad range of image formats, including “jpeg,” “png,” “bmp,” “gif,” “ppm,” and “tiff.” With the pillow module, you can do nearly anything with digital photographs.
pip install Pillow
Note: Visit and Install Tesseract; scroll down to find the latest installers for 32-bit and 64-bit systems; download them as needed.
Step 1: Import the following modules.
Python3
import pytesseract from PIL import Image import osimport pywhatkit as kit
Step 2: Navigate to the path where the picture is located, the chdir function in the OS module can be used to alter the directory.
Python3
os.chdir(r"C:\Users\Dell\Downloads")
Step 3: Copy the installation path for Tesseract, paste it here, or verify the directory of Tesseract and copy the entire path.
Python3
pytesseract.pytesseract.tesseract_cmd = r"C:\Users\Dell\AppData\Local\/Tesseract-OCR\tesseract.exe"
Step 4: First, open the image with the image function, then use pytesseract to get all the image’s data, and store all the text in a variable.
Python3
img = Image.open("GFG.png")text = pytesseract.image_to_string(img)
Step 5: Use the text _to_handwriting function from pywhatkit to convert text to the specified RGB color; in this case, the RGB for blue is 0, 0, 250.
Python3
kit.text_to_handwriting(text, rgb=[0, 0, 250])
Below is the complete implementation:
Python3
# Import the following modulesimport pytesseractfrom PIL import Imageimport osimport pywhatkit as kit # Change the directory to the# location where image is presentos.chdir(r"C:\Users\Dell\Downloads") # Set the Path of Tesseractpytesseract.pytesseract.tesseract_cmd = r"C:\Users\Dell\AppData\/Local\Tesseract-OCR\tesseract.exe" # Load the Imageimg = Image.open("GFG.png") # Convert Image to Texttext = pytesseract.image_to_string(img) # Convert Text to Hand Written Textkit.text_to_handwriting(text, rgb=[0, 0, 250])
Output:
Image-Processing
python-modules
Python-pil
python-utility
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
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 24459,
"s": 24318,
"text": "In this article, we are going to see how to convert text images to handwritten text images using PyWhatkit, Pillow, and Tesseract in Python."
},
{
"code": null,
"e": 24737,
"s": 24459,
"text": "Pytesseract: Sometimes known as Python-tesseract, is a Python-based optical character recognition (OCR) program. It can read and recognize text in photos, license plates, and other documents. To interpret the words from the provided image, we’ll utilize the tesseract software."
},
{
"code": null,
"e": 24761,
"s": 24737,
"text": "pip install pytesseract"
},
{
"code": null,
"e": 24940,
"s": 24761,
"text": "Pywhatkit: It is a library that may be used for a variety of things, including sending WhatsApp messages, watching YouTube videos, searching Google, and writing handwritten text."
},
{
"code": null,
"e": 24962,
"s": 24940,
"text": "pip install pywhatkit"
},
{
"code": null,
"e": 25248,
"s": 24962,
"text": "Pillow: This module adds more features, operates on all major operating systems, and has Python 3 support. It supports a broad range of image formats, including “jpeg,” “png,” “bmp,” “gif,” “ppm,” and “tiff.” With the pillow module, you can do nearly anything with digital photographs."
},
{
"code": null,
"e": 25267,
"s": 25248,
"text": "pip install Pillow"
},
{
"code": null,
"e": 25400,
"s": 25267,
"text": "Note: Visit and Install Tesseract; scroll down to find the latest installers for 32-bit and 64-bit systems; download them as needed."
},
{
"code": null,
"e": 25438,
"s": 25400,
"text": "Step 1: Import the following modules."
},
{
"code": null,
"e": 25446,
"s": 25438,
"text": "Python3"
},
{
"code": "import pytesseract from PIL import Image import osimport pywhatkit as kit",
"e": 25520,
"s": 25446,
"text": null
},
{
"code": null,
"e": 25651,
"s": 25520,
"text": "Step 2: Navigate to the path where the picture is located, the chdir function in the OS module can be used to alter the directory."
},
{
"code": null,
"e": 25659,
"s": 25651,
"text": "Python3"
},
{
"code": "os.chdir(r\"C:\\Users\\Dell\\Downloads\")",
"e": 25696,
"s": 25659,
"text": null
},
{
"code": null,
"e": 25824,
"s": 25696,
"text": "Step 3: Copy the installation path for Tesseract, paste it here, or verify the directory of Tesseract and copy the entire path."
},
{
"code": null,
"e": 25832,
"s": 25824,
"text": "Python3"
},
{
"code": "pytesseract.pytesseract.tesseract_cmd = r\"C:\\Users\\Dell\\AppData\\Local\\/Tesseract-OCR\\tesseract.exe\"",
"e": 25932,
"s": 25832,
"text": null
},
{
"code": null,
"e": 26075,
"s": 25932,
"text": "Step 4: First, open the image with the image function, then use pytesseract to get all the image’s data, and store all the text in a variable."
},
{
"code": null,
"e": 26083,
"s": 26075,
"text": "Python3"
},
{
"code": "img = Image.open(\"GFG.png\")text = pytesseract.image_to_string(img)",
"e": 26150,
"s": 26083,
"text": null
},
{
"code": null,
"e": 26300,
"s": 26150,
"text": "Step 5: Use the text _to_handwriting function from pywhatkit to convert text to the specified RGB color; in this case, the RGB for blue is 0, 0, 250."
},
{
"code": null,
"e": 26308,
"s": 26300,
"text": "Python3"
},
{
"code": "kit.text_to_handwriting(text, rgb=[0, 0, 250])",
"e": 26355,
"s": 26308,
"text": null
},
{
"code": null,
"e": 26393,
"s": 26355,
"text": "Below is the complete implementation:"
},
{
"code": null,
"e": 26401,
"s": 26393,
"text": "Python3"
},
{
"code": "# Import the following modulesimport pytesseractfrom PIL import Imageimport osimport pywhatkit as kit # Change the directory to the# location where image is presentos.chdir(r\"C:\\Users\\Dell\\Downloads\") # Set the Path of Tesseractpytesseract.pytesseract.tesseract_cmd = r\"C:\\Users\\Dell\\AppData\\/Local\\Tesseract-OCR\\tesseract.exe\" # Load the Imageimg = Image.open(\"GFG.png\") # Convert Image to Texttext = pytesseract.image_to_string(img) # Convert Text to Hand Written Textkit.text_to_handwriting(text, rgb=[0, 0, 250])",
"e": 26927,
"s": 26401,
"text": null
},
{
"code": null,
"e": 26935,
"s": 26927,
"text": "Output:"
},
{
"code": null,
"e": 26952,
"s": 26935,
"text": "Image-Processing"
},
{
"code": null,
"e": 26967,
"s": 26952,
"text": "python-modules"
},
{
"code": null,
"e": 26978,
"s": 26967,
"text": "Python-pil"
},
{
"code": null,
"e": 26993,
"s": 26978,
"text": "python-utility"
},
{
"code": null,
"e": 27000,
"s": 26993,
"text": "Python"
},
{
"code": null,
"e": 27098,
"s": 27000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27130,
"s": 27098,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27172,
"s": 27130,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27228,
"s": 27172,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27270,
"s": 27228,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27301,
"s": 27270,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27323,
"s": 27301,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27378,
"s": 27323,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27417,
"s": 27378,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27446,
"s": 27417,
"text": "Create a directory in Python"
}
] |
How can we set Mnemonic Key Radio Button in Java? | Mnemonic key is set so that a user can use Keyboard keys to select a Radio Button. For example, a key can be set with ALT −
radio2.setMnemonic(KeyEvent.VK_R);
Above, we have set key ALT+R for radio2.
The following is an example to set Mnemonic key radio button −
package my;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class SwingDemo {
public static void main(String[] args) {
JRadioButton radio1 = new JRadioButton("Male");
JRadioButton radio2 = new JRadioButton("Female");
radio2.setMnemonic(KeyEvent.VK_R);
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
radio1.setSelected(true);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Select Gender:"));
frame.add(radio1);
frame.add(radio2);
frame.pack();
frame.setVisible(true);
}
}
The output is as follows. When you will press Alt+R, you will be able to select the radio buttons. | [
{
"code": null,
"e": 1186,
"s": 1062,
"text": "Mnemonic key is set so that a user can use Keyboard keys to select a Radio Button. For example, a key can be set with ALT −"
},
{
"code": null,
"e": 1221,
"s": 1186,
"text": "radio2.setMnemonic(KeyEvent.VK_R);"
},
{
"code": null,
"e": 1262,
"s": 1221,
"text": "Above, we have set key ALT+R for radio2."
},
{
"code": null,
"e": 1325,
"s": 1262,
"text": "The following is an example to set Mnemonic key radio button −"
},
{
"code": null,
"e": 2153,
"s": 1325,
"text": "package my;\nimport java.awt.FlowLayout;\nimport java.awt.event.KeyEvent;\nimport javax.swing.ButtonGroup;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JRadioButton;\npublic class SwingDemo {\n public static void main(String[] args) {\n JRadioButton radio1 = new JRadioButton(\"Male\");\n JRadioButton radio2 = new JRadioButton(\"Female\");\n radio2.setMnemonic(KeyEvent.VK_R);\n ButtonGroup group = new ButtonGroup();\n group.add(radio1);\n group.add(radio2);\n radio1.setSelected(true);\n JFrame frame = new JFrame();\n frame.setLayout(new FlowLayout());\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(new JLabel(\"Select Gender:\"));\n frame.add(radio1);\n frame.add(radio2);\n frame.pack();\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 2252,
"s": 2153,
"text": "The output is as follows. When you will press Alt+R, you will be able to select the radio buttons."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.