title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Find day of the week for a given date - GeeksforGeeks | 21 Oct, 2021
Write a function that calculates the day of the week for any particular date in the past or future. A typical application is to calculate the day of the week on which someone was born or some other special event occurred.
Following is a simple function suggested by Sakamoto, Lachman, Keith and Craver to calculate day. The following function returns 0 for Sunday, 1 for Monday, etc.
Understanding the Maths:
14/09/1998
dd=14
mm=09
yyyy=1998 //non-leap year
Step 1: Informations to be remembered.
Magic Number Month array.
For Year: {0,3,3,6,1,4,6,2,5,0,3,5}
DAY array starting from 0-6: {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
Century Year Value: 1600-1699 = 6
1700-1799 = 4
1800-1899 = 2
1900-1999 = 0
2000-2099 = 6..
Step 2: Calculations as per the steps
Last 2 digits of the year: 98
Divide the above by 4: 24
Take the date(dd): 14
Take month value from array: 5 (for September month number 9)
Take century year value: 0 ( 1998 is in the range 1900-1999 thus 0)
-----
Sum: 141
Divide the Sum by 7 and get the remainder: 141 % 7 = 1
Check the Day array starting from index 0: Day[1] = Monday
**If leap year it will be the remainder-1
C++
C
Java
Python3
C#
PHP
Javascript
/* A program to find day of a given date */#include <bits/stdc++.h>using namespace std; int dayofweek(int d, int m, int y){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; return ( y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;} // Driver Codeint main(){ int day = dayofweek(30, 8, 2010); cout << day; return 0;} // This is code is contributed// by rathbhupendra
/* A program to find day of a given date */#include<stdio.h> int dayofweek(int d, int m, int y){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;} /* Driver function to test above function */int main(){ int day = dayofweek(30, 8, 2010); printf ("%d", day); return 0;}
/*This code will return the string value and the exact date * both for leap and non leap years*/import java.util.*;class FindDay { static int dd; static int mm; static int yyyy; FindDay(int dd, int mm, int yyyy) { this.dd = dd; this.mm = mm; this.yyyy = yyyy; } static int checkLeap(int y) { if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) return 1; else return 0; } static void calculate() { // Checking Leap year. If true then 1 else 0. int flag_for_leap = checkLeap(yyyy); /*Declaring and initialising the given informations * and arrays*/ String day[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; int m_no[] = { 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 }; /*Generalised check to find any Year Value*/ int j; if ((yyyy / 100) % 2 == 0) { if ((yyyy / 100) % 4 == 0) j = 6; else j = 2; } else { if (((yyyy / 100) - 1) % 4 == 0) j = 4; else j = 0; } /*THE FINAL FORMULA*/ int total = (yyyy % 100) + ((yyyy % 100) / 4) + dd + m_no[mm - 1] + j; if (flag_for_leap == 1) { if ((total % 7) > 0) System.out.println(day[(total % 7) - 1]); else System.out.println(day[6]); } else System.out.println(day[(total % 7)]); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); /*Take input in string format and then convert to * integer values*/ String date = sc.next(); String[] values = date.split("/"); new FindDay(Integer.parseInt(values[0]), Integer.parseInt(values[1]), Integer.parseInt(values[2])); calculate(); }}/*Contributed and written by Aniket Dey*/
# Python3 program to find day# of a given date def dayofweek(d, m, y): t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ] y -= m < 3 return (( y + int(y / 4) - int(y / 100) + int(y / 400) + t[m - 1] + d) % 7) # Driver Codeday = dayofweek(30, 8, 2010)print(day) # This code is contributed by Shreyanshi Arun.
// C# program to find day of a given dateusing System; class GFG { static int dayofweek(int d, int m, int y) { int []t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= (m < 3) ? 1 : 0; return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; } // Driver Program to test above function public static void Main() { int day = dayofweek(30, 8, 2010); Console.Write(day); }} // This code is contributed by Sam007.
<?php// PHP program to find// day of a given datefunction dayofweek($d, $m, $y){ static $t = array(0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4); $y -= $m < 3; return ($y + $y / 4 - $y / 100 + $y / 400 + $t[$m - 1] + $d) % 7;} // Driver Code$day = dayofweek(30, 8, 2010);echo $day; // This code is contributed by mits.?>
<script> // Javascript program to find day of a given date function dayofweek(d, m, y){ let t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ]; y -= (m < 3) ? 1 : 0; return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;} // Driver Code let day = dayofweek(30, 8, 2010); document.write(Math.round(day)); </script>
Output : 1 (Monday)
Time Complexity: O(1)See this for explanation of the above function.References: http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_weekThis article is compiled by Dheeraj Jain and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Mithun Kumar
RishabhJain16
rathbhupendra
code_hunt
mailaniketdey
subhammahato348
date-time-program
Morgan Stanley
Samsung
Mathematical
Morgan Stanley
Samsung
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Algorithm to solve Rubik's Cube
Write a program to calculate pow(x,n)
Efficient program to print all prime factors of a given number
The Knight's tour problem | Backtracking-1 | [
{
"code": null,
"e": 24690,
"s": 24662,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 24914,
"s": 24690,
"text": "Write a function that calculates the day of the week for any particular date in the past or future. A typical application is to calculate the day of the week on which someone was born or some other special event occurred. "
},
{
"code": null,
"e": 25078,
"s": 24914,
"text": "Following is a simple function suggested by Sakamoto, Lachman, Keith and Craver to calculate day. The following function returns 0 for Sunday, 1 for Monday, etc. "
},
{
"code": null,
"e": 25931,
"s": 25078,
"text": "Understanding the Maths:\n\n14/09/1998\ndd=14\nmm=09\nyyyy=1998 //non-leap year\n\nStep 1: Informations to be remembered.\n Magic Number Month array.\n For Year: {0,3,3,6,1,4,6,2,5,0,3,5}\n DAY array starting from 0-6: {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}\n Century Year Value: 1600-1699 = 6\n 1700-1799 = 4\n 1800-1899 = 2\n 1900-1999 = 0\n 2000-2099 = 6..\n\nStep 2: Calculations as per the steps\n \n Last 2 digits of the year: 98\n Divide the above by 4: 24\n Take the date(dd): 14\n Take month value from array: 5 (for September month number 9)\n Take century year value: 0 ( 1998 is in the range 1900-1999 thus 0)\n -----\n Sum: 141\n \n Divide the Sum by 7 and get the remainder: 141 % 7 = 1\n \n Check the Day array starting from index 0: Day[1] = Monday\n\n**If leap year it will be the remainder-1"
},
{
"code": null,
"e": 25935,
"s": 25931,
"text": "C++"
},
{
"code": null,
"e": 25937,
"s": 25935,
"text": "C"
},
{
"code": null,
"e": 25942,
"s": 25937,
"text": "Java"
},
{
"code": null,
"e": 25950,
"s": 25942,
"text": "Python3"
},
{
"code": null,
"e": 25953,
"s": 25950,
"text": "C#"
},
{
"code": null,
"e": 25957,
"s": 25953,
"text": "PHP"
},
{
"code": null,
"e": 25968,
"s": 25957,
"text": "Javascript"
},
{
"code": "/* A program to find day of a given date */#include <bits/stdc++.h>using namespace std; int dayofweek(int d, int m, int y){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; return ( y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;} // Driver Codeint main(){ int day = dayofweek(30, 8, 2010); cout << day; return 0;} // This is code is contributed// by rathbhupendra",
"e": 26409,
"s": 25968,
"text": null
},
{
"code": "/* A program to find day of a given date */#include<stdio.h> int dayofweek(int d, int m, int y){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;} /* Driver function to test above function */int main(){ int day = dayofweek(30, 8, 2010); printf (\"%d\", day); return 0;}",
"e": 26768,
"s": 26409,
"text": null
},
{
"code": "/*This code will return the string value and the exact date * both for leap and non leap years*/import java.util.*;class FindDay { static int dd; static int mm; static int yyyy; FindDay(int dd, int mm, int yyyy) { this.dd = dd; this.mm = mm; this.yyyy = yyyy; } static int checkLeap(int y) { if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) return 1; else return 0; } static void calculate() { // Checking Leap year. If true then 1 else 0. int flag_for_leap = checkLeap(yyyy); /*Declaring and initialising the given informations * and arrays*/ String day[] = { \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\" }; int m_no[] = { 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 }; /*Generalised check to find any Year Value*/ int j; if ((yyyy / 100) % 2 == 0) { if ((yyyy / 100) % 4 == 0) j = 6; else j = 2; } else { if (((yyyy / 100) - 1) % 4 == 0) j = 4; else j = 0; } /*THE FINAL FORMULA*/ int total = (yyyy % 100) + ((yyyy % 100) / 4) + dd + m_no[mm - 1] + j; if (flag_for_leap == 1) { if ((total % 7) > 0) System.out.println(day[(total % 7) - 1]); else System.out.println(day[6]); } else System.out.println(day[(total % 7)]); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); /*Take input in string format and then convert to * integer values*/ String date = sc.next(); String[] values = date.split(\"/\"); new FindDay(Integer.parseInt(values[0]), Integer.parseInt(values[1]), Integer.parseInt(values[2])); calculate(); }}/*Contributed and written by Aniket Dey*/",
"e": 28834,
"s": 26768,
"text": null
},
{
"code": "# Python3 program to find day# of a given date def dayofweek(d, m, y): t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ] y -= m < 3 return (( y + int(y / 4) - int(y / 100) + int(y / 400) + t[m - 1] + d) % 7) # Driver Codeday = dayofweek(30, 8, 2010)print(day) # This code is contributed by Shreyanshi Arun.",
"e": 29164,
"s": 28834,
"text": null
},
{
"code": "// C# program to find day of a given dateusing System; class GFG { static int dayofweek(int d, int m, int y) { int []t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= (m < 3) ? 1 : 0; return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7; } // Driver Program to test above function public static void Main() { int day = dayofweek(30, 8, 2010); Console.Write(day); }} // This code is contributed by Sam007.",
"e": 29701,
"s": 29164,
"text": null
},
{
"code": "<?php// PHP program to find// day of a given datefunction dayofweek($d, $m, $y){ static $t = array(0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4); $y -= $m < 3; return ($y + $y / 4 - $y / 100 + $y / 400 + $t[$m - 1] + $d) % 7;} // Driver Code$day = dayofweek(30, 8, 2010);echo $day; // This code is contributed by mits.?>",
"e": 30053,
"s": 29701,
"text": null
},
{
"code": "<script> // Javascript program to find day of a given date function dayofweek(d, m, y){ let t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ]; y -= (m < 3) ? 1 : 0; return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;} // Driver Code let day = dayofweek(30, 8, 2010); document.write(Math.round(day)); </script>",
"e": 30372,
"s": 30053,
"text": null
},
{
"code": null,
"e": 30392,
"s": 30372,
"text": "Output : 1 (Monday)"
},
{
"code": null,
"e": 30739,
"s": 30392,
"text": "Time Complexity: O(1)See this for explanation of the above function.References: http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_weekThis article is compiled by Dheeraj Jain and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 30752,
"s": 30739,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30766,
"s": 30752,
"text": "RishabhJain16"
},
{
"code": null,
"e": 30780,
"s": 30766,
"text": "rathbhupendra"
},
{
"code": null,
"e": 30790,
"s": 30780,
"text": "code_hunt"
},
{
"code": null,
"e": 30804,
"s": 30790,
"text": "mailaniketdey"
},
{
"code": null,
"e": 30820,
"s": 30804,
"text": "subhammahato348"
},
{
"code": null,
"e": 30838,
"s": 30820,
"text": "date-time-program"
},
{
"code": null,
"e": 30853,
"s": 30838,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30861,
"s": 30853,
"text": "Samsung"
},
{
"code": null,
"e": 30874,
"s": 30861,
"text": "Mathematical"
},
{
"code": null,
"e": 30889,
"s": 30874,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 30897,
"s": 30889,
"text": "Samsung"
},
{
"code": null,
"e": 30910,
"s": 30897,
"text": "Mathematical"
},
{
"code": null,
"e": 31008,
"s": 30910,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31017,
"s": 31008,
"text": "Comments"
},
{
"code": null,
"e": 31030,
"s": 31017,
"text": "Old Comments"
},
{
"code": null,
"e": 31073,
"s": 31030,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31097,
"s": 31073,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31111,
"s": 31097,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31160,
"s": 31111,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31181,
"s": 31160,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 31223,
"s": 31181,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 31255,
"s": 31223,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 31293,
"s": 31255,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 31356,
"s": 31293,
"text": "Efficient program to print all prime factors of a given number"
}
] |
What is the use of a double-click event in AngularJs? - GeeksforGeeks | 25 Jul, 2019
The ng-dblclick event in the AngularJS is useful for the HTML elements for getting the double click event, defined. In case a user wishes to get the function fired or other events when the double click of the HTML elements is done, then this event will be going to be needed. All the elements of the HTML will be going to support it.
Basically, the directive of ng-dblclick will be telling the AngularJS what exactly the HTML or the HTML elements need to do when it is double-clicked. However, it is not going to be overriding the original ondblclick event of the element, as both of them are going to be executed.
Syntax:
<element ng-dblclick="expression"> </element>
Parameter Values:
expression: The execution of the expression, when double-click is done on any element.Example: (The example is going to increase the value of the “count” of the variable, every time a double-click is done on the header.)<!DOCTYPE html> <html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <head> <title> AngularJS ng-dblclick Directive </title></head> <body style="text-align:center;" ng-app=""> <h1 style="color:green"> GeeksForGeeks </h1> <h2 style="color:purple"> ng-dblclick Directive </h2> <p>On the header given below, Double-Click on it.</p> <h1 style="color:#EA6964" ng-dblclick="count = count + 1" ng-init="count=0">Click</h1> <p>Double-Click has been done {{count}} times.</p> <p></p></body> </html>Output:My Personal Notes
arrow_drop_upSave
Example: (The example is going to increase the value of the “count” of the variable, every time a double-click is done on the header.)
<!DOCTYPE html> <html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <head> <title> AngularJS ng-dblclick Directive </title></head> <body style="text-align:center;" ng-app=""> <h1 style="color:green"> GeeksForGeeks </h1> <h2 style="color:purple"> ng-dblclick Directive </h2> <p>On the header given below, Double-Click on it.</p> <h1 style="color:#EA6964" ng-dblclick="count = count + 1" ng-init="count=0">Click</h1> <p>Double-Click has been done {{count}} times.</p> <p></p></body> </html>
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26464,
"s": 26436,
"text": "\n25 Jul, 2019"
},
{
"code": null,
"e": 26798,
"s": 26464,
"text": "The ng-dblclick event in the AngularJS is useful for the HTML elements for getting the double click event, defined. In case a user wishes to get the function fired or other events when the double click of the HTML elements is done, then this event will be going to be needed. All the elements of the HTML will be going to support it."
},
{
"code": null,
"e": 27079,
"s": 26798,
"text": "Basically, the directive of ng-dblclick will be telling the AngularJS what exactly the HTML or the HTML elements need to do when it is double-clicked. However, it is not going to be overriding the original ondblclick event of the element, as both of them are going to be executed."
},
{
"code": null,
"e": 27087,
"s": 27079,
"text": "Syntax:"
},
{
"code": null,
"e": 27134,
"s": 27087,
"text": "<element ng-dblclick=\"expression\"> </element>\n"
},
{
"code": null,
"e": 27152,
"s": 27134,
"text": "Parameter Values:"
},
{
"code": null,
"e": 28022,
"s": 27152,
"text": "expression: The execution of the expression, when double-click is done on any element.Example: (The example is going to increase the value of the “count” of the variable, every time a double-click is done on the header.)<!DOCTYPE html> <html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> <head> <title> AngularJS ng-dblclick Directive </title></head> <body style=\"text-align:center;\" ng-app=\"\"> <h1 style=\"color:green\"> GeeksForGeeks </h1> <h2 style=\"color:purple\"> ng-dblclick Directive </h2> <p>On the header given below, Double-Click on it.</p> <h1 style=\"color:#EA6964\" ng-dblclick=\"count = count + 1\" ng-init=\"count=0\">Click</h1> <p>Double-Click has been done {{count}} times.</p> <p></p></body> </html>Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28157,
"s": 28022,
"text": "Example: (The example is going to increase the value of the “count” of the variable, every time a double-click is done on the header.)"
},
{
"code": "<!DOCTYPE html> <html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> <head> <title> AngularJS ng-dblclick Directive </title></head> <body style=\"text-align:center;\" ng-app=\"\"> <h1 style=\"color:green\"> GeeksForGeeks </h1> <h2 style=\"color:purple\"> ng-dblclick Directive </h2> <p>On the header given below, Double-Click on it.</p> <h1 style=\"color:#EA6964\" ng-dblclick=\"count = count + 1\" ng-init=\"count=0\">Click</h1> <p>Double-Click has been done {{count}} times.</p> <p></p></body> </html>",
"e": 28765,
"s": 28157,
"text": null
},
{
"code": null,
"e": 28773,
"s": 28765,
"text": "Output:"
},
{
"code": null,
"e": 28788,
"s": 28773,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 28795,
"s": 28788,
"text": "Picked"
},
{
"code": null,
"e": 28805,
"s": 28795,
"text": "AngularJS"
},
{
"code": null,
"e": 28822,
"s": 28805,
"text": "Web Technologies"
},
{
"code": null,
"e": 28920,
"s": 28822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28955,
"s": 28920,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28990,
"s": 28955,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29025,
"s": 28990,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 29049,
"s": 29025,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29102,
"s": 29049,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29142,
"s": 29102,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29175,
"s": 29142,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29220,
"s": 29175,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29263,
"s": 29220,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to create a responsive inline form with CSS? | Following is the code to create a responsive inline form with CSS −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
* {
box-sizing: border-box;
}
form {
display: flex;
flex-flow: row wrap;
align-items: center;
}
form label {
margin: 5px 10px 5px 0;
}
form input {
margin: 5px 10px 5px 0;
padding: 10px;
}
form button {
padding: 10px 20px;
font-size: 20px;
background-color: rgb(39, 22, 141);
border: 1px solid #ddd;
color: white;
cursor: pointer;
font-weight: bolder;
border-radius: 4px;
}
form button:hover {
background-color: rgb(113, 65, 225);
}
@media (max-width: 800px) {
form input {
margin: 10px 0;
}
form {
flex-direction: column;
align-items: stretch;
}
}
</style>
</head>
<body>
<h1>Responsive Inline Form Example</h1>
<form>
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter email" name="email" />
<label for="pass">Password:</label>
<input type="password" id="pass" placeholder="Enter password" name="pass"/>
<button type="submit">Submit</button>
</form>
</body>
</html>
The above code will produce the following output −
On resizing the browser window the elements will reflow as follows − | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Following is the code to create a responsive inline form with CSS −"
},
{
"code": null,
"e": 1141,
"s": 1130,
"text": " Live Demo"
},
{
"code": null,
"e": 2284,
"s": 1141,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\nbody {\n font-family: Arial, Helvetica, sans-serif;\n}\n* {\n box-sizing: border-box;\n}\nform {\n display: flex;\n flex-flow: row wrap;\n align-items: center;\n}\nform label {\n margin: 5px 10px 5px 0;\n}\nform input {\n margin: 5px 10px 5px 0;\n padding: 10px;\n}\nform button {\n padding: 10px 20px;\n font-size: 20px;\n background-color: rgb(39, 22, 141);\n border: 1px solid #ddd;\n color: white;\n cursor: pointer;\n font-weight: bolder;\n border-radius: 4px;\n}\nform button:hover {\n background-color: rgb(113, 65, 225);\n}\n@media (max-width: 800px) {\n form input {\n margin: 10px 0;\n }\n form {\n flex-direction: column;\n align-items: stretch;\n }\n}\n</style>\n</head>\n<body>\n<h1>Responsive Inline Form Example</h1>\n<form>\n<label for=\"email\">Email:</label>\n<input type=\"email\" id=\"email\" placeholder=\"Enter email\" name=\"email\" />\n<label for=\"pass\">Password:</label>\n<input type=\"password\" id=\"pass\" placeholder=\"Enter password\" name=\"pass\"/>\n<button type=\"submit\">Submit</button>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 2335,
"s": 2284,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2404,
"s": 2335,
"text": "On resizing the browser window the elements will reflow as follows −"
}
] |
Find smallest number with given number of digits and sum of digits | 25 May, 2022
How to find the smallest number with given digit sum s and number of digits d? Examples :
Input : s = 9, d = 2
Output : 18
There are many other possible numbers
like 45, 54, 90, etc with sum of digits
as 9 and number of digits as 2. The
smallest of them is 18.
Input : s = 20, d = 3
Output : 299
A Simple Solution is to consider all m digit numbers and keep track of minimum number with digit sum as s. A close upper bound on time complexity of this solution is O(10m).There is a Greedy approach to solve the problem. The idea is to one by one fill all digits from rightmost to leftmost (or from least significant digit to most significant). We initially deduct 1 from sum s so that we have smallest digit at the end. After deducting 1, we apply greedy approach. We compare remaining sum with 9, if remaining sum is more than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits from right to left, we put the highest digits on the right side. Below is implementation of the idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the smallest number that can be// formed from given sum of digits and number of digits.#include <iostream>using namespace std; // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.void findSmallest(int m, int s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? cout << "Smallest number is " << 0 : cout << "Not possible"; return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { cout << "Not possible"; return ; } // Create an array to store digits of result int res[m]; // deduct sum by one to account for cases later // (There must be 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits (from right to left) for (int i=m-1; i>0; i--) { // If sum is still greater than 9, // digit must be 9. if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be the most significant // digit. res[0] = s + 1; // The initially subtracted 1 is // incorporated here. cout << "Smallest number is "; for (int i=0; i<m; i++) cout << res[i];} // Driver codeint main(){ int s = 9, m = 2; findSmallest(m, s); return 0;}
// Java program to find the smallest number that can be// formed from given sum of digits and number of digits class GFG{ // Function to print the smallest possible number with digit sum 's' // and 'm' number of digits static void findSmallest(int m, int s) { // If sum of digits is 0, then a number is possible // only if number of digits is 1 if (s == 0) { System.out.print(m == 1 ? "Smallest number is 0" : "Not possible"); return ; } // Sum greater than the maximum possible sum if (s > 9*m) { System.out.println("Not possible"); return ; } // Create an array to store digits of result int[] res = new int[m]; // deduct sum by one to account for cases later // (There must be 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits (from right to left) for (int i=m-1; i>0; i--) { // If sum is still greater than 9, // digit must be 9 if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be the most significant // digit res[0] = s + 1; // The initially subtracted 1 is // incorporated here System.out.print("Smallest number is "); for (int i=0; i<m; i++) System.out.print(res[i]); } // driver program public static void main (String[] args) { int s = 9, m = 2; findSmallest(m, s); }} // Contributed by Pramod Kumar
# Prints the smallest possible# number with digit sum 's'# and 'm' number of digits. def findSmallest(m,s): # If sum of digits is 0, # then a number is possible # only if number of digits is 1. if (s == 0): if(m == 1) : print("Smallest number is 0") else : print("Not possible") return # Sum greater than the # maximum possible sum. if (s > 9*m): print("Not possible") return # Create an array to # store digits of result res=[0 for i in range(m+1)] # deduct sum by one to # account for cases later # (There must be 1 left # for the most significant # digit) s -= 1 # Fill last m-1 digits # (from right to left) for i in range(m-1,0,-1): # If sum is still greater than 9, # digit must be 9. if (s > 9): res[i] = 9 s -= 9 else: res[i] = s s = 0 # Whatever is left should # be the most significant # digit. # The initially subtracted 1 is # incorporated here. res[0] = s + 1 print("Smallest number is ",end="") for i in range(m): print(res[i],end="") s = 9m = 2findSmallest(m, s) # This code is contributed# by Anant Agarwal.
// C# program to find the smallest// number that can be formed from// given sum of digits and number// of digitsusing System; class GFG{ // Function to print the smallest // possible number with digit sum 's' // and 'm' number of digits static void findSmallest(int m, int s) { // If sum of digits is 0, // then a number is possible // only if number of digits is 1 if (s == 0) { Console.Write(m == 1 ? "Smallest number is 0" : "Not possible"); return ; } // Sum greater than the // maximum possible sum if (s > 9 * m) { Console.Write("Not possible"); return ; } // Create an array to // store digits of result int []res = new int[m]; // deduct sum by one to account // for cases later (There must be // 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits // (from right to left) for (int i = m - 1; i > 0; i--) { // If sum is still greater // than 9, digit must be 9 if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be // the most significant digit // The initially subtracted 1 is // incorporated here res[0] = s + 1; Console.Write("Smallest number is "); for (int i = 0; i < m; i++) Console.Write(res[i]); } // Driver Code public static void Main () { int s = 9, m = 2; findSmallest(m, s); }} // This code is contributed by nitin mittal.
<?php// PHP program to find the smallest// number that can be formed from// given sum of digits and number// of digits. // Prints the smallest possible// number with digit sum 's'// and 'm' number of digits.function findSmallest($m, $s){ // If sum of digits is 0, then // a number is possible only if // number of digits is 1. if ($s == 0) { if(($m == 1) == true) echo "Smallest number is " , 0; else echo "Not possible"; return ; } // Sum greater than the // maximum possible sum. if ($s > 9 * $m) { echo "Not possible"; return ; } // Create an array to store // digits of result int res[m]; // deduct sum by one to account // for cases later (There must // be 1 left for the most // significant digit) $s -= 1; // Fill last m-1 digits // (from right to left) for ($i = $m - 1; $i > 0; $i--) { // If sum is still greater // than 9, digit must be 9. if ($s > 9) { $res[$i] = 9; $s -= 9; } else { $res[$i] = $s; $s = 0; } } // Whatever is left should be // the most significant digit. // The initially subtracted 1 // is incorporated here. $res[0] = $s + 1; echo "Smallest number is "; for ($i = 0; $i < $m; $i++) echo $res[$i];} // Driver code$s = 9; $m = 2;findSmallest($m, $s); // This code is contributed by ajit?>
<script> // Javascript program to find the smallest number that can be// formed from given sum of digits and number of digits. // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.function findSmallest(m, s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? document.write("Smallest number is ") + 0 : document.write("Not possible"); return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { document.write("Not possible"); return ; } // Create an array to store digits of result let res = new Array(m); // deduct sum by one to account for cases later // (There must be 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits (from right to left) for (let i=m-1; i>0; i--) { // If sum is still greater than 9, // digit must be 9. if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be the most significant // digit. res[0] = s + 1; // The initially subtracted 1 is // incorporated here. document.write("Smallest number is "); for (let i=0; i<m; i++) document.write(res[i]);} // Driver code let s = 9, m = 2; findSmallest(m, s); // This code is contributed by Mayank Tyagi </script>
Output :
Smallest number is 18
Time Complexity: O(m), where m represents the value of given integer.
Auxiliary Space: O(m), where m represents the value of given integer.
We will soon be discussing approach to find the largest possible number with given sum of digits and number of digits.This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
jit_t
mayanktyagi1709
tamanna17122007
MAQ Software
number-digits
Greedy
MAQ Software
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 146,
"s": 54,
"text": "How to find the smallest number with given digit sum s and number of digits d? Examples : "
},
{
"code": null,
"e": 357,
"s": 146,
"text": "Input : s = 9, d = 2\nOutput : 18\nThere are many other possible numbers \nlike 45, 54, 90, etc with sum of digits\nas 9 and number of digits as 2. The \nsmallest of them is 18.\n\nInput : s = 20, d = 3\nOutput : 299"
},
{
"code": null,
"e": 1081,
"s": 359,
"text": "A Simple Solution is to consider all m digit numbers and keep track of minimum number with digit sum as s. A close upper bound on time complexity of this solution is O(10m).There is a Greedy approach to solve the problem. The idea is to one by one fill all digits from rightmost to leftmost (or from least significant digit to most significant). We initially deduct 1 from sum s so that we have smallest digit at the end. After deducting 1, we apply greedy approach. We compare remaining sum with 9, if remaining sum is more than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits from right to left, we put the highest digits on the right side. Below is implementation of the idea. "
},
{
"code": null,
"e": 1085,
"s": 1081,
"text": "C++"
},
{
"code": null,
"e": 1090,
"s": 1085,
"text": "Java"
},
{
"code": null,
"e": 1098,
"s": 1090,
"text": "Python3"
},
{
"code": null,
"e": 1101,
"s": 1098,
"text": "C#"
},
{
"code": null,
"e": 1105,
"s": 1101,
"text": "PHP"
},
{
"code": null,
"e": 1116,
"s": 1105,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest number that can be// formed from given sum of digits and number of digits.#include <iostream>using namespace std; // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.void findSmallest(int m, int s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? cout << \"Smallest number is \" << 0 : cout << \"Not possible\"; return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { cout << \"Not possible\"; return ; } // Create an array to store digits of result int res[m]; // deduct sum by one to account for cases later // (There must be 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits (from right to left) for (int i=m-1; i>0; i--) { // If sum is still greater than 9, // digit must be 9. if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be the most significant // digit. res[0] = s + 1; // The initially subtracted 1 is // incorporated here. cout << \"Smallest number is \"; for (int i=0; i<m; i++) cout << res[i];} // Driver codeint main(){ int s = 9, m = 2; findSmallest(m, s); return 0;}",
"e": 2566,
"s": 1116,
"text": null
},
{
"code": "// Java program to find the smallest number that can be// formed from given sum of digits and number of digits class GFG{ // Function to print the smallest possible number with digit sum 's' // and 'm' number of digits static void findSmallest(int m, int s) { // If sum of digits is 0, then a number is possible // only if number of digits is 1 if (s == 0) { System.out.print(m == 1 ? \"Smallest number is 0\" : \"Not possible\"); return ; } // Sum greater than the maximum possible sum if (s > 9*m) { System.out.println(\"Not possible\"); return ; } // Create an array to store digits of result int[] res = new int[m]; // deduct sum by one to account for cases later // (There must be 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits (from right to left) for (int i=m-1; i>0; i--) { // If sum is still greater than 9, // digit must be 9 if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be the most significant // digit res[0] = s + 1; // The initially subtracted 1 is // incorporated here System.out.print(\"Smallest number is \"); for (int i=0; i<m; i++) System.out.print(res[i]); } // driver program public static void main (String[] args) { int s = 9, m = 2; findSmallest(m, s); }} // Contributed by Pramod Kumar",
"e": 4310,
"s": 2566,
"text": null
},
{
"code": "# Prints the smallest possible# number with digit sum 's'# and 'm' number of digits. def findSmallest(m,s): # If sum of digits is 0, # then a number is possible # only if number of digits is 1. if (s == 0): if(m == 1) : print(\"Smallest number is 0\") else : print(\"Not possible\") return # Sum greater than the # maximum possible sum. if (s > 9*m): print(\"Not possible\") return # Create an array to # store digits of result res=[0 for i in range(m+1)] # deduct sum by one to # account for cases later # (There must be 1 left # for the most significant # digit) s -= 1 # Fill last m-1 digits # (from right to left) for i in range(m-1,0,-1): # If sum is still greater than 9, # digit must be 9. if (s > 9): res[i] = 9 s -= 9 else: res[i] = s s = 0 # Whatever is left should # be the most significant # digit. # The initially subtracted 1 is # incorporated here. res[0] = s + 1 print(\"Smallest number is \",end=\"\") for i in range(m): print(res[i],end=\"\") s = 9m = 2findSmallest(m, s) # This code is contributed# by Anant Agarwal.",
"e": 5632,
"s": 4310,
"text": null
},
{
"code": "// C# program to find the smallest// number that can be formed from// given sum of digits and number// of digitsusing System; class GFG{ // Function to print the smallest // possible number with digit sum 's' // and 'm' number of digits static void findSmallest(int m, int s) { // If sum of digits is 0, // then a number is possible // only if number of digits is 1 if (s == 0) { Console.Write(m == 1 ? \"Smallest number is 0\" : \"Not possible\"); return ; } // Sum greater than the // maximum possible sum if (s > 9 * m) { Console.Write(\"Not possible\"); return ; } // Create an array to // store digits of result int []res = new int[m]; // deduct sum by one to account // for cases later (There must be // 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits // (from right to left) for (int i = m - 1; i > 0; i--) { // If sum is still greater // than 9, digit must be 9 if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be // the most significant digit // The initially subtracted 1 is // incorporated here res[0] = s + 1; Console.Write(\"Smallest number is \"); for (int i = 0; i < m; i++) Console.Write(res[i]); } // Driver Code public static void Main () { int s = 9, m = 2; findSmallest(m, s); }} // This code is contributed by nitin mittal.",
"e": 7493,
"s": 5632,
"text": null
},
{
"code": "<?php// PHP program to find the smallest// number that can be formed from// given sum of digits and number// of digits. // Prints the smallest possible// number with digit sum 's'// and 'm' number of digits.function findSmallest($m, $s){ // If sum of digits is 0, then // a number is possible only if // number of digits is 1. if ($s == 0) { if(($m == 1) == true) echo \"Smallest number is \" , 0; else echo \"Not possible\"; return ; } // Sum greater than the // maximum possible sum. if ($s > 9 * $m) { echo \"Not possible\"; return ; } // Create an array to store // digits of result int res[m]; // deduct sum by one to account // for cases later (There must // be 1 left for the most // significant digit) $s -= 1; // Fill last m-1 digits // (from right to left) for ($i = $m - 1; $i > 0; $i--) { // If sum is still greater // than 9, digit must be 9. if ($s > 9) { $res[$i] = 9; $s -= 9; } else { $res[$i] = $s; $s = 0; } } // Whatever is left should be // the most significant digit. // The initially subtracted 1 // is incorporated here. $res[0] = $s + 1; echo \"Smallest number is \"; for ($i = 0; $i < $m; $i++) echo $res[$i];} // Driver code$s = 9; $m = 2;findSmallest($m, $s); // This code is contributed by ajit?>",
"e": 8998,
"s": 7493,
"text": null
},
{
"code": "<script> // Javascript program to find the smallest number that can be// formed from given sum of digits and number of digits. // Prints the smallest possible number with digit sum 's'// and 'm' number of digits.function findSmallest(m, s){ // If sum of digits is 0, then a number is possible // only if number of digits is 1. if (s == 0) { (m == 1)? document.write(\"Smallest number is \") + 0 : document.write(\"Not possible\"); return ; } // Sum greater than the maximum possible sum. if (s > 9*m) { document.write(\"Not possible\"); return ; } // Create an array to store digits of result let res = new Array(m); // deduct sum by one to account for cases later // (There must be 1 left for the most significant // digit) s -= 1; // Fill last m-1 digits (from right to left) for (let i=m-1; i>0; i--) { // If sum is still greater than 9, // digit must be 9. if (s > 9) { res[i] = 9; s -= 9; } else { res[i] = s; s = 0; } } // Whatever is left should be the most significant // digit. res[0] = s + 1; // The initially subtracted 1 is // incorporated here. document.write(\"Smallest number is \"); for (let i=0; i<m; i++) document.write(res[i]);} // Driver code let s = 9, m = 2; findSmallest(m, s); // This code is contributed by Mayank Tyagi </script>",
"e": 10504,
"s": 8998,
"text": null
},
{
"code": null,
"e": 10515,
"s": 10504,
"text": "Output : "
},
{
"code": null,
"e": 10537,
"s": 10515,
"text": "Smallest number is 18"
},
{
"code": null,
"e": 10607,
"s": 10537,
"text": "Time Complexity: O(m), where m represents the value of given integer."
},
{
"code": null,
"e": 10677,
"s": 10607,
"text": "Auxiliary Space: O(m), where m represents the value of given integer."
},
{
"code": null,
"e": 11189,
"s": 10677,
"text": "We will soon be discussing approach to find the largest possible number with given sum of digits and number of digits.This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 11202,
"s": 11189,
"text": "nitin mittal"
},
{
"code": null,
"e": 11208,
"s": 11202,
"text": "jit_t"
},
{
"code": null,
"e": 11224,
"s": 11208,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 11240,
"s": 11224,
"text": "tamanna17122007"
},
{
"code": null,
"e": 11253,
"s": 11240,
"text": "MAQ Software"
},
{
"code": null,
"e": 11267,
"s": 11253,
"text": "number-digits"
},
{
"code": null,
"e": 11274,
"s": 11267,
"text": "Greedy"
},
{
"code": null,
"e": 11287,
"s": 11274,
"text": "MAQ Software"
},
{
"code": null,
"e": 11294,
"s": 11287,
"text": "Greedy"
}
] |
Python | Check if all the values in a list that are greater than a given value | 21 Nov, 2018
Given a list, print all the values in a list that are greater than the given valueExamples:
Input : list = [10, 20, 30, 40, 50]
given value = 20
Output : No
Input : list = [10, 20, 30, 40, 50]
given value = 5
Output : Yes
Method 1: Traversal of list
By traversing in the list, we can compare every element and check if all the elements in the given list are greater than the given value or not.
# python program to check if all # values in the list are greater # than val using traversal def check(list1, val): # traverse in the list for x in list1: # compare with all the values # with val if val>= x: return False return True # driver code list1 =[10, 20, 30, 40, 50, 60]val = 5if(check(list1, val)): print"Yes"else: print"No" val = 20 if(check(list1, val)): print"Yes"else: print"No"
Output:
Yes
No
Method 2: Using all() function:
Using all() function we can check if all values are greater than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false.
# python program to check if all # values in the list are greater# than val using all() function def check(list1, val): return(all(x > val for x in list1)) # driver code list1 =[10, 20, 30, 40, 50, 60]val = 5if(check(list1, val)): print"Yes"else: print"No" val = 20 if (check(list1, val)): print"Yes"else: print"No"
Output:
Yes
No
Python list-programs
python-list
Arrays
Python
python-list
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 120,
"s": 28,
"text": "Given a list, print all the values in a list that are greater than the given valueExamples:"
},
{
"code": null,
"e": 272,
"s": 120,
"text": "Input : list = [10, 20, 30, 40, 50] \n given value = 20 \nOutput : No\n\nInput : list = [10, 20, 30, 40, 50] \n given value = 5 \nOutput : Yes\n"
},
{
"code": null,
"e": 300,
"s": 272,
"text": "Method 1: Traversal of list"
},
{
"code": null,
"e": 445,
"s": 300,
"text": "By traversing in the list, we can compare every element and check if all the elements in the given list are greater than the given value or not."
},
{
"code": "# python program to check if all # values in the list are greater # than val using traversal def check(list1, val): # traverse in the list for x in list1: # compare with all the values # with val if val>= x: return False return True # driver code list1 =[10, 20, 30, 40, 50, 60]val = 5if(check(list1, val)): print\"Yes\"else: print\"No\" val = 20 if(check(list1, val)): print\"Yes\"else: print\"No\"",
"e": 912,
"s": 445,
"text": null
},
{
"code": null,
"e": 920,
"s": 912,
"text": "Output:"
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Yes\nNo\n"
},
{
"code": null,
"e": 960,
"s": 928,
"text": "Method 2: Using all() function:"
},
{
"code": null,
"e": 1171,
"s": 960,
"text": "Using all() function we can check if all values are greater than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false."
},
{
"code": "# python program to check if all # values in the list are greater# than val using all() function def check(list1, val): return(all(x > val for x in list1)) # driver code list1 =[10, 20, 30, 40, 50, 60]val = 5if(check(list1, val)): print\"Yes\"else: print\"No\" val = 20 if (check(list1, val)): print\"Yes\"else: print\"No\"",
"e": 1515,
"s": 1171,
"text": null
},
{
"code": null,
"e": 1523,
"s": 1515,
"text": "Output:"
},
{
"code": null,
"e": 1531,
"s": 1523,
"text": "Yes\nNo\n"
},
{
"code": null,
"e": 1552,
"s": 1531,
"text": "Python list-programs"
},
{
"code": null,
"e": 1564,
"s": 1552,
"text": "python-list"
},
{
"code": null,
"e": 1571,
"s": 1564,
"text": "Arrays"
},
{
"code": null,
"e": 1578,
"s": 1571,
"text": "Python"
},
{
"code": null,
"e": 1590,
"s": 1578,
"text": "python-list"
},
{
"code": null,
"e": 1597,
"s": 1590,
"text": "Arrays"
}
] |
ML | OPTICS Clustering Implementing using Sklearn | 14 Jul, 2019
Prerequisites: OPTICS Clustering
This article will demonstrate how to implement OPTICS Clustering technique using Sklearn in Python. The dataset used for the demonstration is the Mall Customer Segmentation Data which can be downloaded from Kaggle.
Step 1: Importing the required libraries
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import gridspecfrom sklearn.cluster import OPTICS, cluster_optics_dbscanfrom sklearn.preprocessing import normalize, StandardScaler
Step 2: Loading the Data
# Changing the working location to the location of the datacd C:\Users\Dev\Desktop\Kaggle\Customer Segmentation X = pd.read_csv('Mall_Customers.csv') # Dropping irrelevant columnsdrop_features = ['CustomerID', 'Gender']X = X.drop(drop_features, axis = 1) # Handling the missing values if anyX.fillna(method ='ffill', inplace = True) X.head()
Step 3: Preprocessing the Data
# Scaling the data to bring all the attributes to a comparable levelscaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the data so that the data# approximately follows a Gaussian distributionX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized) # Renaming the columnsX_normalized.columns = X.columns X_normalized.head()
Step 4: Building the Clustering Model
# Building the OPTICS Clustering modeloptics_model = OPTICS(min_samples = 10, xi = 0.05, min_cluster_size = 0.05) # Training the modeloptics_model.fit(X_normalized)
Step 5: Storing the results of the training
# Producing the labels according to the DBSCAN technique with eps = 0.5labels1 = cluster_optics_dbscan(reachability = optics_model.reachability_, core_distances = optics_model.core_distances_, ordering = optics_model.ordering_, eps = 0.5) # Producing the labels according to the DBSCAN technique with eps = 2.0labels2 = cluster_optics_dbscan(reachability = optics_model.reachability_, core_distances = optics_model.core_distances_, ordering = optics_model.ordering_, eps = 2) # Creating a numpy array with numbers at equal spaces till# the specified rangespace = np.arange(len(X_normalized)) # Storing the reachability distance of each pointreachability = optics_model.reachability_[optics_model.ordering_] # Storing the cluster labels of each pointlabels = optics_model.labels_[optics_model.ordering_] print(labels)
Step 6: Visualizing the results
# Defining the framework of the visualizationplt.figure(figsize =(10, 7))G = gridspec.GridSpec(2, 3)ax1 = plt.subplot(G[0, :])ax2 = plt.subplot(G[1, 0])ax3 = plt.subplot(G[1, 1])ax4 = plt.subplot(G[1, 2]) # Plotting the Reachability-Distance Plotcolors = ['c.', 'b.', 'r.', 'y.', 'g.']for Class, colour in zip(range(0, 5), colors): Xk = space[labels == Class] Rk = reachability[labels == Class] ax1.plot(Xk, Rk, colour, alpha = 0.3)ax1.plot(space[labels == -1], reachability[labels == -1], 'k.', alpha = 0.3)ax1.plot(space, np.full_like(space, 2., dtype = float), 'k-', alpha = 0.5)ax1.plot(space, np.full_like(space, 0.5, dtype = float), 'k-.', alpha = 0.5)ax1.set_ylabel('Reachability Distance')ax1.set_title('Reachability Plot') # Plotting the OPTICS Clusteringcolors = ['c.', 'b.', 'r.', 'y.', 'g.']for Class, colour in zip(range(0, 5), colors): Xk = X_normalized[optics_model.labels_ == Class] ax2.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3) ax2.plot(X_normalized.iloc[optics_model.labels_ == -1, 0], X_normalized.iloc[optics_model.labels_ == -1, 1], 'k+', alpha = 0.1)ax2.set_title('OPTICS Clustering') # Plotting the DBSCAN Clustering with eps = 0.5colors = ['c', 'b', 'r', 'y', 'g', 'greenyellow']for Class, colour in zip(range(0, 6), colors): Xk = X_normalized[labels1 == Class] ax3.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3, marker ='.') ax3.plot(X_normalized.iloc[labels1 == -1, 0], X_normalized.iloc[labels1 == -1, 1], 'k+', alpha = 0.1)ax3.set_title('DBSCAN clustering with eps = 0.5') # Plotting the DBSCAN Clustering with eps = 2.0colors = ['c.', 'y.', 'm.', 'g.']for Class, colour in zip(range(0, 4), colors): Xk = X_normalized.iloc[labels2 == Class] ax4.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3) ax4.plot(X_normalized.iloc[labels2 == -1, 0], X_normalized.iloc[labels2 == -1, 1], 'k+', alpha = 0.1)ax4.set_title('DBSCAN Clustering with eps = 2.0') plt.tight_layout()plt.show()
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 61,
"s": 28,
"text": "Prerequisites: OPTICS Clustering"
},
{
"code": null,
"e": 276,
"s": 61,
"text": "This article will demonstrate how to implement OPTICS Clustering technique using Sklearn in Python. The dataset used for the demonstration is the Mall Customer Segmentation Data which can be downloaded from Kaggle."
},
{
"code": null,
"e": 317,
"s": 276,
"text": "Step 1: Importing the required libraries"
},
{
"code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import gridspecfrom sklearn.cluster import OPTICS, cluster_optics_dbscanfrom sklearn.preprocessing import normalize, StandardScaler",
"e": 533,
"s": 317,
"text": null
},
{
"code": null,
"e": 558,
"s": 533,
"text": "Step 2: Loading the Data"
},
{
"code": "# Changing the working location to the location of the datacd C:\\Users\\Dev\\Desktop\\Kaggle\\Customer Segmentation X = pd.read_csv('Mall_Customers.csv') # Dropping irrelevant columnsdrop_features = ['CustomerID', 'Gender']X = X.drop(drop_features, axis = 1) # Handling the missing values if anyX.fillna(method ='ffill', inplace = True) X.head()",
"e": 904,
"s": 558,
"text": null
},
{
"code": null,
"e": 935,
"s": 904,
"text": "Step 3: Preprocessing the Data"
},
{
"code": "# Scaling the data to bring all the attributes to a comparable levelscaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the data so that the data# approximately follows a Gaussian distributionX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized) # Renaming the columnsX_normalized.columns = X.columns X_normalized.head()",
"e": 1357,
"s": 935,
"text": null
},
{
"code": null,
"e": 1395,
"s": 1357,
"text": "Step 4: Building the Clustering Model"
},
{
"code": "# Building the OPTICS Clustering modeloptics_model = OPTICS(min_samples = 10, xi = 0.05, min_cluster_size = 0.05) # Training the modeloptics_model.fit(X_normalized)",
"e": 1561,
"s": 1395,
"text": null
},
{
"code": null,
"e": 1605,
"s": 1561,
"text": "Step 5: Storing the results of the training"
},
{
"code": "# Producing the labels according to the DBSCAN technique with eps = 0.5labels1 = cluster_optics_dbscan(reachability = optics_model.reachability_, core_distances = optics_model.core_distances_, ordering = optics_model.ordering_, eps = 0.5) # Producing the labels according to the DBSCAN technique with eps = 2.0labels2 = cluster_optics_dbscan(reachability = optics_model.reachability_, core_distances = optics_model.core_distances_, ordering = optics_model.ordering_, eps = 2) # Creating a numpy array with numbers at equal spaces till# the specified rangespace = np.arange(len(X_normalized)) # Storing the reachability distance of each pointreachability = optics_model.reachability_[optics_model.ordering_] # Storing the cluster labels of each pointlabels = optics_model.labels_[optics_model.ordering_] print(labels)",
"e": 2563,
"s": 1605,
"text": null
},
{
"code": null,
"e": 2595,
"s": 2563,
"text": "Step 6: Visualizing the results"
},
{
"code": "# Defining the framework of the visualizationplt.figure(figsize =(10, 7))G = gridspec.GridSpec(2, 3)ax1 = plt.subplot(G[0, :])ax2 = plt.subplot(G[1, 0])ax3 = plt.subplot(G[1, 1])ax4 = plt.subplot(G[1, 2]) # Plotting the Reachability-Distance Plotcolors = ['c.', 'b.', 'r.', 'y.', 'g.']for Class, colour in zip(range(0, 5), colors): Xk = space[labels == Class] Rk = reachability[labels == Class] ax1.plot(Xk, Rk, colour, alpha = 0.3)ax1.plot(space[labels == -1], reachability[labels == -1], 'k.', alpha = 0.3)ax1.plot(space, np.full_like(space, 2., dtype = float), 'k-', alpha = 0.5)ax1.plot(space, np.full_like(space, 0.5, dtype = float), 'k-.', alpha = 0.5)ax1.set_ylabel('Reachability Distance')ax1.set_title('Reachability Plot') # Plotting the OPTICS Clusteringcolors = ['c.', 'b.', 'r.', 'y.', 'g.']for Class, colour in zip(range(0, 5), colors): Xk = X_normalized[optics_model.labels_ == Class] ax2.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3) ax2.plot(X_normalized.iloc[optics_model.labels_ == -1, 0], X_normalized.iloc[optics_model.labels_ == -1, 1], 'k+', alpha = 0.1)ax2.set_title('OPTICS Clustering') # Plotting the DBSCAN Clustering with eps = 0.5colors = ['c', 'b', 'r', 'y', 'g', 'greenyellow']for Class, colour in zip(range(0, 6), colors): Xk = X_normalized[labels1 == Class] ax3.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3, marker ='.') ax3.plot(X_normalized.iloc[labels1 == -1, 0], X_normalized.iloc[labels1 == -1, 1], 'k+', alpha = 0.1)ax3.set_title('DBSCAN clustering with eps = 0.5') # Plotting the DBSCAN Clustering with eps = 2.0colors = ['c.', 'y.', 'm.', 'g.']for Class, colour in zip(range(0, 4), colors): Xk = X_normalized.iloc[labels2 == Class] ax4.plot(Xk.iloc[:, 0], Xk.iloc[:, 1], colour, alpha = 0.3) ax4.plot(X_normalized.iloc[labels2 == -1, 0], X_normalized.iloc[labels2 == -1, 1], 'k+', alpha = 0.1)ax4.set_title('DBSCAN Clustering with eps = 2.0') plt.tight_layout()plt.show()",
"e": 4621,
"s": 2595,
"text": null
},
{
"code": null,
"e": 4638,
"s": 4621,
"text": "Machine Learning"
},
{
"code": null,
"e": 4645,
"s": 4638,
"text": "Python"
},
{
"code": null,
"e": 4662,
"s": 4645,
"text": "Machine Learning"
}
] |
Python | Pandas Series.argmax() | 27 Feb, 2019
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.argmax() function returns the row label of the maximum value in the given series object.
Syntax: Series.argmax(axis=0, skipna=True, *args, **kwargs)
Parameter :skipna : Exclude NA/null values. If the entire Series is NA, the result will be NA.axis : For compatibility with DataFrame.idxmax. Redundant for application on Series.*args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with NumPy.
Returns : idxmax : Index of maximum of values.
Example #1: Use Series.argmax() function to return the row label of the maximum value in the given series object
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([34, 5, 13, 32, 4, 15]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Coca Cola 34
Sprite 5
Coke 13
Fanta 32
Dew 4
ThumbsUp 15
dtype: int64
Now we will use Series.argmax() function to return the row label of the maximum value in the given series object.
# return the row label for# the maximum valueresult = sr.argmax() # Print the resultprint(result)
Output :
Coca Cola
As we can see in the output, the Series.argmax() function has successfully returned the row label of the maximum value in the given series object. Example #2 : Use Series.argmax() function to return the row label of the maximum value in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
2010-12-31 08:45:00 11.0
2011-12-31 08:45:00 21.0
2012-12-31 08:45:00 8.0
2013-12-31 08:45:00 18.0
2014-12-31 08:45:00 65.0
2015-12-31 08:45:00 18.0
2016-12-31 08:45:00 32.0
2017-12-31 08:45:00 10.0
2018-12-31 08:45:00 5.0
2019-12-31 08:45:00 32.0
2020-12-31 08:45:00 NaN
Freq: A-DEC, dtype: float64
Now we will use Series.argmax() function to return the row label of the maximum value in the given series object.
# return the row label for# the maximum valueresult = sr.argmax() # Print the resultprint(result)
Output :
2014-12-31 08:45:00
As we can see in the output, the Series.argmax() function has successfully returned the row label of the maximum value in the given series object.
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": "\n27 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"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": 388,
"s": 285,
"text": "Pandas Series.argmax() function returns the row label of the maximum value in the given series object."
},
{
"code": null,
"e": 448,
"s": 388,
"text": "Syntax: Series.argmax(axis=0, skipna=True, *args, **kwargs)"
},
{
"code": null,
"e": 731,
"s": 448,
"text": "Parameter :skipna : Exclude NA/null values. If the entire Series is NA, the result will be NA.axis : For compatibility with DataFrame.idxmax. Redundant for application on Series.*args, **kwargs : Additional keywords have no effect but might be accepted for compatibility with NumPy."
},
{
"code": null,
"e": 778,
"s": 731,
"text": "Returns : idxmax : Index of maximum of values."
},
{
"code": null,
"e": 891,
"s": 778,
"text": "Example #1: Use Series.argmax() function to return the row label of the maximum value in the given series object"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([34, 5, 13, 32, 4, 15]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1147,
"s": 891,
"text": null
},
{
"code": null,
"e": 1156,
"s": 1147,
"text": "Output :"
},
{
"code": null,
"e": 1265,
"s": 1156,
"text": "Coca Cola 34\nSprite 5\nCoke 13\nFanta 32\nDew 4\nThumbsUp 15\ndtype: int64"
},
{
"code": null,
"e": 1379,
"s": 1265,
"text": "Now we will use Series.argmax() function to return the row label of the maximum value in the given series object."
},
{
"code": "# return the row label for# the maximum valueresult = sr.argmax() # Print the resultprint(result)",
"e": 1478,
"s": 1379,
"text": null
},
{
"code": null,
"e": 1487,
"s": 1478,
"text": "Output :"
},
{
"code": null,
"e": 1497,
"s": 1487,
"text": "Coca Cola"
},
{
"code": null,
"e": 1759,
"s": 1497,
"text": "As we can see in the output, the Series.argmax() function has successfully returned the row label of the maximum value in the given series object. Example #2 : Use Series.argmax() function to return the row label of the maximum value in the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 2060,
"s": 1759,
"text": null
},
{
"code": null,
"e": 2069,
"s": 2060,
"text": "Output :"
},
{
"code": null,
"e": 2405,
"s": 2069,
"text": "2010-12-31 08:45:00 11.0\n2011-12-31 08:45:00 21.0\n2012-12-31 08:45:00 8.0\n2013-12-31 08:45:00 18.0\n2014-12-31 08:45:00 65.0\n2015-12-31 08:45:00 18.0\n2016-12-31 08:45:00 32.0\n2017-12-31 08:45:00 10.0\n2018-12-31 08:45:00 5.0\n2019-12-31 08:45:00 32.0\n2020-12-31 08:45:00 NaN\nFreq: A-DEC, dtype: float64"
},
{
"code": null,
"e": 2519,
"s": 2405,
"text": "Now we will use Series.argmax() function to return the row label of the maximum value in the given series object."
},
{
"code": "# return the row label for# the maximum valueresult = sr.argmax() # Print the resultprint(result)",
"e": 2618,
"s": 2519,
"text": null
},
{
"code": null,
"e": 2627,
"s": 2618,
"text": "Output :"
},
{
"code": null,
"e": 2647,
"s": 2627,
"text": "2014-12-31 08:45:00"
},
{
"code": null,
"e": 2794,
"s": 2647,
"text": "As we can see in the output, the Series.argmax() function has successfully returned the row label of the maximum value in the given series object."
},
{
"code": null,
"e": 2815,
"s": 2794,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2844,
"s": 2815,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2858,
"s": 2844,
"text": "Python-pandas"
},
{
"code": null,
"e": 2865,
"s": 2858,
"text": "Python"
}
] |
Python – Character coordinates in Matrix | 30 Dec, 2020
Sometimes, while working with Python data, we can have a problem in which we need to extract all the coordinates in Matrix, which are characters. This kind of problem can have potential application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [‘1G’, ’12F’, ‘231G’]Output : [(0, 1), (1, 2), (2, 3)]
Input : test_list = [‘G’, ‘F’, ‘G’]Output : [(0, 0), (1, 0), (2, 0)]
Method #1 : Using enumerate() + list comprehension + isalpha()The combination of above functions can be used to solve this problem. In this, we perform the task of working with indices using enumerate and characters filtering is done using isalpha().
# Python3 code to demonstrate working of # Character coordinates in Matrix# Using enumerate() + list comprehension + isalpha() # initializing listtest_list = ['23f45.;4d', '5678d56d', '789', '5678g'] # printing original listprint("The original list is : " + str(test_list)) # Character coordinates in Matrix# Using enumerate() + list comprehension + isalpha()res = [(x, y) for x, val in enumerate(test_list) for y, chr in enumerate(val) if chr.isalpha()] # printing result print("Character indices : " + str(res))
The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (0, 8), (1, 4), (1, 7), (3, 4)]
Method #2 : Using regex() + loopThe combination of above functions can be used to solve this problem. In this, we perform task of filtering alphabets using regex expressions. Just returns the first occurrence of character in each string.
# Python3 code to demonstrate working of # Character coordinates in Matrix# Using regex() + loopimport re # initializing listtest_list = ['23f45.;4d', '5678d56d', '789', '5678g'] # printing original listprint("The original list is : " + str(test_list)) # Character coordinates in Matrix# Using regex() + loopres = []for key, val in enumerate(test_list): temp = re.search('([a-zA-Z]+)', val) if temp : res.append((key, temp.start())) # printing result print("Character indices : " + str(res))
The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']
Character indices : [(0, 2), (1, 4), (3, 4)]
Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 350,
"s": 28,
"text": "Sometimes, while working with Python data, we can have a problem in which we need to extract all the coordinates in Matrix, which are characters. This kind of problem can have potential application in domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 425,
"s": 350,
"text": "Input : test_list = [‘1G’, ’12F’, ‘231G’]Output : [(0, 1), (1, 2), (2, 3)]"
},
{
"code": null,
"e": 494,
"s": 425,
"text": "Input : test_list = [‘G’, ‘F’, ‘G’]Output : [(0, 0), (1, 0), (2, 0)]"
},
{
"code": null,
"e": 745,
"s": 494,
"text": "Method #1 : Using enumerate() + list comprehension + isalpha()The combination of above functions can be used to solve this problem. In this, we perform the task of working with indices using enumerate and characters filtering is done using isalpha()."
},
{
"code": "# Python3 code to demonstrate working of # Character coordinates in Matrix# Using enumerate() + list comprehension + isalpha() # initializing listtest_list = ['23f45.;4d', '5678d56d', '789', '5678g'] # printing original listprint(\"The original list is : \" + str(test_list)) # Character coordinates in Matrix# Using enumerate() + list comprehension + isalpha()res = [(x, y) for x, val in enumerate(test_list) for y, chr in enumerate(val) if chr.isalpha()] # printing result print(\"Character indices : \" + str(res)) ",
"e": 1282,
"s": 745,
"text": null
},
{
"code": null,
"e": 1409,
"s": 1282,
"text": "The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']\nCharacter indices : [(0, 2), (0, 8), (1, 4), (1, 7), (3, 4)]\n"
},
{
"code": null,
"e": 1649,
"s": 1411,
"text": "Method #2 : Using regex() + loopThe combination of above functions can be used to solve this problem. In this, we perform task of filtering alphabets using regex expressions. Just returns the first occurrence of character in each string."
},
{
"code": "# Python3 code to demonstrate working of # Character coordinates in Matrix# Using regex() + loopimport re # initializing listtest_list = ['23f45.;4d', '5678d56d', '789', '5678g'] # printing original listprint(\"The original list is : \" + str(test_list)) # Character coordinates in Matrix# Using regex() + loopres = []for key, val in enumerate(test_list): temp = re.search('([a-zA-Z]+)', val) if temp : res.append((key, temp.start())) # printing result print(\"Character indices : \" + str(res)) ",
"e": 2175,
"s": 1649,
"text": null
},
{
"code": null,
"e": 2286,
"s": 2175,
"text": "The original list is : ['23f45.;4d', '5678d56d', '789', '5678g']\nCharacter indices : [(0, 2), (1, 4), (3, 4)]\n"
},
{
"code": null,
"e": 2307,
"s": 2286,
"text": "Python list-programs"
},
{
"code": null,
"e": 2329,
"s": 2307,
"text": "Python matrix-program"
},
{
"code": null,
"e": 2336,
"s": 2329,
"text": "Python"
},
{
"code": null,
"e": 2352,
"s": 2336,
"text": "Python Programs"
}
] |
Longest Repeating Subsequence | Practice | GeeksforGeeks | Given string str, find the length of the longest repeating subsequence such that it can be found twice in the given string.
The two identified subsequences A and B can use the same ith character from string str if and only if that ith character has different indices in A and B. For example, A = "xax" and B = "xax" then the index of first "x" must be different in the original string for A and B.
Example 1:
Input:
str = "axxzxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x z x y
0 1 2 3 4 5
The longest subsequence is "xx".
It appears twice as explained below.
subsequence A
x x
0 1 <-- index of subsequence A
------
1 2 <-- index of str
subsequence B
x x
0 1 <-- index of subsequence B
------
2 4 <-- index of str
We are able to use character 'x'
(at index 2 in str) in both subsequences
as it appears on index 1 in subsequence A
and index 0 in subsequence B.
Example 2:
Input:
str = "axxxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x x y
0 1 2 3 4
The longest subsequence is "xx".
It appears twice as explained below.
subsequence A
x x
0 1 <-- index of subsequence A
------
1 2 <-- index of str
subsequence B
x x
0 1 <-- index of subsequence B
------
2 3 <-- index of str
We are able to use character 'x'
(at index 2 in str) in both subsequences
as it appears on index 1 in subsequence A
and index 0 in subsequence B.
Your Task:
You don't need to read or print anything. Your task is to complete the LongestRepeatingSubsequence() which takes str as input parameter and returns the length of the longest repeating subsequnece.
Expected Time Complexity: O(n2)
Expected Space Complexity: O(n2)
Constraints:
1 <= |str| <= 103
-239
eeshagoyal2Admin10 months ago
The problem statement has been updated to avoid any ambiguity.
0
10ayushshuklain 8 hours
LCS DP C++
int LongestRepeatingSubsequence(string str){ // Code here int n=str.length(); int t[n+1][n+1]; string S=str; for(int i=0;i<=n;i++){ for(int j=0;j<=n;j++){ if(i==0||j==0){ t[i][j]=0; } } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(str[i-1]==S[j-1] && i!=j){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=max(t[i-1][j],t[i][j-1]); } } } return t[n][n]; }
0
user_hix315 hours ago
int LongestRepeatingSubsequence(string str){
// Code here
int n = str.size();
int dp[n+1][n+1];
memset( dp, 0, sizeof(dp) );// this is base case
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(str[i-1] == str[j-1] && i!=j){ //same character differnt index(similar to LCS)
dp[i][j] = dp[i-1][j-1]+1;
}
else{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);// usual dp concept of top down approch
}
}
}
return dp[n][n];// last corner will give solution top down concept
}
0
user_r1cs3 days ago
class Solution {public: int LongestRepeatingSubsequence(string str){ int n=str.length(); string str1=str; string str2=str; int t[n+1][n+1]; for(int i=0;i<n+1;i++){ for(int j=0;j<n+1;j++){ if(i==0){ t[i][j]=0; } if(j==0){ t[i][j]=0; } } } for(int i=1;i<n+1;i++){ for(int j=1;j<n+1;j++){ if(str1[i-1]==str2[j-1] && i!=j){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=max(t[i-1][j],t[i][j-1]); } } } return t[n][n]; }
};
0
absurajsinghchamiyal4 days ago
Neat and clean code
yaa! it's easy if you are GOD!
//--------TABULATION// Varaition of LCS // Hint : take two str (same) and find LCS such that i!=j
public class Solution { public int LongestRepeatingSubsequence(String str) { int n = str.length(); int dp[][] = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i != j && str.charAt(i - 1) == str.charAt(j - 1)) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } return dp[n][n]; }}// Time complexity : O(n^2)// Space complexity : O(n^2)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 363,
"s": 238,
"text": "Given string str, find the length of the longest repeating subsequence such that it can be found twice in the given string. "
},
{
"code": null,
"e": 637,
"s": 363,
"text": "The two identified subsequences A and B can use the same ith character from string str if and only if that ith character has different indices in A and B. For example, A = \"xax\" and B = \"xax\" then the index of first \"x\" must be different in the original string for A and B."
},
{
"code": null,
"e": 648,
"s": 637,
"text": "Example 1:"
},
{
"code": null,
"e": 1142,
"s": 648,
"text": "Input:\nstr = \"axxzxy\"\nOutput: 2\nExplanation:\nThe given array with indexes looks like\na x x z x y \n0 1 2 3 4 5\n\nThe longest subsequence is \"xx\". \nIt appears twice as explained below.\n\nsubsequence A\nx x\n0 1 <-- index of subsequence A\n------\n1 2 <-- index of str \n\n\nsubsequence B\nx x\n0 1 <-- index of subsequence B\n------\n2 4 <-- index of str \n\nWe are able to use character 'x' \n(at index 2 in str) in both subsequences\nas it appears on index 1 in subsequence A \nand index 0 in subsequence B."
},
{
"code": null,
"e": 1153,
"s": 1142,
"text": "Example 2:"
},
{
"code": null,
"e": 1642,
"s": 1153,
"text": "Input:\nstr = \"axxxy\"\nOutput: 2\nExplanation:\nThe given array with indexes looks like\na x x x y \n0 1 2 3 4\n\nThe longest subsequence is \"xx\". \nIt appears twice as explained below.\n\nsubsequence A\nx x\n0 1 <-- index of subsequence A\n------\n1 2 <-- index of str \n\n\nsubsequence B\nx x\n0 1 <-- index of subsequence B\n------\n2 3 <-- index of str \n\nWe are able to use character 'x' \n(at index 2 in str) in both subsequences\nas it appears on index 1 in subsequence A \nand index 0 in subsequence B."
},
{
"code": null,
"e": 1851,
"s": 1642,
"text": "\nYour Task:\nYou don't need to read or print anything. Your task is to complete the LongestRepeatingSubsequence() which takes str as input parameter and returns the length of the longest repeating subsequnece."
},
{
"code": null,
"e": 1917,
"s": 1851,
"text": "\nExpected Time Complexity: O(n2)\nExpected Space Complexity: O(n2)"
},
{
"code": null,
"e": 1949,
"s": 1917,
"text": "\nConstraints:\n1 <= |str| <= 103"
},
{
"code": null,
"e": 1954,
"s": 1949,
"text": "-239"
},
{
"code": null,
"e": 1984,
"s": 1954,
"text": "eeshagoyal2Admin10 months ago"
},
{
"code": null,
"e": 2048,
"s": 1984,
"text": "The problem statement has been updated to avoid any ambiguity. "
},
{
"code": null,
"e": 2050,
"s": 2048,
"text": "0"
},
{
"code": null,
"e": 2074,
"s": 2050,
"text": "10ayushshuklain 8 hours"
},
{
"code": null,
"e": 2085,
"s": 2074,
"text": "LCS DP C++"
},
{
"code": null,
"e": 2635,
"s": 2089,
"text": "int LongestRepeatingSubsequence(string str){ // Code here int n=str.length(); int t[n+1][n+1]; string S=str; for(int i=0;i<=n;i++){ for(int j=0;j<=n;j++){ if(i==0||j==0){ t[i][j]=0; } } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(str[i-1]==S[j-1] && i!=j){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=max(t[i-1][j],t[i][j-1]); } } } return t[n][n]; }"
},
{
"code": null,
"e": 2637,
"s": 2635,
"text": "0"
},
{
"code": null,
"e": 2659,
"s": 2637,
"text": "user_hix315 hours ago"
},
{
"code": null,
"e": 3283,
"s": 2659,
"text": "int LongestRepeatingSubsequence(string str){\n\t\t // Code here\n\t\t int n = str.size();\n\t\t int dp[n+1][n+1];\n\t\t memset( dp, 0, sizeof(dp) );// this is base case \n\t\t for(int i=1;i<=n;i++){\n\t\t for(int j=1;j<=n;j++){\n\t\t if(str[i-1] == str[j-1] && i!=j){ //same character differnt index(similar to LCS) \n\t\t dp[i][j] = dp[i-1][j-1]+1;\n\t\t }\n\t\t else{\n\t\t dp[i][j] = max(dp[i-1][j],dp[i][j-1]);// usual dp concept of top down approch\n\t\t }\n\t\t }\n\t\t }\n\t\t return dp[n][n];// last corner will give solution top down concept\n\t\t}"
},
{
"code": null,
"e": 3285,
"s": 3283,
"text": "0"
},
{
"code": null,
"e": 3305,
"s": 3285,
"text": "user_r1cs3 days ago"
},
{
"code": null,
"e": 3936,
"s": 3305,
"text": "class Solution {public: int LongestRepeatingSubsequence(string str){ int n=str.length(); string str1=str; string str2=str; int t[n+1][n+1]; for(int i=0;i<n+1;i++){ for(int j=0;j<n+1;j++){ if(i==0){ t[i][j]=0; } if(j==0){ t[i][j]=0; } } } for(int i=1;i<n+1;i++){ for(int j=1;j<n+1;j++){ if(str1[i-1]==str2[j-1] && i!=j){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=max(t[i-1][j],t[i][j-1]); } } } return t[n][n]; }"
},
{
"code": null,
"e": 3939,
"s": 3936,
"text": "};"
},
{
"code": null,
"e": 3941,
"s": 3939,
"text": "0"
},
{
"code": null,
"e": 3972,
"s": 3941,
"text": "absurajsinghchamiyal4 days ago"
},
{
"code": null,
"e": 3993,
"s": 3972,
"text": "Neat and clean code "
},
{
"code": null,
"e": 4025,
"s": 3993,
"text": "yaa! it's easy if you are GOD!"
},
{
"code": null,
"e": 4125,
"s": 4027,
"text": "//--------TABULATION// Varaition of LCS // Hint : take two str (same) and find LCS such that i!=j"
},
{
"code": null,
"e": 4660,
"s": 4125,
"text": "public class Solution { public int LongestRepeatingSubsequence(String str) { int n = str.length(); int dp[][] = new int[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i != j && str.charAt(i - 1) == str.charAt(j - 1)) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } return dp[n][n]; }}// Time complexity : O(n^2)// Space complexity : O(n^2)"
},
{
"code": null,
"e": 4806,
"s": 4660,
"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": 4842,
"s": 4806,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4852,
"s": 4842,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4862,
"s": 4852,
"text": "\nContest\n"
},
{
"code": null,
"e": 4925,
"s": 4862,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5110,
"s": 4925,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5394,
"s": 5110,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 5540,
"s": 5394,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 5617,
"s": 5540,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5658,
"s": 5617,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5686,
"s": 5658,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5757,
"s": 5686,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5944,
"s": 5757,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Taking Linux System Snapshots with Timeshift | 02 Feb, 2021
Timeshift is a Linux application that is built for providing functionality to restore your system just like when you restore a Windows system. Timeshift makes snapshots of your system in regular intervals which are further used at the time of restoration or undo all changes in the system.
Each Snapshot taken by Timeshift is a complete system backup that can be located in a file system. Timeshift is designed to protect system files and settings where user files such as documents, pictures, and music are excluded.
Timeshift is easy to use and install, you can directly start taking snapshots after installation and there is no need to do other configuration setups.
Snapshots are saved in the root partition in directory /timeshift as default. To avoid any uncertainty it is best to save snapshots in external storage mediums.
Timeshift creates boot snapshots that provide an additional level of backup and are created every time the system starts. Boot snapshots created by Timeshift have a delay of 10 minutes so that the system boot process is not affected.
Installing Timeshift is simple, you can use your terminal and add the repository to install it or you can download the file from the official website and install it after extracting it.
To install Timeshift in Ubuntu-based distributions use the following commands:
sudo add-apt-repository -y ppa:teejee2008/ppa
Before installing the tool please update your apt-get:
sudo apt-get update
sudo apt-get install timeshift
If you are using other Linux distributions then you can download the installer from https://github.com/teejee2008/Timeshift/releases.
Linux’s distributions do come with a default package installer for .deb files, you can simply click install and complete the installation. However, if you do not have a package installer you can use the following command:
sudo sh ./timeshift.deb
Where ./timeshift.deb will be your complete file name.
Firstly there are two types of snapshots supported by Timeshift
Rsync: Supports rsync snapshots in all systemsBTRFS: Supports BTRFS snapshots in BTRFS systems
Rsync: Supports rsync snapshots in all systems
BTRFS: Supports BTRFS snapshots in BTRFS systems
If you are using a BTRFS system then please make sure you use the BTRFS type of snapshot. However, by default systems support Rsync mode.
Step 1: Once you launch your time shift instance you can see an interface with several options like create, restore, and so on.
Step 2: First go to your settings and select the location for the drive you want to create a snapshot of.
Step 3: After selecting location click schedule, there you can schedule time intervals which will help to create snapshots on periods of time so if any uncertainty happens you have a backup available.
Step 4: When you have done configuring your settings click on create a snapshot to make a recovery snapshot. It will take a few minutes and you will have your recovery file ready.
When the creation process is complete you will be able to see the recovery file ready to be recovered. You can also save the recovery file in an external drive so that you do not lose the recovery file also in case of uncertainty.
It is suggested that you keep settings default for your recovery. However, a question arises that what to do if you are not even able to login into your system and have no control over it?
In such cases, you can create a live bootable USB device of Ubuntu, launch the live instance, connect it to the network and install Timeshift in it. Locate the recovery file and use it to recover your system. Since! Timeshift creates complete system recovery files it is easier to recover systems that lose the ability to log in.
Linux-Tools
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
chmod command in Linux with examples
nohup Command in Linux with Examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "Timeshift is a Linux application that is built for providing functionality to restore your system just like when you restore a Windows system. Timeshift makes snapshots of your system in regular intervals which are further used at the time of restoration or undo all changes in the system."
},
{
"code": null,
"e": 546,
"s": 318,
"text": "Each Snapshot taken by Timeshift is a complete system backup that can be located in a file system. Timeshift is designed to protect system files and settings where user files such as documents, pictures, and music are excluded."
},
{
"code": null,
"e": 698,
"s": 546,
"text": "Timeshift is easy to use and install, you can directly start taking snapshots after installation and there is no need to do other configuration setups."
},
{
"code": null,
"e": 859,
"s": 698,
"text": "Snapshots are saved in the root partition in directory /timeshift as default. To avoid any uncertainty it is best to save snapshots in external storage mediums."
},
{
"code": null,
"e": 1093,
"s": 859,
"text": "Timeshift creates boot snapshots that provide an additional level of backup and are created every time the system starts. Boot snapshots created by Timeshift have a delay of 10 minutes so that the system boot process is not affected."
},
{
"code": null,
"e": 1280,
"s": 1093,
"text": "Installing Timeshift is simple, you can use your terminal and add the repository to install it or you can download the file from the official website and install it after extracting it. "
},
{
"code": null,
"e": 1359,
"s": 1280,
"text": "To install Timeshift in Ubuntu-based distributions use the following commands:"
},
{
"code": null,
"e": 1405,
"s": 1359,
"text": "sudo add-apt-repository -y ppa:teejee2008/ppa"
},
{
"code": null,
"e": 1460,
"s": 1405,
"text": "Before installing the tool please update your apt-get:"
},
{
"code": null,
"e": 1511,
"s": 1460,
"text": "sudo apt-get update\nsudo apt-get install timeshift"
},
{
"code": null,
"e": 1645,
"s": 1511,
"text": "If you are using other Linux distributions then you can download the installer from https://github.com/teejee2008/Timeshift/releases."
},
{
"code": null,
"e": 1867,
"s": 1645,
"text": "Linux’s distributions do come with a default package installer for .deb files, you can simply click install and complete the installation. However, if you do not have a package installer you can use the following command:"
},
{
"code": null,
"e": 1891,
"s": 1867,
"text": "sudo sh ./timeshift.deb"
},
{
"code": null,
"e": 1947,
"s": 1891,
"text": "Where ./timeshift.deb will be your complete file name. "
},
{
"code": null,
"e": 2011,
"s": 1947,
"text": "Firstly there are two types of snapshots supported by Timeshift"
},
{
"code": null,
"e": 2106,
"s": 2011,
"text": "Rsync: Supports rsync snapshots in all systemsBTRFS: Supports BTRFS snapshots in BTRFS systems"
},
{
"code": null,
"e": 2153,
"s": 2106,
"text": "Rsync: Supports rsync snapshots in all systems"
},
{
"code": null,
"e": 2202,
"s": 2153,
"text": "BTRFS: Supports BTRFS snapshots in BTRFS systems"
},
{
"code": null,
"e": 2341,
"s": 2202,
"text": "If you are using a BTRFS system then please make sure you use the BTRFS type of snapshot. However, by default systems support Rsync mode. "
},
{
"code": null,
"e": 2470,
"s": 2341,
"text": "Step 1: Once you launch your time shift instance you can see an interface with several options like create, restore, and so on. "
},
{
"code": null,
"e": 2577,
"s": 2470,
"text": "Step 2: First go to your settings and select the location for the drive you want to create a snapshot of. "
},
{
"code": null,
"e": 2779,
"s": 2577,
"text": "Step 3: After selecting location click schedule, there you can schedule time intervals which will help to create snapshots on periods of time so if any uncertainty happens you have a backup available. "
},
{
"code": null,
"e": 2959,
"s": 2779,
"text": "Step 4: When you have done configuring your settings click on create a snapshot to make a recovery snapshot. It will take a few minutes and you will have your recovery file ready."
},
{
"code": null,
"e": 3191,
"s": 2959,
"text": "When the creation process is complete you will be able to see the recovery file ready to be recovered. You can also save the recovery file in an external drive so that you do not lose the recovery file also in case of uncertainty. "
},
{
"code": null,
"e": 3380,
"s": 3191,
"text": "It is suggested that you keep settings default for your recovery. However, a question arises that what to do if you are not even able to login into your system and have no control over it?"
},
{
"code": null,
"e": 3710,
"s": 3380,
"text": "In such cases, you can create a live bootable USB device of Ubuntu, launch the live instance, connect it to the network and install Timeshift in it. Locate the recovery file and use it to recover your system. Since! Timeshift creates complete system recovery files it is easier to recover systems that lose the ability to log in."
},
{
"code": null,
"e": 3722,
"s": 3710,
"text": "Linux-Tools"
},
{
"code": null,
"e": 3729,
"s": 3722,
"text": "Picked"
},
{
"code": null,
"e": 3740,
"s": 3729,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3838,
"s": 3740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3864,
"s": 3838,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3899,
"s": 3864,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3936,
"s": 3899,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3975,
"s": 3936,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 4004,
"s": 3975,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 4041,
"s": 4004,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 4078,
"s": 4041,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 4112,
"s": 4078,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 4152,
"s": 4112,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
Extract dominant colors of an image using Python | 17 May, 2022
Let us see how to extract the dominant colors of an image using Python. Clustering is used in much real-world application, one such real-world example of clustering is extracting dominant colors from an image.
Any image consists of pixels, each pixel represents a dot in an image. A pixel contains three values and each value ranges between 0 to 255, representing the amount of red, green and blue components. The combination of these forms an actual color of the pixel. To find the dominant colors, the concept of the k-means clustering is used. One important use of k-means clustering is to segment satellite images to identify surface features.
Below shown satellite image contains the terrain of a river valley.
The terrain of the river valley
Various colors typically belong to different features, k-means clustering can be used to cluster them into groups which can then be identified into various surfaces like water, vegetation etc as shown below.
Clustered groups (water, open land, ...)
matplotlib.image.imread – It converts JPEG image into a matrix which contains RGB values of each pixel.
matplotlib.pyplot.imshow – This method would display colors of the cluster centers after k-means clustering performed on RGB values.
Lets now dive into an example, performing k-means clustering on the following image:
Example image
As it can be seen that there are three dominant colors in this image, a shade of blue, a shade of red and black.
Step 1 : The first step in the process is to convert the image to pixels using imread method of image class.
Python3
# Import image class of matplotlibimport matplotlib.image as img # Read batman image and print dimensionsbatman_image = img.imread('batman.png')print(batman_image.shape)
Output :
(187, 295, 4)
The output is M*N*3 matrix where M and N are the dimensions of the image.
Step 2 : In this analysis, we are going to collectively look at all pixels regardless of there positions. So in this step, all the RGB values are extracted and stored in their corresponding lists. Once the lists are created, they are stored into the Pandas DataFrame, and then scale the DataFrame to get standardized values.
Python3
# Importing the modulesimport pandas as pdfrom scipy.cluster.vq import whiten # Store RGB values of all pixels in lists r, g and br = []g = []b = []for row in batman_image: for temp_r, temp_g, temp_b, temp in row: r.append(temp_r) g.append(temp_g) b.append(temp_b) # only printing the size of these lists# as the content is too bigprint(len(r))print(len(g))print(len(b)) # Saving as DataFramebatman_df = pd.DataFrame({'red' : r, 'green' : g, 'blue' : b}) # Scaling the valuesbatman_df['scaled_color_red'] = whiten(batman_df['red'])batman_df['scaled_color_blue'] = whiten(batman_df['blue'])batman_df['scaled_color_green'] = whiten(batman_df['green'])
Output :
55165
55165
55165
Step 3 : Now, to find the number of clusters in k-means using the elbow plot approach . This is not an absolute method to find the number of clusters but helps in giving an indication about the clusters.
Elbow plot: a line plot between cluster centers and distortion (the sum of the squared differences between the observations and the corresponding centroid).
Below is the code to generate the elbow plot:
Python3
# Preparing data to construct elbow plot.distortions = []num_clusters = range(1, 7) #range of cluster sizes # Create a list of distortions from the kmeans functionfor i in num_clusters: cluster_centers, distortion = kmeans(batman_df[['scaled_color_red', 'scaled_color_blue', 'scaled_color_green']], i) distortions.append(distortion) # Create a data frame with two lists, num_clusters and distortionselbow_plot = pd.DataFrame({'num_clusters' : num_clusters, 'distortions' : distortions}) # Create a line plot of num_clusters and distortionssns.lineplot(x = 'num_clusters', y = 'distortions', data = elbow_plot)plt.xticks(num_clusters)plt.show()
Elbow plot is plotted as shown below :
Output :
Elbow plot
It can be seen that a proper elbow is formed at 3 on the x-axis, which means the number of clusters is equal to 3 (there are three dominant colors in the given image).
Step 4 : The cluster centers obtained are standardized RGB values.
Standardized value = Actual value / Standard Deviation
Dominant colors are displayed using imshow() method, which takes RGB values scaled to the range of 0 to 1. To do so, you need to multiply the standardized values of the cluster centers with there corresponding standard deviations. Since the actual RGB values take the maximum range of 255, the multiplied result is divided by 255 to get scaled values in the range 0-1.
Python3
cluster_centers, _ = kmeans(batman_df[['scaled_color_red', 'scaled_color_blue', 'scaled_color_green']], 3) dominant_colors = [] # Get standard deviations of each colorred_std, green_std, blue_std = batman_df[['red', 'green', 'blue']].std() for cluster_center in cluster_centers: red_scaled, green_scaled, blue_scaled = cluster_center # Convert each standardized value to scaled value dominant_colors.append(( red_scaled * red_std / 255, green_scaled * green_std / 255, blue_scaled * blue_std / 255 )) # Display colors of cluster centersplt.imshow([dominant_colors])plt.show()
Here is the resultant plot showing the three dominant colors of the given image.
Output :
Plot showing dominant colors
Notice the three colors resemble the three that are indicative from visual inspection of the image.
Below is the full code without the comments :
Python3
import matplotlib.image as imgimport matplotlib.pyplot as pltfrom scipy.cluster.vq import whitenfrom scipy.cluster.vq import kmeansimport pandas as pd batman_image = img.imread('batman.jpg') r = []g = []b = []for row in batman_image: for temp_r, temp_g, temp_b, temp in row: r.append(temp_r) g.append(temp_g) b.append(temp_b) batman_df = pd.DataFrame({'red' : r, 'green' : g, 'blue' : b}) batman_df['scaled_color_red'] = whiten(batman_df['red'])batman_df['scaled_color_blue'] = whiten(batman_df['blue'])batman_df['scaled_color_green'] = whiten(batman_df['green']) cluster_centers, _ = kmeans(batman_df[['scaled_color_red', 'scaled_color_blue', 'scaled_color_green']], 3) dominant_colors = [] red_std, green_std, blue_std = batman_df[['red', 'green', 'blue']].std() for cluster_center in cluster_centers: red_scaled, green_scaled, blue_scaled = cluster_center dominant_colors.append(( red_scaled * red_std / 255, green_scaled * green_std / 255, blue_scaled * blue_std / 255 )) plt.imshow([dominant_colors])plt.show()
anikaseth98
Image-Processing
Python-matplotlib
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 May, 2022"
},
{
"code": null,
"e": 265,
"s": 54,
"text": "Let us see how to extract the dominant colors of an image using Python. Clustering is used in much real-world application, one such real-world example of clustering is extracting dominant colors from an image. "
},
{
"code": null,
"e": 704,
"s": 265,
"text": "Any image consists of pixels, each pixel represents a dot in an image. A pixel contains three values and each value ranges between 0 to 255, representing the amount of red, green and blue components. The combination of these forms an actual color of the pixel. To find the dominant colors, the concept of the k-means clustering is used. One important use of k-means clustering is to segment satellite images to identify surface features. "
},
{
"code": null,
"e": 772,
"s": 704,
"text": "Below shown satellite image contains the terrain of a river valley."
},
{
"code": null,
"e": 804,
"s": 772,
"text": "The terrain of the river valley"
},
{
"code": null,
"e": 1012,
"s": 804,
"text": "Various colors typically belong to different features, k-means clustering can be used to cluster them into groups which can then be identified into various surfaces like water, vegetation etc as shown below."
},
{
"code": null,
"e": 1053,
"s": 1012,
"text": "Clustered groups (water, open land, ...)"
},
{
"code": null,
"e": 1157,
"s": 1053,
"text": "matplotlib.image.imread – It converts JPEG image into a matrix which contains RGB values of each pixel."
},
{
"code": null,
"e": 1290,
"s": 1157,
"text": "matplotlib.pyplot.imshow – This method would display colors of the cluster centers after k-means clustering performed on RGB values."
},
{
"code": null,
"e": 1375,
"s": 1290,
"text": "Lets now dive into an example, performing k-means clustering on the following image:"
},
{
"code": null,
"e": 1389,
"s": 1375,
"text": "Example image"
},
{
"code": null,
"e": 1502,
"s": 1389,
"text": "As it can be seen that there are three dominant colors in this image, a shade of blue, a shade of red and black."
},
{
"code": null,
"e": 1611,
"s": 1502,
"text": "Step 1 : The first step in the process is to convert the image to pixels using imread method of image class."
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Python3"
},
{
"code": "# Import image class of matplotlibimport matplotlib.image as img # Read batman image and print dimensionsbatman_image = img.imread('batman.png')print(batman_image.shape)",
"e": 1790,
"s": 1619,
"text": null
},
{
"code": null,
"e": 1799,
"s": 1790,
"text": "Output :"
},
{
"code": null,
"e": 1813,
"s": 1799,
"text": "(187, 295, 4)"
},
{
"code": null,
"e": 1887,
"s": 1813,
"text": "The output is M*N*3 matrix where M and N are the dimensions of the image."
},
{
"code": null,
"e": 2212,
"s": 1887,
"text": "Step 2 : In this analysis, we are going to collectively look at all pixels regardless of there positions. So in this step, all the RGB values are extracted and stored in their corresponding lists. Once the lists are created, they are stored into the Pandas DataFrame, and then scale the DataFrame to get standardized values."
},
{
"code": null,
"e": 2220,
"s": 2212,
"text": "Python3"
},
{
"code": "# Importing the modulesimport pandas as pdfrom scipy.cluster.vq import whiten # Store RGB values of all pixels in lists r, g and br = []g = []b = []for row in batman_image: for temp_r, temp_g, temp_b, temp in row: r.append(temp_r) g.append(temp_g) b.append(temp_b) # only printing the size of these lists# as the content is too bigprint(len(r))print(len(g))print(len(b)) # Saving as DataFramebatman_df = pd.DataFrame({'red' : r, 'green' : g, 'blue' : b}) # Scaling the valuesbatman_df['scaled_color_red'] = whiten(batman_df['red'])batman_df['scaled_color_blue'] = whiten(batman_df['blue'])batman_df['scaled_color_green'] = whiten(batman_df['green'])",
"e": 2948,
"s": 2220,
"text": null
},
{
"code": null,
"e": 2959,
"s": 2948,
"text": "Output : "
},
{
"code": null,
"e": 2977,
"s": 2959,
"text": "55165\n55165\n55165"
},
{
"code": null,
"e": 3181,
"s": 2977,
"text": "Step 3 : Now, to find the number of clusters in k-means using the elbow plot approach . This is not an absolute method to find the number of clusters but helps in giving an indication about the clusters."
},
{
"code": null,
"e": 3338,
"s": 3181,
"text": "Elbow plot: a line plot between cluster centers and distortion (the sum of the squared differences between the observations and the corresponding centroid)."
},
{
"code": null,
"e": 3385,
"s": 3338,
"text": " Below is the code to generate the elbow plot:"
},
{
"code": null,
"e": 3393,
"s": 3385,
"text": "Python3"
},
{
"code": "# Preparing data to construct elbow plot.distortions = []num_clusters = range(1, 7) #range of cluster sizes # Create a list of distortions from the kmeans functionfor i in num_clusters: cluster_centers, distortion = kmeans(batman_df[['scaled_color_red', 'scaled_color_blue', 'scaled_color_green']], i) distortions.append(distortion) # Create a data frame with two lists, num_clusters and distortionselbow_plot = pd.DataFrame({'num_clusters' : num_clusters, 'distortions' : distortions}) # Create a line plot of num_clusters and distortionssns.lineplot(x = 'num_clusters', y = 'distortions', data = elbow_plot)plt.xticks(num_clusters)plt.show()",
"e": 4181,
"s": 3393,
"text": null
},
{
"code": null,
"e": 4220,
"s": 4181,
"text": "Elbow plot is plotted as shown below :"
},
{
"code": null,
"e": 4231,
"s": 4220,
"text": "Output : "
},
{
"code": null,
"e": 4242,
"s": 4231,
"text": "Elbow plot"
},
{
"code": null,
"e": 4412,
"s": 4244,
"text": "It can be seen that a proper elbow is formed at 3 on the x-axis, which means the number of clusters is equal to 3 (there are three dominant colors in the given image)."
},
{
"code": null,
"e": 4481,
"s": 4414,
"text": "Step 4 : The cluster centers obtained are standardized RGB values."
},
{
"code": null,
"e": 4536,
"s": 4481,
"text": "Standardized value = Actual value / Standard Deviation"
},
{
"code": null,
"e": 4905,
"s": 4536,
"text": "Dominant colors are displayed using imshow() method, which takes RGB values scaled to the range of 0 to 1. To do so, you need to multiply the standardized values of the cluster centers with there corresponding standard deviations. Since the actual RGB values take the maximum range of 255, the multiplied result is divided by 255 to get scaled values in the range 0-1."
},
{
"code": null,
"e": 4913,
"s": 4905,
"text": "Python3"
},
{
"code": "cluster_centers, _ = kmeans(batman_df[['scaled_color_red', 'scaled_color_blue', 'scaled_color_green']], 3) dominant_colors = [] # Get standard deviations of each colorred_std, green_std, blue_std = batman_df[['red', 'green', 'blue']].std() for cluster_center in cluster_centers: red_scaled, green_scaled, blue_scaled = cluster_center # Convert each standardized value to scaled value dominant_colors.append(( red_scaled * red_std / 255, green_scaled * green_std / 255, blue_scaled * blue_std / 255 )) # Display colors of cluster centersplt.imshow([dominant_colors])plt.show()",
"e": 5686,
"s": 4913,
"text": null
},
{
"code": null,
"e": 5767,
"s": 5686,
"text": "Here is the resultant plot showing the three dominant colors of the given image."
},
{
"code": null,
"e": 5778,
"s": 5767,
"text": "Output : "
},
{
"code": null,
"e": 5807,
"s": 5778,
"text": "Plot showing dominant colors"
},
{
"code": null,
"e": 5909,
"s": 5809,
"text": "Notice the three colors resemble the three that are indicative from visual inspection of the image."
},
{
"code": null,
"e": 5955,
"s": 5909,
"text": "Below is the full code without the comments :"
},
{
"code": null,
"e": 5963,
"s": 5955,
"text": "Python3"
},
{
"code": "import matplotlib.image as imgimport matplotlib.pyplot as pltfrom scipy.cluster.vq import whitenfrom scipy.cluster.vq import kmeansimport pandas as pd batman_image = img.imread('batman.jpg') r = []g = []b = []for row in batman_image: for temp_r, temp_g, temp_b, temp in row: r.append(temp_r) g.append(temp_g) b.append(temp_b) batman_df = pd.DataFrame({'red' : r, 'green' : g, 'blue' : b}) batman_df['scaled_color_red'] = whiten(batman_df['red'])batman_df['scaled_color_blue'] = whiten(batman_df['blue'])batman_df['scaled_color_green'] = whiten(batman_df['green']) cluster_centers, _ = kmeans(batman_df[['scaled_color_red', 'scaled_color_blue', 'scaled_color_green']], 3) dominant_colors = [] red_std, green_std, blue_std = batman_df[['red', 'green', 'blue']].std() for cluster_center in cluster_centers: red_scaled, green_scaled, blue_scaled = cluster_center dominant_colors.append(( red_scaled * red_std / 255, green_scaled * green_std / 255, blue_scaled * blue_std / 255 )) plt.imshow([dominant_colors])plt.show()",
"e": 7245,
"s": 5963,
"text": null
},
{
"code": null,
"e": 7257,
"s": 7245,
"text": "anikaseth98"
},
{
"code": null,
"e": 7274,
"s": 7257,
"text": "Image-Processing"
},
{
"code": null,
"e": 7292,
"s": 7274,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 7307,
"s": 7292,
"text": "python-utility"
},
{
"code": null,
"e": 7314,
"s": 7307,
"text": "Python"
}
] |
Matplotlib.figure.Figure.get_axes() in Python | 30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The get_axes() method figure module of matplotlib library is used to get the list of axes in the Figure.
Syntax: get_axes(self)
Parameters: This method does not accept any parameters.
Returns: This method returns a list of axes in the Figure.
Below examples illustrate the matplotlib.figure.Figure.get_axes() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np xs = list([ 1, 2, 3, 4, 5, 6, 7, 8, 9])ys = list([9, 8, 7, 6, 5, 4, 3, 2, 1]) fig = plt.figure() ax = fig.add_subplot(111)ax.plot(ys, xs) fig.get_axes()[0].set_ylabel("Y label")fig.get_axes()[0].set_xlabel("X label") fig.suptitle('matplotlib.figure.Figure.get_axes()\function Example\n\n', fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np xs = list([ 1, 2, 3, 4, 5, 6, 7, 8, 9])ys = list([9, 8, 7, 6, 5, 4, 3, 2, 1]) fig = plt.figure() ax = fig.add_subplot(111)ax.bar(ys, xs, width = 0.5, align ="center") fig.get_axes()[0].set_ylabel("Number")fig.get_axes()[0].set_xlabel("Values") fig.suptitle('matplotlib.figure.Figure.get_axes()\ function Example\n\n', fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 444,
"s": 339,
"text": "The get_axes() method figure module of matplotlib library is used to get the list of axes in the Figure."
},
{
"code": null,
"e": 467,
"s": 444,
"text": "Syntax: get_axes(self)"
},
{
"code": null,
"e": 523,
"s": 467,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 582,
"s": 523,
"text": "Returns: This method returns a list of axes in the Figure."
},
{
"code": null,
"e": 679,
"s": 582,
"text": "Below examples illustrate the matplotlib.figure.Figure.get_axes() function in matplotlib.figure:"
},
{
"code": null,
"e": 690,
"s": 679,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np xs = list([ 1, 2, 3, 4, 5, 6, 7, 8, 9])ys = list([9, 8, 7, 6, 5, 4, 3, 2, 1]) fig = plt.figure() ax = fig.add_subplot(111)ax.plot(ys, xs) fig.get_axes()[0].set_ylabel(\"Y label\")fig.get_axes()[0].set_xlabel(\"X label\") fig.suptitle('matplotlib.figure.Figure.get_axes()\\function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 1196,
"s": 690,
"text": null
},
{
"code": null,
"e": 1204,
"s": 1196,
"text": "Output:"
},
{
"code": null,
"e": 1215,
"s": 1204,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np xs = list([ 1, 2, 3, 4, 5, 6, 7, 8, 9])ys = list([9, 8, 7, 6, 5, 4, 3, 2, 1]) fig = plt.figure() ax = fig.add_subplot(111)ax.bar(ys, xs, width = 0.5, align =\"center\") fig.get_axes()[0].set_ylabel(\"Number\")fig.get_axes()[0].set_xlabel(\"Values\") fig.suptitle('matplotlib.figure.Figure.get_axes()\\ function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 1749,
"s": 1215,
"text": null
},
{
"code": null,
"e": 1757,
"s": 1749,
"text": "Output:"
},
{
"code": null,
"e": 1781,
"s": 1757,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 1799,
"s": 1781,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1806,
"s": 1799,
"text": "Python"
},
{
"code": null,
"e": 1904,
"s": 1806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1936,
"s": 1904,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1963,
"s": 1936,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1984,
"s": 1963,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2007,
"s": 1984,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2038,
"s": 2007,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2094,
"s": 2038,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2136,
"s": 2094,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2178,
"s": 2136,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2217,
"s": 2178,
"text": "Python | Get unique values from a list"
}
] |
Program to print the Ladder Pattern | 27 Apr, 2021
Given an integer N, the task is to print the ladder with N steps using ‘*’. The ladder will be with the gap of 3 spaces between two side rails.
Input: N = 3
Output:
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
Input: N = 4
Output:
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
Approach: Dividing the pattern into two sub-pattern.
* *
* *
which will be printed N+1 times
*****
* *
* *
which will be printed N times.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print the ladder pattern #include <iostream>using namespace std; // Function to print the desired ladder Patternvoid ladder_pattern(int N){ for (int i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times cout << "* *" << endl; cout << "* *" << endl; if (i < N) { // Printing the sub-pattern 2 // N times cout << "*****" << endl; } }} // Driver Codeint main(){ // Size of the Pattern int N = 3; // Print the ladder ladder_pattern(N); return 0;}
// Java program to print the ladder patternclass GFG{ // Function to print the desired ladder Patternstatic void ladder_pattern(int N){ for (int i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times System.out.println("* *"); System.out.println("* *"); if (i < N) { // Printing the sub-pattern 2 // N times System.out.println("*****" ); } }} // Driver Codepublic static void main(String args[]){ // Size of the Pattern int N = 3; // Print the ladder ladder_pattern(N);}} // This code is contributed by Rajput Ji
# Python3 program to print the ladder pattern # Function to print the desired ladder Patterndef ladder_pattern(N) : for i in range(N + 1) : # Printing the sub-pattern 1 # N + 1 times print("* *"); print("* *"); if (i < N) : # Printing the sub-pattern 2 # N times print("*****"); # Driver Codeif __name__ == "__main__" : # Size of the Pattern N = 3; # Print the ladder ladder_pattern(N); # This code is contributed by AnkitRai01
// C# program to print the ladder patternusing System; class GFG{ // Function to print the desired ladder Patternstatic void ladder_pattern(int N){ for (int i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times Console.WriteLine("* *"); Console.WriteLine("* *"); if (i < N) { // Printing the sub-pattern 2 // N times Console.WriteLine("*****"); } }} // Driver Codestatic public void Main (){ // Size of the Pattern int N = 3; // Print the ladder ladder_pattern(N);}} // This code is contributed by ajit.
<script> // JavaScript program to print the ladder pattern // Function to print the desired ladder Pattern function ladder_pattern(N) { for (var i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times document.write("* *" + "<br>"); document.write("* *" + "<br>"); if (i < N) { // Printing the sub-pattern 2 // N times document.write("*****" + "<br>"); } } } // Driver Code // Size of the Pattern var N = 3; // Print the ladder ladder_pattern(N); </script>
* *
* *
*****
* *
* *
*****
* *
* *
*****
* *
* *
ankthon
Rajput-Ji
jit_t
rdtank
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "Given an integer N, the task is to print the ladder with N steps using ‘*’. The ladder will be with the gap of 3 spaces between two side rails. "
},
{
"code": null,
"e": 368,
"s": 173,
"text": "Input: N = 3\nOutput: \n* *\n* *\n*****\n* *\n* *\n*****\n* *\n* *\n*****\n* *\n* *\n\nInput: N = 4\nOutput: \n* *\n* *\n*****\n* *\n* *\n*****\n* *\n* *\n*****\n* *\n* *\n*****\n* *\n* *"
},
{
"code": null,
"e": 425,
"s": 370,
"text": "Approach: Dividing the pattern into two sub-pattern. "
},
{
"code": null,
"e": 441,
"s": 427,
"text": "* *\n* *"
},
{
"code": null,
"e": 473,
"s": 441,
"text": "which will be printed N+1 times"
},
{
"code": null,
"e": 495,
"s": 475,
"text": "*****\n* *\n* *"
},
{
"code": null,
"e": 526,
"s": 495,
"text": "which will be printed N times."
},
{
"code": null,
"e": 578,
"s": 526,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 582,
"s": 578,
"text": "C++"
},
{
"code": null,
"e": 587,
"s": 582,
"text": "Java"
},
{
"code": null,
"e": 595,
"s": 587,
"text": "Python3"
},
{
"code": null,
"e": 598,
"s": 595,
"text": "C#"
},
{
"code": null,
"e": 609,
"s": 598,
"text": "Javascript"
},
{
"code": "// C++ program to print the ladder pattern #include <iostream>using namespace std; // Function to print the desired ladder Patternvoid ladder_pattern(int N){ for (int i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times cout << \"* *\" << endl; cout << \"* *\" << endl; if (i < N) { // Printing the sub-pattern 2 // N times cout << \"*****\" << endl; } }} // Driver Codeint main(){ // Size of the Pattern int N = 3; // Print the ladder ladder_pattern(N); return 0;}",
"e": 1185,
"s": 609,
"text": null
},
{
"code": "// Java program to print the ladder patternclass GFG{ // Function to print the desired ladder Patternstatic void ladder_pattern(int N){ for (int i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times System.out.println(\"* *\"); System.out.println(\"* *\"); if (i < N) { // Printing the sub-pattern 2 // N times System.out.println(\"*****\" ); } }} // Driver Codepublic static void main(String args[]){ // Size of the Pattern int N = 3; // Print the ladder ladder_pattern(N);}} // This code is contributed by Rajput Ji",
"e": 1827,
"s": 1185,
"text": null
},
{
"code": "# Python3 program to print the ladder pattern # Function to print the desired ladder Patterndef ladder_pattern(N) : for i in range(N + 1) : # Printing the sub-pattern 1 # N + 1 times print(\"* *\"); print(\"* *\"); if (i < N) : # Printing the sub-pattern 2 # N times print(\"*****\"); # Driver Codeif __name__ == \"__main__\" : # Size of the Pattern N = 3; # Print the ladder ladder_pattern(N); # This code is contributed by AnkitRai01",
"e": 2376,
"s": 1827,
"text": null
},
{
"code": "// C# program to print the ladder patternusing System; class GFG{ // Function to print the desired ladder Patternstatic void ladder_pattern(int N){ for (int i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times Console.WriteLine(\"* *\"); Console.WriteLine(\"* *\"); if (i < N) { // Printing the sub-pattern 2 // N times Console.WriteLine(\"*****\"); } }} // Driver Codestatic public void Main (){ // Size of the Pattern int N = 3; // Print the ladder ladder_pattern(N);}} // This code is contributed by ajit.",
"e": 3013,
"s": 2376,
"text": null
},
{
"code": "<script> // JavaScript program to print the ladder pattern // Function to print the desired ladder Pattern function ladder_pattern(N) { for (var i = 0; i <= N; i++) { // Printing the sub-pattern 1 // N+1 times document.write(\"* *\" + \"<br>\"); document.write(\"* *\" + \"<br>\"); if (i < N) { // Printing the sub-pattern 2 // N times document.write(\"*****\" + \"<br>\"); } } } // Driver Code // Size of the Pattern var N = 3; // Print the ladder ladder_pattern(N); </script>",
"e": 3641,
"s": 3013,
"text": null
},
{
"code": null,
"e": 3707,
"s": 3641,
"text": "* *\n* *\n*****\n* *\n* *\n*****\n* *\n* *\n*****\n* *\n* *"
},
{
"code": null,
"e": 3717,
"s": 3709,
"text": "ankthon"
},
{
"code": null,
"e": 3727,
"s": 3717,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 3733,
"s": 3727,
"text": "jit_t"
},
{
"code": null,
"e": 3740,
"s": 3733,
"text": "rdtank"
},
{
"code": null,
"e": 3757,
"s": 3740,
"text": "pattern-printing"
},
{
"code": null,
"e": 3776,
"s": 3757,
"text": "School Programming"
},
{
"code": null,
"e": 3793,
"s": 3776,
"text": "pattern-printing"
}
] |
Monte Carlo method applied on a 2D binary alloy using an Ising Model on Python | by Jonathan Leban | Towards Data Science | A material such as a piece of metal or a glass sample has physical properties such as electrical conductivity, magnetic susceptibility, thermal conductivity and many others. For industrial applications, these properties must be known in order to select the best material or alloy that will meet the requirements of the load cell. For example, the body of a car must be light, load and corrosion resistant. To meet all these needs, the three main materials used are: metals, polymers and aluminium alloys. But how do you determine the properties of an object? How is it possible to calculate the properties of a material composed of billions of billions of microstates?
Strictly speaking, we need to know the energy of each microstate in order to calculate the properties of a material. In this article, I will focus on four physical quantities: energy, magnetic susceptibility, magnetization, and heat capacity. These quantities are those that are interconnected and define a system well because they are fundamental physical properties although energy is the basis of all the relationships we define below. But one question remains: how to simulate the behavior of a material in order to calculate its properties?
As we are limited by the power of computers, we cannot model the complete behavior of the hardware because it would cost us too much time and lead us to ask a new question: how should the size of the system be a representation close to reality?
To answer these questions, I will consider a 2D binary alloy as the piece of material I want to examine. For all the properties I am interested in, I will compare the theoretical value and the experimental value (value given by the simulation) for different system sizes.
But first, we will look at the mathematics and physics that establish the relationships for the different properties we want to evaluate.
The probability of finding the system in a particular microstate with the energy E is given by the canonical distribution :
With β = 1/kT, k defined as the Boltzman constant and T as the temperature. Z is known as the repartition function and is given by:
With both equations, we can measure any experimental parameter but, in general, summation cannot be performed. Fortunately, the probability of finding the system in the micro state of energy E, P(E), is a precise function of the energy E. Thus, we can make an approximation of the number of microstates to be taken into account in the calculation of physical properties. In this paper, I will show the impact of the size of the system on the accuracy of the calculation of the physical properties.
As I said before, we are only interested in energy, magnetic susceptibility, magnetization and heat capacity. There are multiple ways to simulate these properties as Density Functional Theory (the most accurate one), Machine Learning or Monte Carlo method.
In this article, I decided to build a Monte Carlo simulation of Ising’s 2D model with H=0. Using this model, I was able to calculate the expectation values of the absolute value of spin magnetization for L xL spins systems with L=4, 8, 16 and 32 as a function of temperature (the Ising model is the representation of spins on a graph). The Monte Carlo method is based on the repetition of random sampling (changing a rotation from -1 to 1 or vice versa) to obtain a new energy value. If the value of the total energy decreases, we accept the new situation because it means that we are getting closer to the equilibrium situation where the energy is minimal.As it is more convenient to work in dimensionless units, I have therefore calculated all energies in J units. All temperatures have been measured in J/k units.
The expression for the Energy of the total system is :
Where σ is the spin and can be equal to -1 or 1. In addition, I computed the magnetic susceptibility per site χ, at each temperature.
Here M is the total magnetization of the system and T the temperature. The magnetization per site is given by:
And finally the heat capacity per spin C is the following:
with Tc the critical temperature defined by ln(1 + √2) = (2J)/(k*Tc). It can be seen that the heat capacity diverges logarithmically at the critical temperature. This divergence is not visible in a finite size system. In addition, I did not have an analytical solution for magnetic susceptibility, so I did not compare the simulation result with the exact result.
Now, as the mathematics are done, we can go into the computational part.
With Python, I built Monte Carlo simulation of the 2D Ising model with H=0 and I included uncertainty for each physical property.
def init(L): state = 2 * np.random.randint(2, size=(L,L)) - 1 return state def E_dimensionless(config,L): total_energy = 0 for i in range(len(config)): for j in range(len(config)): S = config[i,j] nb = config[(i+1)%L, j] + config[i, (j+1)%L] + config[(i-1)%L, j] + config[i, (j-1)%L] total_energy += -nb * S return (total_energy/4)def magnetization(config): Mag = np.sum(config) return Mag
I first initialized my system which is a square of LxL spins that can take the value -1 or 1. I created one function to calculate the energy and another one for the magnetization.
def MC_step(config, beta): '''Monte Carlo move using Metropolis algorithm ''' L = len(config) for i in range(L): for j in range(L): a = np.random.randint(0, L) # looping over i & j therefore use a & b b = np.random.randint(0, L) sigma = config[a, b] neighbors = config[(a+1)%L, b] + config[a, (b+1)%L] + config[(a-1)%L, b] + config[a, (b-1)%L] del_E = 2*sigma*neighbors if del_E < 0: sigma *= -1 elif rand() < np.exp(-del_E*beta): sigma *= -1 config[a, b] = sigma return config
Then I used the Metropolis algorithm for my Monte Carlo simulation. Based on a random initial configuration, I performed a random spin change and recalculated the energy. If the energy of the system decreases, the new configuration is accepted as we approach equilibrium. Otherwise, if the new system has a higher energy, the configuration is accepted with a probability given by exp(−βΔE).
def calcul_energy_mag_C_X(config, L, eqSteps, err_runs): # L is the length of the lattice nt = 100 # number of temperature points mcSteps = 1000 T_c = 2/math.log(1 + math.sqrt(2)) # the number of MC sweeps for equilibrium should be at least equal to the number of MC sweeps for equilibrium # initialization of all variables T = np.linspace(1., 7., nt); E,M,C,X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt) C_theoric, M_theoric = np.zeros(nt), np.zeros(nt) delta_E,delta_M, delta_C, delta_X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt) n1 = 1.0/(mcSteps*L*L) n2 = 1.0/(mcSteps*mcSteps*L*L) # n1 and n2 will be use to compute the mean value and the # by sites # of E and E^2 Energies = [] Magnetizations = [] SpecificHeats = [] Susceptibilities = [] delEnergies = [] delMagnetizations = [] delSpecificHeats = [] delSusceptibilities = [] for t in range(nt): # initialize total energy and mag beta = 1./T[t] # evolve the system to equilibrium for i in range(eqSteps): MC_step(config, beta) # list of ten macroscopic properties Ez = [], Cz = [], Mz = [], Xz = [] for j in range(err_runs): E = E_squared = M = M_squared = 0 for i in range(mcSteps): MC_step(config, beta) energy = E_dimensionless(config,L) # calculate the energy at time stamp mag = abs(magnetization(config)) # calculate the abs total mag. at time stamp # sum up total energy and mag after each time steps E += energy E_squared += energy**2 M += mag M_squared += mag**2 # mean (divide by total time steps) E_mean = E/mcSteps E_squared_mean = E_squared/mcSteps M_mean = M/mcSteps M_squared_mean = M_squared/mcSteps # calculate macroscopic properties (divide by # sites) and append Energy = E_mean/(L**2) SpecificHeat = beta**2 * (E_squared_mean - E_mean**2)/L**2 Magnetization = M_mean/L**2 Susceptibility = beta * (M_squared_mean - M_mean**2)/(L**2) Ez.append(Energy); Cz.append(SpecificHeat); Mz.append(Magnetization); Xz.append(Susceptibility); Energy = np.mean(Ez) Energies.append(Energy) delEnergy = np.std(Ez) delEnergies.append(float(delEnergy)) Magnetization = np.mean(Mz) Magnetizations.append(Magnetization) delMagnetization = np.std(Mz) delMagnetizations.append(delMagnetization) SpecificHeat = np.mean(Cz) SpecificHeats.append(SpecificHeat) delSpecificHeat = np.std(Cz) delSpecificHeats.append(delSpecificHeat) Susceptibility = np.mean(Xz) delSusceptibility = np.std(Xz) Susceptibilities.append(Susceptibility) delSusceptibilities.append(delSusceptibility) if T[t] - T_c >= 0: C_theoric[t] = 0 else: M_theoric[t] = pow(1 - pow(np.sinh(2*beta), -4),1/8) coeff = math.log(1 + math.sqrt(2)) if T[t] - T_c >= 0: C_theoric[t] = 0 else: C_theoric[t] = (2.0/np.pi) * (coeff**2) * (-math.log(1-T[t]/T_c) + math.log(1.0/coeff) - (1 + np.pi/4)) return (T,Energies,Magnetizations,SpecificHeats,Susceptibilities, delEnergies, delMagnetizations,M_theoric, C_theoric, delSpecificHeats, delSusceptibilities)
For each system size (4x4, 8x8, 16x16, 32x32), I’ve calculated energy, magnetization, specific heat and magnetic susceptibility. Each graph corresponds to a property. The black line for magnetization and specific heat is the exact solution and for each property an error estimation has been taken into account.
After executing the script above, I have the following results:
The simulations illustrate the concepts of finite size scale. Using the exact results known for Tc and critical exponents, we can check whether the simulation results for large systems actually converge towards the thermodynamic limit behaviour. The most fundamental concept underlying critical phenomena theory is a correlation length, which is a measure of a typical system length scale. The correlation length can be defined in terms of a correlation function, which, in the case of the Ising model, is given by the following. The correlation function decreases exponentially over long distances and is given by the so-called Ornstein-Zernicke form:
C(r⃗ )=exp(−r/ξ)/r^(d-2/2)
where ξ is the correlation length. This expression is valid only when r>>ξ. The correlation length ξ corresponds to the typical size of the ordered domains in the system. In the Ising model above Tc there are on average equal number of ordered domains with spin up and down (the material has lost all, and their typical size corresponds to the correlation length). Below Tc the correlation length corresponds to the typical size of domains of spins in an ordered background of opposite directed spins.
As a critical point (continuous phase transition) is approached, the correlation length diverges, in the thermodynamic limit, according to a power-law : ξ∼t^(−ν) where t is the reduced temperature measuring the distance from the critical point : t=|T−Tc| and ν is an example of a critical exponent. Another important critical exponent is the one determining the onset of order at the critical point, the magnetization. The order parameter is zero above Tc , and below Tc it emerges as : <m>=(Tc−T)^β.
For the heat capacity the relation is given by the following formula C=t^(−α). The heat capacity presents a singularity as T gets close to Tc.
For the susceptibility, the relation is the following: χ=t^(−γ). It seems that χ presents a singularity as T gets close to Tc. Hence, the system becomes infinitely sensitive to a magnetic field h as T gets close to Tc.
The set of exponents ν,α,β,γ for different systems fall into universality classes. Systems belonging to the same universality class have the same exponents. The universality class does not depend on microscopic details related to the system constituents and their interactions (as long as the interactions are short-ranged; long-range interactions can change the universality class), only on the dimensionality of the system and the nature of the order parameter. In our cases, the size of the system is therefore L. This is why the magnetization profile, heat capacity and temperature susceptibility differ from each other as the size of the system changes. The basis of finite-size scaling is that deviations from the infinite-size critical behavior occurs when the correlation length χ becomes comparable with the system length L. The way these finite-size deviations affects other quantities can be studied by expressing their temperature dependencies using the correlation length as the variable. Thus, t∼ξ^(−1/ν)
For example, in the asymptotic power-law form of the magnetization <m>=Tc^β t^β=Tc^β ξ^(−β/ν). The maximum value of the magnetization for a given system size L should be <m>=Tc^β L^(−β/ν). The convergence of the magnetization toward zero depends on the dimension size of the system L. In the 2D Ising model, we also have the following relation β/ν=1/8.
Based on the following expression χ=t^(−γ), in the asymptotic power-law form of the susceptibility, the substitution of t gives χ=ξ^(γ/ν). The maximum value of the susceptibility for a given system size L should be χ=L^(γ/ν). With this expression we can see that the peak value of χ grows very rapidly with L and explains the difference of profile in the susceptibility plot of the different system sizes. For the 2D Ising model, we have γ/ν=7/4
Regarding the heat capacity, the relation is quite similar and it is the following one C=ξ^(α/ν) and the maximum value of the heat capacity for a given system size L should be C=ξ^(α/ν). Thus as for the magnetic susceptibility, the peak value of C grows very rapidly with L and explains the difference of profile in the heat capacity plot of the different system sizes.
From a more qualitative point of view, we notice that there is an inflection point for T=Tc for the energy profile but also that magnetization, thermal capacity and susceptibility fall to zero from this temperature. This means a change in the system behavior, which corresponds to the definition of the critical temperature. In fact, the critical temperature is the Curie temperature in our case, and the Curie temperature is the temperature above which the material loses all its permanent magnetic properties, which heralds a change in the behavior of the material. The permanent magnetic properties are caused by the alignment of the magnetic moments. Thus, above Tc, there are on average an equal number of domains ordered with upward and downward spin, which can be illustrated by the convergence of magnetic moment, specific heat and susceptibility towards zero.
Thus, the relationship between the accuracy of the results and the size of the system depends on the relevance we are examining. But the larger the size of the system, the higher the computational cost. Thus, since the cost of time is really important, we need to think about the trade-off: time/cost/precision. That’s why I wondered about the dependence of each property on the size of the system. What I understood is that for energy, we can perform our simulation with the smallest system size and the result will be usable because the dependence of energy on system size is exponential. This is no longer true for other properties where the larger the system size, the more accurate the results are. Nevertheless, we can still improve our results by increasing the number of steps needed to reach equilibrium for the 32x32 system size.
PS: I am currently a Master of Engineering Student at Berkeley, and if you want to discuss the topic, feel free to reach me. Here is my email. | [
{
"code": null,
"e": 840,
"s": 171,
"text": "A material such as a piece of metal or a glass sample has physical properties such as electrical conductivity, magnetic susceptibility, thermal conductivity and many others. For industrial applications, these properties must be known in order to select the best material or alloy that will meet the requirements of the load cell. For example, the body of a car must be light, load and corrosion resistant. To meet all these needs, the three main materials used are: metals, polymers and aluminium alloys. But how do you determine the properties of an object? How is it possible to calculate the properties of a material composed of billions of billions of microstates?"
},
{
"code": null,
"e": 1386,
"s": 840,
"text": "Strictly speaking, we need to know the energy of each microstate in order to calculate the properties of a material. In this article, I will focus on four physical quantities: energy, magnetic susceptibility, magnetization, and heat capacity. These quantities are those that are interconnected and define a system well because they are fundamental physical properties although energy is the basis of all the relationships we define below. But one question remains: how to simulate the behavior of a material in order to calculate its properties?"
},
{
"code": null,
"e": 1631,
"s": 1386,
"text": "As we are limited by the power of computers, we cannot model the complete behavior of the hardware because it would cost us too much time and lead us to ask a new question: how should the size of the system be a representation close to reality?"
},
{
"code": null,
"e": 1903,
"s": 1631,
"text": "To answer these questions, I will consider a 2D binary alloy as the piece of material I want to examine. For all the properties I am interested in, I will compare the theoretical value and the experimental value (value given by the simulation) for different system sizes."
},
{
"code": null,
"e": 2041,
"s": 1903,
"text": "But first, we will look at the mathematics and physics that establish the relationships for the different properties we want to evaluate."
},
{
"code": null,
"e": 2165,
"s": 2041,
"text": "The probability of finding the system in a particular microstate with the energy E is given by the canonical distribution :"
},
{
"code": null,
"e": 2297,
"s": 2165,
"text": "With β = 1/kT, k defined as the Boltzman constant and T as the temperature. Z is known as the repartition function and is given by:"
},
{
"code": null,
"e": 2795,
"s": 2297,
"text": "With both equations, we can measure any experimental parameter but, in general, summation cannot be performed. Fortunately, the probability of finding the system in the micro state of energy E, P(E), is a precise function of the energy E. Thus, we can make an approximation of the number of microstates to be taken into account in the calculation of physical properties. In this paper, I will show the impact of the size of the system on the accuracy of the calculation of the physical properties."
},
{
"code": null,
"e": 3052,
"s": 2795,
"text": "As I said before, we are only interested in energy, magnetic susceptibility, magnetization and heat capacity. There are multiple ways to simulate these properties as Density Functional Theory (the most accurate one), Machine Learning or Monte Carlo method."
},
{
"code": null,
"e": 3869,
"s": 3052,
"text": "In this article, I decided to build a Monte Carlo simulation of Ising’s 2D model with H=0. Using this model, I was able to calculate the expectation values of the absolute value of spin magnetization for L xL spins systems with L=4, 8, 16 and 32 as a function of temperature (the Ising model is the representation of spins on a graph). The Monte Carlo method is based on the repetition of random sampling (changing a rotation from -1 to 1 or vice versa) to obtain a new energy value. If the value of the total energy decreases, we accept the new situation because it means that we are getting closer to the equilibrium situation where the energy is minimal.As it is more convenient to work in dimensionless units, I have therefore calculated all energies in J units. All temperatures have been measured in J/k units."
},
{
"code": null,
"e": 3924,
"s": 3869,
"text": "The expression for the Energy of the total system is :"
},
{
"code": null,
"e": 4058,
"s": 3924,
"text": "Where σ is the spin and can be equal to -1 or 1. In addition, I computed the magnetic susceptibility per site χ, at each temperature."
},
{
"code": null,
"e": 4169,
"s": 4058,
"text": "Here M is the total magnetization of the system and T the temperature. The magnetization per site is given by:"
},
{
"code": null,
"e": 4228,
"s": 4169,
"text": "And finally the heat capacity per spin C is the following:"
},
{
"code": null,
"e": 4592,
"s": 4228,
"text": "with Tc the critical temperature defined by ln(1 + √2) = (2J)/(k*Tc). It can be seen that the heat capacity diverges logarithmically at the critical temperature. This divergence is not visible in a finite size system. In addition, I did not have an analytical solution for magnetic susceptibility, so I did not compare the simulation result with the exact result."
},
{
"code": null,
"e": 4665,
"s": 4592,
"text": "Now, as the mathematics are done, we can go into the computational part."
},
{
"code": null,
"e": 4795,
"s": 4665,
"text": "With Python, I built Monte Carlo simulation of the 2D Ising model with H=0 and I included uncertainty for each physical property."
},
{
"code": null,
"e": 5265,
"s": 4795,
"text": "def init(L): state = 2 * np.random.randint(2, size=(L,L)) - 1 return state def E_dimensionless(config,L): total_energy = 0 for i in range(len(config)): for j in range(len(config)): S = config[i,j] nb = config[(i+1)%L, j] + config[i, (j+1)%L] + config[(i-1)%L, j] + config[i, (j-1)%L] total_energy += -nb * S return (total_energy/4)def magnetization(config): Mag = np.sum(config) return Mag"
},
{
"code": null,
"e": 5445,
"s": 5265,
"text": "I first initialized my system which is a square of LxL spins that can take the value -1 or 1. I created one function to calculate the energy and another one for the magnetization."
},
{
"code": null,
"e": 6061,
"s": 5445,
"text": "def MC_step(config, beta): '''Monte Carlo move using Metropolis algorithm ''' L = len(config) for i in range(L): for j in range(L): a = np.random.randint(0, L) # looping over i & j therefore use a & b b = np.random.randint(0, L) sigma = config[a, b] neighbors = config[(a+1)%L, b] + config[a, (b+1)%L] + config[(a-1)%L, b] + config[a, (b-1)%L] del_E = 2*sigma*neighbors if del_E < 0: sigma *= -1 elif rand() < np.exp(-del_E*beta): sigma *= -1 config[a, b] = sigma return config"
},
{
"code": null,
"e": 6452,
"s": 6061,
"text": "Then I used the Metropolis algorithm for my Monte Carlo simulation. Based on a random initial configuration, I performed a random spin change and recalculated the energy. If the energy of the system decreases, the new configuration is accepted as we approach equilibrium. Otherwise, if the new system has a higher energy, the configuration is accepted with a probability given by exp(−βΔE)."
},
{
"code": null,
"e": 10080,
"s": 6452,
"text": "def calcul_energy_mag_C_X(config, L, eqSteps, err_runs): # L is the length of the lattice nt = 100 # number of temperature points mcSteps = 1000 T_c = 2/math.log(1 + math.sqrt(2)) # the number of MC sweeps for equilibrium should be at least equal to the number of MC sweeps for equilibrium # initialization of all variables T = np.linspace(1., 7., nt); E,M,C,X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt) C_theoric, M_theoric = np.zeros(nt), np.zeros(nt) delta_E,delta_M, delta_C, delta_X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt) n1 = 1.0/(mcSteps*L*L) n2 = 1.0/(mcSteps*mcSteps*L*L) # n1 and n2 will be use to compute the mean value and the # by sites # of E and E^2 Energies = [] Magnetizations = [] SpecificHeats = [] Susceptibilities = [] delEnergies = [] delMagnetizations = [] delSpecificHeats = [] delSusceptibilities = [] for t in range(nt): # initialize total energy and mag beta = 1./T[t] # evolve the system to equilibrium for i in range(eqSteps): MC_step(config, beta) # list of ten macroscopic properties Ez = [], Cz = [], Mz = [], Xz = [] for j in range(err_runs): E = E_squared = M = M_squared = 0 for i in range(mcSteps): MC_step(config, beta) energy = E_dimensionless(config,L) # calculate the energy at time stamp mag = abs(magnetization(config)) # calculate the abs total mag. at time stamp # sum up total energy and mag after each time steps E += energy E_squared += energy**2 M += mag M_squared += mag**2 # mean (divide by total time steps) E_mean = E/mcSteps E_squared_mean = E_squared/mcSteps M_mean = M/mcSteps M_squared_mean = M_squared/mcSteps # calculate macroscopic properties (divide by # sites) and append Energy = E_mean/(L**2) SpecificHeat = beta**2 * (E_squared_mean - E_mean**2)/L**2 Magnetization = M_mean/L**2 Susceptibility = beta * (M_squared_mean - M_mean**2)/(L**2) Ez.append(Energy); Cz.append(SpecificHeat); Mz.append(Magnetization); Xz.append(Susceptibility); Energy = np.mean(Ez) Energies.append(Energy) delEnergy = np.std(Ez) delEnergies.append(float(delEnergy)) Magnetization = np.mean(Mz) Magnetizations.append(Magnetization) delMagnetization = np.std(Mz) delMagnetizations.append(delMagnetization) SpecificHeat = np.mean(Cz) SpecificHeats.append(SpecificHeat) delSpecificHeat = np.std(Cz) delSpecificHeats.append(delSpecificHeat) Susceptibility = np.mean(Xz) delSusceptibility = np.std(Xz) Susceptibilities.append(Susceptibility) delSusceptibilities.append(delSusceptibility) if T[t] - T_c >= 0: C_theoric[t] = 0 else: M_theoric[t] = pow(1 - pow(np.sinh(2*beta), -4),1/8) coeff = math.log(1 + math.sqrt(2)) if T[t] - T_c >= 0: C_theoric[t] = 0 else: C_theoric[t] = (2.0/np.pi) * (coeff**2) * (-math.log(1-T[t]/T_c) + math.log(1.0/coeff) - (1 + np.pi/4)) return (T,Energies,Magnetizations,SpecificHeats,Susceptibilities, delEnergies, delMagnetizations,M_theoric, C_theoric, delSpecificHeats, delSusceptibilities)"
},
{
"code": null,
"e": 10391,
"s": 10080,
"text": "For each system size (4x4, 8x8, 16x16, 32x32), I’ve calculated energy, magnetization, specific heat and magnetic susceptibility. Each graph corresponds to a property. The black line for magnetization and specific heat is the exact solution and for each property an error estimation has been taken into account."
},
{
"code": null,
"e": 10455,
"s": 10391,
"text": "After executing the script above, I have the following results:"
},
{
"code": null,
"e": 11108,
"s": 10455,
"text": "The simulations illustrate the concepts of finite size scale. Using the exact results known for Tc and critical exponents, we can check whether the simulation results for large systems actually converge towards the thermodynamic limit behaviour. The most fundamental concept underlying critical phenomena theory is a correlation length, which is a measure of a typical system length scale. The correlation length can be defined in terms of a correlation function, which, in the case of the Ising model, is given by the following. The correlation function decreases exponentially over long distances and is given by the so-called Ornstein-Zernicke form:"
},
{
"code": null,
"e": 11135,
"s": 11108,
"text": "C(r⃗ )=exp(−r/ξ)/r^(d-2/2)"
},
{
"code": null,
"e": 11637,
"s": 11135,
"text": "where ξ is the correlation length. This expression is valid only when r>>ξ. The correlation length ξ corresponds to the typical size of the ordered domains in the system. In the Ising model above Tc there are on average equal number of ordered domains with spin up and down (the material has lost all, and their typical size corresponds to the correlation length). Below Tc the correlation length corresponds to the typical size of domains of spins in an ordered background of opposite directed spins."
},
{
"code": null,
"e": 12138,
"s": 11637,
"text": "As a critical point (continuous phase transition) is approached, the correlation length diverges, in the thermodynamic limit, according to a power-law : ξ∼t^(−ν) where t is the reduced temperature measuring the distance from the critical point : t=|T−Tc| and ν is an example of a critical exponent. Another important critical exponent is the one determining the onset of order at the critical point, the magnetization. The order parameter is zero above Tc , and below Tc it emerges as : <m>=(Tc−T)^β."
},
{
"code": null,
"e": 12281,
"s": 12138,
"text": "For the heat capacity the relation is given by the following formula C=t^(−α). The heat capacity presents a singularity as T gets close to Tc."
},
{
"code": null,
"e": 12500,
"s": 12281,
"text": "For the susceptibility, the relation is the following: χ=t^(−γ). It seems that χ presents a singularity as T gets close to Tc. Hence, the system becomes infinitely sensitive to a magnetic field h as T gets close to Tc."
},
{
"code": null,
"e": 13519,
"s": 12500,
"text": "The set of exponents ν,α,β,γ for different systems fall into universality classes. Systems belonging to the same universality class have the same exponents. The universality class does not depend on microscopic details related to the system constituents and their interactions (as long as the interactions are short-ranged; long-range interactions can change the universality class), only on the dimensionality of the system and the nature of the order parameter. In our cases, the size of the system is therefore L. This is why the magnetization profile, heat capacity and temperature susceptibility differ from each other as the size of the system changes. The basis of finite-size scaling is that deviations from the infinite-size critical behavior occurs when the correlation length χ becomes comparable with the system length L. The way these finite-size deviations affects other quantities can be studied by expressing their temperature dependencies using the correlation length as the variable. Thus, t∼ξ^(−1/ν)"
},
{
"code": null,
"e": 13872,
"s": 13519,
"text": "For example, in the asymptotic power-law form of the magnetization <m>=Tc^β t^β=Tc^β ξ^(−β/ν). The maximum value of the magnetization for a given system size L should be <m>=Tc^β L^(−β/ν). The convergence of the magnetization toward zero depends on the dimension size of the system L. In the 2D Ising model, we also have the following relation β/ν=1/8."
},
{
"code": null,
"e": 14318,
"s": 13872,
"text": "Based on the following expression χ=t^(−γ), in the asymptotic power-law form of the susceptibility, the substitution of t gives χ=ξ^(γ/ν). The maximum value of the susceptibility for a given system size L should be χ=L^(γ/ν). With this expression we can see that the peak value of χ grows very rapidly with L and explains the difference of profile in the susceptibility plot of the different system sizes. For the 2D Ising model, we have γ/ν=7/4"
},
{
"code": null,
"e": 14688,
"s": 14318,
"text": "Regarding the heat capacity, the relation is quite similar and it is the following one C=ξ^(α/ν) and the maximum value of the heat capacity for a given system size L should be C=ξ^(α/ν). Thus as for the magnetic susceptibility, the peak value of C grows very rapidly with L and explains the difference of profile in the heat capacity plot of the different system sizes."
},
{
"code": null,
"e": 15557,
"s": 14688,
"text": "From a more qualitative point of view, we notice that there is an inflection point for T=Tc for the energy profile but also that magnetization, thermal capacity and susceptibility fall to zero from this temperature. This means a change in the system behavior, which corresponds to the definition of the critical temperature. In fact, the critical temperature is the Curie temperature in our case, and the Curie temperature is the temperature above which the material loses all its permanent magnetic properties, which heralds a change in the behavior of the material. The permanent magnetic properties are caused by the alignment of the magnetic moments. Thus, above Tc, there are on average an equal number of domains ordered with upward and downward spin, which can be illustrated by the convergence of magnetic moment, specific heat and susceptibility towards zero."
},
{
"code": null,
"e": 16397,
"s": 15557,
"text": "Thus, the relationship between the accuracy of the results and the size of the system depends on the relevance we are examining. But the larger the size of the system, the higher the computational cost. Thus, since the cost of time is really important, we need to think about the trade-off: time/cost/precision. That’s why I wondered about the dependence of each property on the size of the system. What I understood is that for energy, we can perform our simulation with the smallest system size and the result will be usable because the dependence of energy on system size is exponential. This is no longer true for other properties where the larger the system size, the more accurate the results are. Nevertheless, we can still improve our results by increasing the number of steps needed to reach equilibrium for the 32x32 system size."
}
] |
kinit - Unix, Linux Command | The use must be registered as a principal with the Key Distribution Center
(KDC) prior to running kinit.
<USER_HOME> is obtained from the
java.lang.System property
user.home. <USER_NAME> is obtained from
java.lang.System property
user.name. If <USER_HOME>
is null, the cache file would be stored in
the current directory that
the program is running from.
<USER_NAME> is the operating system’s login
username. This username could be different than
the user’s principal name. For
example on Solaris, it could be
/home/duke/krb5cc_duke,
in which duke is the <USER_NAME>
and /home/duke is the
<USER_HOME>.
By default, the keytab name is retrieved from
the Kerberos configuration file. If
the keytab name is not specifed in the Kerberos
configuration file, the name is
assumed to be <USER_HOME>/krb5.keytab
If you do not specify the password using
the password option on the command
line, kinit will prompt you for the password.
Note: password is provided only for testing purposes. Do not place
your password in a script or provide your password on the command
line. Doing so will compromise your password.
For more information see the man pages for kinit.
kinit [email protected]
Requesting proxiable credentials for a different
principal and storing these credentials in a
specified file cache:
kinit -p -c FILE:/home/duke/credentials/krb5cc_cafebeef
[email protected]
Requesting proxiable and forwardable credentials
for a different principal and
storing these credentials in a specified file cache:
kinit -f -p -c
FILE:/home/duke/credentials/krb5cc_cafebeef
[email protected]
Displaying the help menu for kinit:
kinit -help
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10684,
"s": 10577,
"text": "\nThe use must be registered as a principal with the Key Distribution Center\n(KDC) prior to running kinit.\n"
},
{
"code": null,
"e": 11184,
"s": 10684,
"text": "\n<USER_HOME> is obtained from the\njava.lang.System property\nuser.home. <USER_NAME> is obtained from\njava.lang.System property\nuser.name. If <USER_HOME>\nis null, the cache file would be stored in\nthe current directory that\nthe program is running from.\n<USER_NAME> is the operating system’s login\nusername. This username could be different than\nthe user’s principal name. For\nexample on Solaris, it could be\n/home/duke/krb5cc_duke,\nin which duke is the <USER_NAME>\nand /home/duke is the\n<USER_HOME>.\n"
},
{
"code": null,
"e": 11386,
"s": 11184,
"text": "\nBy default, the keytab name is retrieved from\nthe Kerberos configuration file. If\nthe keytab name is not specifed in the Kerberos\nconfiguration file, the name is\nassumed to be <USER_HOME>/krb5.keytab\n"
},
{
"code": null,
"e": 11510,
"s": 11386,
"text": "\nIf you do not specify the password using\nthe password option on the command\nline, kinit will prompt you for the password.\n"
},
{
"code": null,
"e": 11691,
"s": 11510,
"text": "\nNote: password is provided only for testing purposes. Do not place\nyour password in a script or provide your password on the command\nline. Doing so will compromise your password.\n"
},
{
"code": null,
"e": 11743,
"s": 11691,
"text": "\nFor more information see the man pages for kinit.\n"
},
{
"code": null,
"e": 11770,
"s": 11745,
"text": "kinit [email protected]\n"
},
{
"code": null,
"e": 11888,
"s": 11770,
"text": "\nRequesting proxiable credentials for a different\nprincipal and storing these credentials in a\nspecified file cache:\n"
},
{
"code": null,
"e": 11969,
"s": 11890,
"text": "kinit -p -c FILE:/home/duke/credentials/krb5cc_cafebeef\[email protected]\n"
},
{
"code": null,
"e": 12103,
"s": 11969,
"text": "\nRequesting proxiable and forwardable credentials\nfor a different principal and\nstoring these credentials in a specified file cache:\n"
},
{
"code": null,
"e": 12187,
"s": 12105,
"text": "kinit -f -p -c\nFILE:/home/duke/credentials/krb5cc_cafebeef\[email protected]\n"
},
{
"code": null,
"e": 12225,
"s": 12187,
"text": "\nDisplaying the help menu for kinit:\n"
},
{
"code": null,
"e": 12240,
"s": 12227,
"text": "kinit -help\n"
},
{
"code": null,
"e": 12270,
"s": 12253,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 12305,
"s": 12270,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12333,
"s": 12305,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12367,
"s": 12333,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12384,
"s": 12367,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12417,
"s": 12384,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12428,
"s": 12417,
"text": " Pradeep D"
},
{
"code": null,
"e": 12463,
"s": 12428,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12479,
"s": 12463,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12512,
"s": 12479,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12524,
"s": 12512,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12556,
"s": 12524,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12564,
"s": 12556,
"text": " Uplatz"
},
{
"code": null,
"e": 12571,
"s": 12564,
"text": " Print"
},
{
"code": null,
"e": 12582,
"s": 12571,
"text": " Add Notes"
}
] |
How to convert an integer to a unicode character in Python? | Python library’s chr() function converts Unicode character associated to any interger which is between 0 an 0x10ffff.
>>> chr(36)
'$'
>>> chr(97)
'a'
>>> chr(81)
'Q' | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Python library’s chr() function converts Unicode character associated to any interger which is between 0 an 0x10ffff."
},
{
"code": null,
"e": 1228,
"s": 1180,
"text": ">>> chr(36)\n'$'\n>>> chr(97)\n'a'\n>>> chr(81)\n'Q'"
}
] |
Create scatterplot for two dependent variables and one independent variable in R. | To create scatterplot for two dependent variables and one independent variable, we can use geom_point function and geom_smooth function of ggplot2 package. Both of these functions will be used twice, where we can define the aesthetics of the plot for each dependent variable as shown in the Example below.
Following snippet creates a sample data frame −
x<-rnorm(20)
y1<-rnorm(20,5)
y2<-rnorm(20,10)
df<-data.frame(x,y1,y2)
df
The following dataframe is created −
x y1 y2
1 2.4995751 5.515944 11.055437
2 -0.6271148 6.234058 9.847844
3 1.5572278 4.363662 10.305286
4 0.7544594 4.660968 9.709750
5 -0.3531405 5.896566 8.300061
6 0.3516249 6.714057 10.735020
7 0.4605740 4.955006 8.975519
8 0.2999492 4.671082 10.373543
9 1.0682999 4.590270 11.436856
10 0.2140709 5.163876 9.100128
11 -0.3508677 4.798086 9.221152
12 0.6303074 4.879782 10.123158
13 -1.0964767 4.678353 9.703888
14 -1.0814789 4.701568 10.983667
15 0.3777337 4.694484 11.089179
16 0.9787944 5.577403 8.935059
17 -0.2456083 6.365431 9.195587
18 -1.1495510 3.654495 7.648289
19 0.1903006 7.930433 11.254847
20 0.6788355 4.661313 11.421257
To load the ggplot2 package and to create a scatterplot for dependent variables y1 and y2 that has only one independent variable x on the above created data frame, add the following code to the above snippet −
x<-rnorm(20)
y1<-rnorm(20,5)
y2<-rnorm(20,10)
df<-data.frame(x,y1,y2)
library(ggplot2)
ggplot(df,aes(x,y1))+geom_point()+geom_smooth(method="lm")+geom_point(aes(x,y2)
)+geom_smooth(aes(x,y2),method="lm")
`geom_smooth()` using formula 'y ~ x'
`geom_smooth()` using formula 'y ~ x'
If you execute all the above given snippets as a single program, it generates the following Output − | [
{
"code": null,
"e": 1368,
"s": 1062,
"text": "To create scatterplot for two dependent variables and one independent variable, we can use geom_point function and geom_smooth function of ggplot2 package. Both of these functions will be used twice, where we can define the aesthetics of the plot for each dependent variable as shown in the Example below."
},
{
"code": null,
"e": 1416,
"s": 1368,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1489,
"s": 1416,
"text": "x<-rnorm(20)\ny1<-rnorm(20,5)\ny2<-rnorm(20,10)\ndf<-data.frame(x,y1,y2)\ndf"
},
{
"code": null,
"e": 1526,
"s": 1489,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 2208,
"s": 1526,
"text": " x y1 y2\n 1 2.4995751 5.515944 11.055437\n 2 -0.6271148 6.234058 9.847844\n 3 1.5572278 4.363662 10.305286\n 4 0.7544594 4.660968 9.709750\n 5 -0.3531405 5.896566 8.300061\n 6 0.3516249 6.714057 10.735020\n 7 0.4605740 4.955006 8.975519\n 8 0.2999492 4.671082 10.373543\n 9 1.0682999 4.590270 11.436856\n10 0.2140709 5.163876 9.100128\n11 -0.3508677 4.798086 9.221152\n12 0.6303074 4.879782 10.123158\n13 -1.0964767 4.678353 9.703888\n14 -1.0814789 4.701568 10.983667\n15 0.3777337 4.694484 11.089179\n16 0.9787944 5.577403 8.935059\n17 -0.2456083 6.365431 9.195587\n18 -1.1495510 3.654495 7.648289\n19 0.1903006 7.930433 11.254847\n20 0.6788355 4.661313 11.421257"
},
{
"code": null,
"e": 2418,
"s": 2208,
"text": "To load the ggplot2 package and to create a scatterplot for dependent variables y1 and y2 that has only one independent variable x on the above created data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 2699,
"s": 2418,
"text": "x<-rnorm(20)\ny1<-rnorm(20,5)\ny2<-rnorm(20,10)\ndf<-data.frame(x,y1,y2)\nlibrary(ggplot2)\n\nggplot(df,aes(x,y1))+geom_point()+geom_smooth(method=\"lm\")+geom_point(aes(x,y2)\n)+geom_smooth(aes(x,y2),method=\"lm\")\n`geom_smooth()` using formula 'y ~ x'\n`geom_smooth()` using formula 'y ~ x'"
},
{
"code": null,
"e": 2800,
"s": 2699,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
}
] |
Sowing the Seeds of Decision Tree Regression | by Ashwin Raj | Towards Data Science | In this article we will discuss about decision trees, one of the supervised learning algorithm, commonly referred to as CART that can be used for both regression and classification problems.
As the name suggests, the primary role of this algorithm is to make a decision using a tree structure. To find solutions a decision tree makes a sequential, hierarchical decision about the outcome variable based on the predictor data. A decision tree is generally used while working with non-linear data.
Because of their simplicity and the fact that they are easy to understand and implement, they are widely used in a large number of industries.
Now, before we move further it’s important that we understand some important terminologies associated with the algorithm. Decision Trees are made up of a number of nodes, each of which represents a particular feature. The first node of a decision tree is generally referred to as the Root Node.
The depth of the tree is the total number of levels present in the tree excluding the root node. A branch denotes a decision and can be visualized as a link between different nodes. A leaf tells you what class each sample belongs to.
Decision Trees progressively divide data sets into small data groups until they reach sets that are small enough to be described by some label. At the same time an associated decision tree is incrementally developed.
Decision trees apply a top-down approach to data. The splitting of a binary tree can either be binary or multiway. The algorithm partitions the data into a set of rectangles and fits the model over each of these rectangles. More the number of rectangles (splits) greater is the complexity.
A downside of using super complex decision tree is that they are likely of fall into overfitting scenario as the model learns the training data so good that it has problems to generalize to new unseen data.
It then examines all the features of the dataset to find the best possible result by splitting the data into smaller and smaller subgroups until the tree concludes.
The information gain is based on the decrease in entropy after a dataset is split on an attribute. Entropy controls how a decision tree decides to split the data.
The objective of constructing a decision tree is to find the attributes that returns the highest information gain.
Now we will be practically applying what we have learned by building a decision tree model.
You can access the complete code and other resources used for building this decision tree model on my GitHub handle.
The first step in building our model is to import the necessary libraries. Pandas, Numpy and Matplotlib are the most commonly used libraries for data manipulation, scientific computing and plotting data on graphs respectively.
#Import the Libraries and read the data into a Pandas DataFrameimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snstest=pd.read_csv("california_housing_test.csv")train=pd.read_csv("california_housing_train.csv")
Seaborn is also being extensively used these days for making statistical graphics in python. After importing the necessary libraries, our next step is to load the dataset into our Jupiter notebook. Here I have used Google collaboratory notebook for demonstration purpose.
After successfully loading the data into our notebook, our next step is to visualize the data. Visualizing the data is important in order to find any correlation between the various features.
#Visualise the dataplt.figure()sns.heatmap(data.corr(), cmap='coolwarm')plt.show()sns.lmplot(x='median_income', y='median_house_value', data=train)sns.lmplot(x='housing_median_age', y='median_house_value', data=train)
After this, appropriate features are selected to build the model. This is commonly referred to as Feature Engineering. Feature engineering is the process of using domain knowledge to extract features from raw data via various data mining techniques.
#Select appropriate featuresdata = data[[‘total_rooms’, ‘total_bedrooms’, ‘housing_median_age’, ‘median_income’, ‘population’, ‘households’]]data.info()data['total_rooms'] = data['total_rooms'].fillna(data['total_rooms'].mean())data['total_bedrooms'] = data['total_bedrooms'].fillna(data['total_bedrooms'].mean()
Feature selection is essentially important when the number of features in our dataset is large.
Once the features are selected, the dataset is split into training data and testing data. This is done by importing the train_test_split function from sklearn library.
#Split the dataset into training and testing dataimport train_test_splitX_train, X_test, y_train, y_test = train_test_split(train, y, test_size = 0.2, random_state = 0)y_train = y_train.reshape(-1,1)y_test = y_test.reshape(-1,1
Note that we have called the library in between our code. Python allows us to import libraries anywhere in between the code.
#Fit the model over training datafrom sklearn.tree import DecisionTreeRegressordt = DecisionTreeRegressor()dt.fit(X_train, y_train)
After this we import the decision tree model from Scikit Learn Library and initialize our regression model. We then fit the data into our model. With that we have succesfully built our decision tree model.
A major problem associated with decision trees is that it suffers from high variance i.e. a small change in data can lead to an entirely different set of splits. Similarly they are also found to create biased trees in scenarios where one class dominates other.
A decision tree is bound within boundaries and generally look for local optimal value instead of the global optimal one. These drawbacks however can be easily corrected using Ensemble methods like bagging and boosting which we will discuss in the upcoming posts.
With this we have reached the end of this article. I hope you would have found this article really informative. If you have any question or if you believe I have made any mistake, please contact me! You can get in touch with me via: Email or LinkedIn. | [
{
"code": null,
"e": 362,
"s": 171,
"text": "In this article we will discuss about decision trees, one of the supervised learning algorithm, commonly referred to as CART that can be used for both regression and classification problems."
},
{
"code": null,
"e": 667,
"s": 362,
"text": "As the name suggests, the primary role of this algorithm is to make a decision using a tree structure. To find solutions a decision tree makes a sequential, hierarchical decision about the outcome variable based on the predictor data. A decision tree is generally used while working with non-linear data."
},
{
"code": null,
"e": 810,
"s": 667,
"text": "Because of their simplicity and the fact that they are easy to understand and implement, they are widely used in a large number of industries."
},
{
"code": null,
"e": 1105,
"s": 810,
"text": "Now, before we move further it’s important that we understand some important terminologies associated with the algorithm. Decision Trees are made up of a number of nodes, each of which represents a particular feature. The first node of a decision tree is generally referred to as the Root Node."
},
{
"code": null,
"e": 1339,
"s": 1105,
"text": "The depth of the tree is the total number of levels present in the tree excluding the root node. A branch denotes a decision and can be visualized as a link between different nodes. A leaf tells you what class each sample belongs to."
},
{
"code": null,
"e": 1556,
"s": 1339,
"text": "Decision Trees progressively divide data sets into small data groups until they reach sets that are small enough to be described by some label. At the same time an associated decision tree is incrementally developed."
},
{
"code": null,
"e": 1846,
"s": 1556,
"text": "Decision trees apply a top-down approach to data. The splitting of a binary tree can either be binary or multiway. The algorithm partitions the data into a set of rectangles and fits the model over each of these rectangles. More the number of rectangles (splits) greater is the complexity."
},
{
"code": null,
"e": 2053,
"s": 1846,
"text": "A downside of using super complex decision tree is that they are likely of fall into overfitting scenario as the model learns the training data so good that it has problems to generalize to new unseen data."
},
{
"code": null,
"e": 2218,
"s": 2053,
"text": "It then examines all the features of the dataset to find the best possible result by splitting the data into smaller and smaller subgroups until the tree concludes."
},
{
"code": null,
"e": 2381,
"s": 2218,
"text": "The information gain is based on the decrease in entropy after a dataset is split on an attribute. Entropy controls how a decision tree decides to split the data."
},
{
"code": null,
"e": 2496,
"s": 2381,
"text": "The objective of constructing a decision tree is to find the attributes that returns the highest information gain."
},
{
"code": null,
"e": 2588,
"s": 2496,
"text": "Now we will be practically applying what we have learned by building a decision tree model."
},
{
"code": null,
"e": 2705,
"s": 2588,
"text": "You can access the complete code and other resources used for building this decision tree model on my GitHub handle."
},
{
"code": null,
"e": 2932,
"s": 2705,
"text": "The first step in building our model is to import the necessary libraries. Pandas, Numpy and Matplotlib are the most commonly used libraries for data manipulation, scientific computing and plotting data on graphs respectively."
},
{
"code": null,
"e": 3181,
"s": 2932,
"text": "#Import the Libraries and read the data into a Pandas DataFrameimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snstest=pd.read_csv(\"california_housing_test.csv\")train=pd.read_csv(\"california_housing_train.csv\")"
},
{
"code": null,
"e": 3453,
"s": 3181,
"text": "Seaborn is also being extensively used these days for making statistical graphics in python. After importing the necessary libraries, our next step is to load the dataset into our Jupiter notebook. Here I have used Google collaboratory notebook for demonstration purpose."
},
{
"code": null,
"e": 3645,
"s": 3453,
"text": "After successfully loading the data into our notebook, our next step is to visualize the data. Visualizing the data is important in order to find any correlation between the various features."
},
{
"code": null,
"e": 3863,
"s": 3645,
"text": "#Visualise the dataplt.figure()sns.heatmap(data.corr(), cmap='coolwarm')plt.show()sns.lmplot(x='median_income', y='median_house_value', data=train)sns.lmplot(x='housing_median_age', y='median_house_value', data=train)"
},
{
"code": null,
"e": 4113,
"s": 3863,
"text": "After this, appropriate features are selected to build the model. This is commonly referred to as Feature Engineering. Feature engineering is the process of using domain knowledge to extract features from raw data via various data mining techniques."
},
{
"code": null,
"e": 4426,
"s": 4113,
"text": "#Select appropriate featuresdata = data[[‘total_rooms’, ‘total_bedrooms’, ‘housing_median_age’, ‘median_income’, ‘population’, ‘households’]]data.info()data['total_rooms'] = data['total_rooms'].fillna(data['total_rooms'].mean())data['total_bedrooms'] = data['total_bedrooms'].fillna(data['total_bedrooms'].mean()"
},
{
"code": null,
"e": 4522,
"s": 4426,
"text": "Feature selection is essentially important when the number of features in our dataset is large."
},
{
"code": null,
"e": 4690,
"s": 4522,
"text": "Once the features are selected, the dataset is split into training data and testing data. This is done by importing the train_test_split function from sklearn library."
},
{
"code": null,
"e": 4918,
"s": 4690,
"text": "#Split the dataset into training and testing dataimport train_test_splitX_train, X_test, y_train, y_test = train_test_split(train, y, test_size = 0.2, random_state = 0)y_train = y_train.reshape(-1,1)y_test = y_test.reshape(-1,1"
},
{
"code": null,
"e": 5043,
"s": 4918,
"text": "Note that we have called the library in between our code. Python allows us to import libraries anywhere in between the code."
},
{
"code": null,
"e": 5175,
"s": 5043,
"text": "#Fit the model over training datafrom sklearn.tree import DecisionTreeRegressordt = DecisionTreeRegressor()dt.fit(X_train, y_train)"
},
{
"code": null,
"e": 5381,
"s": 5175,
"text": "After this we import the decision tree model from Scikit Learn Library and initialize our regression model. We then fit the data into our model. With that we have succesfully built our decision tree model."
},
{
"code": null,
"e": 5642,
"s": 5381,
"text": "A major problem associated with decision trees is that it suffers from high variance i.e. a small change in data can lead to an entirely different set of splits. Similarly they are also found to create biased trees in scenarios where one class dominates other."
},
{
"code": null,
"e": 5905,
"s": 5642,
"text": "A decision tree is bound within boundaries and generally look for local optimal value instead of the global optimal one. These drawbacks however can be easily corrected using Ensemble methods like bagging and boosting which we will discuss in the upcoming posts."
}
] |
C++ Queue Library - empty() Function | The C++ function std::queue::empty() tests whether queue is empty or not. Queue of zero size is considered as empty queue.
Following is the declaration for std::queue::empty() function form std::queue header.
bool empty() const;
None
Returns true if queue is empty otherwise false.
Constant i.e. O(1)
The following example shows the usage of std::queue::empty() function.
#include <iostream>
#include <queue>
using namespace std;
int main(void) {
queue<int> q;
if (q.empty())
cout << "Queue is empty." << endl;
q.push(10);
if (!q.empty())
cout << "Queue is not empty." << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
Queue is empty.
Queue is not empty.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2726,
"s": 2603,
"text": "The C++ function std::queue::empty() tests whether queue is empty or not. Queue of zero size is considered as empty queue."
},
{
"code": null,
"e": 2812,
"s": 2726,
"text": "Following is the declaration for std::queue::empty() function form std::queue header."
},
{
"code": null,
"e": 2833,
"s": 2812,
"text": "bool empty() const;\n"
},
{
"code": null,
"e": 2838,
"s": 2833,
"text": "None"
},
{
"code": null,
"e": 2886,
"s": 2838,
"text": "Returns true if queue is empty otherwise false."
},
{
"code": null,
"e": 2905,
"s": 2886,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 2976,
"s": 2905,
"text": "The following example shows the usage of std::queue::empty() function."
},
{
"code": null,
"e": 3227,
"s": 2976,
"text": "#include <iostream>\n#include <queue>\n\nusing namespace std;\n\nint main(void) {\n queue<int> q;\n\n if (q.empty())\n cout << \"Queue is empty.\" << endl;\n\n q.push(10);\n\n if (!q.empty())\n cout << \"Queue is not empty.\" << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3310,
"s": 3227,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3347,
"s": 3310,
"text": "Queue is empty.\nQueue is not empty.\n"
},
{
"code": null,
"e": 3354,
"s": 3347,
"text": " Print"
},
{
"code": null,
"e": 3365,
"s": 3354,
"text": " Add Notes"
}
] |
Decimal.Round() Method in C# | Set - 1 - GeeksforGeeks | 20 Mar, 2019
Decimal.Round Method is used to round a value to the nearest integer or a specified number of decimal places. There are 4 methods in the overload list of this method as follows:
Round(Decimal) Method
Round(Decimal, Int32) Method
Round(Decimal, MidpointRounding) Method
Round(Decimal, Int32, MidpointRounding) Method
Here, we will discuss the first two methods.
This method is used to round a decimal value to the nearest integer.
Syntax: public static decimal Round (decimal d);Here, it takes a decimal number to round.
Return Value: This method returns the integer which is nearest to the d parameter. If d is halfway between two integers, one of which is even and the other odd, the even number is returned.
Exceptions: This method throws OverflowException if the result is outside the range of a Decimal value.
Below programs illustrate the use of Decimal.Round(Decimal) Method:
Example 1:
// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 184467440737095.51615M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value); // Display the value Console.WriteLine("Rounded value is {0}", round); } catch (OverflowException e) { Console.WriteLine("Value must not be out of bound"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Output:
Rounded value is 184467440737096
Example 2: For OverflowException
// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 79228162514264337593543950335.5M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value); // Display the value Console.WriteLine("Rounded value is {0}", round); } catch (OverflowException e) { Console.WriteLine("Value must not be out of bound"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Compile-Time Errors:
prog.cs(15,51): error CS0594: Floating-point constant is outside the range of type `decimal’
This method is used to round a Decimal value to a specified number of decimal places.
Syntax: public static decimal Round (decimal d, int decimals);
Parameters:d: It is a decimal number which is to be rounded.decimals: It is a value from 0 to 28 that specifies the number of decimal places to round to.
Return Value: This method returns the decimal number equivalent to d rounded to decimals number of decimal places.
Exception: This method throws ArgumentOutOfRangeException if decimals is not a value from 0 to 28.
Below programs illustrate the use of Decimal.Round(Decimal, Int32) Method:
Example 1:
// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 7922816251426433759354.39503305M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value, 4); // Display the value Console.WriteLine("Rounded value is {0}", round); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("decimal place is not within bound"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Output:
Rounded value is 7922816251426433759354.3950
Example 2: For ArgumentOutOfRangeException
// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 7922816251426433759354.39503305M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value, 29); // Display the value Console.WriteLine("Rounded value is {0}", round); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("Decimal place is not within bound"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Output:
Decimal place is not within bound
Exception Thrown: System.ArgumentOutOfRangeException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal.round?view=netframework-4.7.2
CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 24480,
"s": 24302,
"text": "Decimal.Round Method is used to round a value to the nearest integer or a specified number of decimal places. There are 4 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 24502,
"s": 24480,
"text": "Round(Decimal) Method"
},
{
"code": null,
"e": 24531,
"s": 24502,
"text": "Round(Decimal, Int32) Method"
},
{
"code": null,
"e": 24571,
"s": 24531,
"text": "Round(Decimal, MidpointRounding) Method"
},
{
"code": null,
"e": 24618,
"s": 24571,
"text": "Round(Decimal, Int32, MidpointRounding) Method"
},
{
"code": null,
"e": 24663,
"s": 24618,
"text": "Here, we will discuss the first two methods."
},
{
"code": null,
"e": 24732,
"s": 24663,
"text": "This method is used to round a decimal value to the nearest integer."
},
{
"code": null,
"e": 24822,
"s": 24732,
"text": "Syntax: public static decimal Round (decimal d);Here, it takes a decimal number to round."
},
{
"code": null,
"e": 25012,
"s": 24822,
"text": "Return Value: This method returns the integer which is nearest to the d parameter. If d is halfway between two integers, one of which is even and the other odd, the even number is returned."
},
{
"code": null,
"e": 25116,
"s": 25012,
"text": "Exceptions: This method throws OverflowException if the result is outside the range of a Decimal value."
},
{
"code": null,
"e": 25184,
"s": 25116,
"text": "Below programs illustrate the use of Decimal.Round(Decimal) Method:"
},
{
"code": null,
"e": 25195,
"s": 25184,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 184467440737095.51615M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value); // Display the value Console.WriteLine(\"Rounded value is {0}\", round); } catch (OverflowException e) { Console.WriteLine(\"Value must not be out of bound\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 25912,
"s": 25195,
"text": null
},
{
"code": null,
"e": 25920,
"s": 25912,
"text": "Output:"
},
{
"code": null,
"e": 25953,
"s": 25920,
"text": "Rounded value is 184467440737096"
},
{
"code": null,
"e": 25986,
"s": 25953,
"text": "Example 2: For OverflowException"
},
{
"code": "// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 79228162514264337593543950335.5M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value); // Display the value Console.WriteLine(\"Rounded value is {0}\", round); } catch (OverflowException e) { Console.WriteLine(\"Value must not be out of bound\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 26723,
"s": 25986,
"text": null
},
{
"code": null,
"e": 26744,
"s": 26723,
"text": "Compile-Time Errors:"
},
{
"code": null,
"e": 26837,
"s": 26744,
"text": "prog.cs(15,51): error CS0594: Floating-point constant is outside the range of type `decimal’"
},
{
"code": null,
"e": 26923,
"s": 26837,
"text": "This method is used to round a Decimal value to a specified number of decimal places."
},
{
"code": null,
"e": 26986,
"s": 26923,
"text": "Syntax: public static decimal Round (decimal d, int decimals);"
},
{
"code": null,
"e": 27140,
"s": 26986,
"text": "Parameters:d: It is a decimal number which is to be rounded.decimals: It is a value from 0 to 28 that specifies the number of decimal places to round to."
},
{
"code": null,
"e": 27255,
"s": 27140,
"text": "Return Value: This method returns the decimal number equivalent to d rounded to decimals number of decimal places."
},
{
"code": null,
"e": 27354,
"s": 27255,
"text": "Exception: This method throws ArgumentOutOfRangeException if decimals is not a value from 0 to 28."
},
{
"code": null,
"e": 27429,
"s": 27354,
"text": "Below programs illustrate the use of Decimal.Round(Decimal, Int32) Method:"
},
{
"code": null,
"e": 27440,
"s": 27429,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 7922816251426433759354.39503305M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value, 4); // Display the value Console.WriteLine(\"Rounded value is {0}\", round); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"decimal place is not within bound\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 28183,
"s": 27440,
"text": null
},
{
"code": null,
"e": 28191,
"s": 28183,
"text": "Output:"
},
{
"code": null,
"e": 28236,
"s": 28191,
"text": "Rounded value is 7922816251426433759354.3950"
},
{
"code": null,
"e": 28279,
"s": 28236,
"text": "Example 2: For ArgumentOutOfRangeException"
},
{
"code": "// C# program to demonstrate the// Decimal.Round(Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring and initializing value decimal value = 7922816251426433759354.39503305M; // getting rounded decimal // using Round() method decimal round = Decimal.Round(value, 29); // Display the value Console.WriteLine(\"Rounded value is {0}\", round); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"Decimal place is not within bound\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 29031,
"s": 28279,
"text": null
},
{
"code": null,
"e": 29039,
"s": 29031,
"text": "Output:"
},
{
"code": null,
"e": 29127,
"s": 29039,
"text": "Decimal place is not within bound\nException Thrown: System.ArgumentOutOfRangeException\n"
},
{
"code": null,
"e": 29138,
"s": 29127,
"text": "Reference:"
},
{
"code": null,
"e": 29227,
"s": 29138,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.decimal.round?view=netframework-4.7.2"
},
{
"code": null,
"e": 29249,
"s": 29227,
"text": "CSharp-Decimal-Struct"
},
{
"code": null,
"e": 29263,
"s": 29249,
"text": "CSharp-method"
},
{
"code": null,
"e": 29266,
"s": 29263,
"text": "C#"
},
{
"code": null,
"e": 29364,
"s": 29266,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29382,
"s": 29364,
"text": "Destructors in C#"
},
{
"code": null,
"e": 29405,
"s": 29382,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29433,
"s": 29405,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29473,
"s": 29433,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29516,
"s": 29473,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 29538,
"s": 29516,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29555,
"s": 29538,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29571,
"s": 29555,
"text": "C# | List Class"
},
{
"code": null,
"e": 29621,
"s": 29571,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
How to build a real-time fraud detection pipeline using Faust and MLFlow | by Bogdan Cojocar | Towards Data Science | In this tutorial we will learn to start a Kafka cluster locally, to write a producer that sends messages, to create a simple machine learning training process for fraud detection, to expose the model via a REST interface and to do prediction in real-time.
The main frameworks that we will use are:
Faust: stream processing library, using the async/away paradigm and requires python 3.6+
Kafka: we will use the confluent version for kafka as our streaming platform
MLFlow: an open-source platform used to monitor and save machine learning models after training
Jupyter lab: our environment to run the code
We will also need some data for our training. We can use a CSV source from a Kaggle credit card fraud competition.
TL;DR: The code is on GitHub.
Let’s first build our fraud detection model. We will read the CSV data representing credit card transactions and apply a simple binary logistic regression classification between the two classes 0(not fraud) and 1(fraud) .
df = pd.read_csv('creditcard.csv')df.dtypesTime float64V1 float64V2 float64V3 float64V4 float64V5 float64V6 float64V7 float64V8 float64V9 float64V10 float64V11 float64V12 float64V13 float64V14 float64V15 float64V16 float64V17 float64V18 float64V19 float64V20 float64V21 float64V22 float64V23 float64V24 float64V25 float64V26 float64V27 float64V28 float64Amount float64Class int64
As we can see, most of the columns that we read are float , except the Class , which is our target variable. Now let’s do the training:
x_name = df.iloc[:, 1:30].columnsy_name = df.iloc[:1, 30: ].columnsdata_x = df[x_name]data_y = df[y_name]train_x, test_x, train_y, test_y = train_test_split(data_x, data_y, train_size=0.7, test_size=0.3)model = LogisticRegression()model.fit(train_x, train_y.values.ravel())
For features we use V1 — V28 and Amount . We do the split between train and test data, and fit the model. We can check some performance metrics:
pred_y = model.predict(test_x)accuracy_score(test_y, pred_y)0.9993094811745842f1_score(test_y, pred_y)0.7773584905660378precision_score(test_y, pred_y)0.8272727272727273recall_score(test_y, pred_y)0.6776315789473685
If we just use only accuracy as a metric we can shot ourselves in the foot. Always use better performance indicators like f1_score , precision and recall .
After the training we can save our new fraud detection model:
mlflow.sklearn.save_model(model, path='./fraud_model')
We use the sklearn module inside MLFlow as this will help us with the servis part.
Let’s start a terminal in the root of our project and type the following command:
mlflow models serve -m fraud_model
This will take a little bit of time, as additionally to deploying a microservice, it will also create a conda environment. This is to ensure that next time when we do the deployment we have our dependencies locked at a certain version and in a separate virtual environment. If everything runs fine, we will notice that we have a url for our service:
Listening at: http://127.0.0.1:5000
We can do a quick test from the terminal using cURL :
curl http://127.0.0.1:5000/invocations -H 'Content-Type: application/json' -d '{ "columns":["V1","V2","V3","V4","V5","V6","V7","V8","V9","V10","V11","V12","V13","V14","V15","V16","V17","V18","V19","V20","V21","V22","V23","V24","V25","V26","V27","V28","Amount"], "data":[[12.8,0.029,0.48,0.98,6.2,29.1,3.33,1.2,0.39,75.1,0.66,1.2,1.3,44.2,12.8,0.029,0.48,0.98,6.2,29,3.33,1.2,0.39,75.3,0.66,1.2,1.3,44.2,1.1]]}'
We are sending a POST request using a JSON object containing the feature columns and a set of values. We will get back the answer from the classifier [0] .
To build the cluster we will use a docker-compose file that will start all the docker containers needed: zookeeper and a broker.
Now very briefly, kafka is a distributed streaming platform capable of handling a large number of messages, that are organized or grouped together into topics. In order to be able to process a topic in parallel, it has to be split into partitions, and the data from these partitions are stored into separate machines called brokers. And finally, zookeeper is used to manage the resources of the brokers in the clusters.To read or write into a kafka cluster we need a broker address and a topic.
The docker-compose will start zookeper on port 2181 , a kafka broker on port 9092. Besides that we use another docker container kafka-create-topic for the sole purpose to create a topic (called test) in the kafka broker.
To start the kafka cluster, we have to run the following command line instruction in the same folder where we have defined the docker compose file:
docker-compose up
This will start all the docker containers with logs. We should see something like this in the console:
To be able to consume data in realtime we first must write some messages into kafka. We will use the confluent_kafka library in python to write a producer:
We will send JSON messages having the format:
{ "columns":["V1","V2","V3","V4","V5","V6","V7","V8","V9","V10","V11","V12","V13","V14","V15","V16","V17","V18","V19","V20","V21","V22","V23","V24","V25","V26","V27","V28","Amount"], "data":[]}
It is the same format we use for the MLFlow web service, where data can contain multiple lists of values for the features.
For each message we write into the queue we also need to assign a key. We will assign a random one based on the uuid to achieve a good distribution into the cluster. In the end, we also run a flush command to ensure that all the messages are sent.
Once we run the confluent_kafka_producer we should receive a log telling us that the data has been sent correctly:
we’ve sent 6 messages to 127.0.0.1:9092
We have reached our final step in the tutorial. With the Faust framework we will run a simple worker that will consume data from Kafka and will apply the prediction on the new features. We need to create a separate python script for this one. First, we define our Faust app, and the topic:
app = faust.App( 'fraud_detection_app', broker='kafka://localhost:9092', value_serializer='raw',)kafka_topic = app.topic('test')
We define the broker from where we read and the serializer format. We are happy to use raw as we will just pass the data to the machine learning algorithm.
Now, let’s define the coroutine. In the Faust framework, it’s called anagent :
The agent is an asynchronous process. We connect to the Kafka topic, and for each value that we read, we do a call to the REST service and obtain a result. As expected, this will run immediately after new values are available in Kafka.
The script is finalised. Let’s name it fraud_detection_worker.py . Now we can run it. From a terminal started in the root of the project we need to type:
faust -A fraud_detection_worker worker -l info
This will start a worker, which is an instance of the app. If we need more computing power, we can start additional workers.
If everything is running fine, we will start to see the following logs:
Input data: b'{"columns": ["V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17", "V18", "V19", "V20", "V21", "V22", "V23", "V24", "V25", "V26", "V27", "V28", "Amount"], "data": [[12.8, 0.029, 0.48, 0.98, 6.2, 29.1, 3.33, 1.2, 0.39, 75.1, 0.66, 11.2, 1.3, 0.2, 12.8, 0.029, 0.45, 0.98, 6.2, 29, 3.33, 1.2, 0.39, 75.3, 0.3, 2.2, 1.3, 2.2, 1.01]]}'Fraud detection result: [0]
We have reached the end of this tutorial. I hope you enjoyed it and find it useful. We saw how now we have the option to use a pure python framework to do real-time data processing. This is a great advantage as a lot of the data science work out there is in this programming language. | [
{
"code": null,
"e": 428,
"s": 172,
"text": "In this tutorial we will learn to start a Kafka cluster locally, to write a producer that sends messages, to create a simple machine learning training process for fraud detection, to expose the model via a REST interface and to do prediction in real-time."
},
{
"code": null,
"e": 470,
"s": 428,
"text": "The main frameworks that we will use are:"
},
{
"code": null,
"e": 559,
"s": 470,
"text": "Faust: stream processing library, using the async/away paradigm and requires python 3.6+"
},
{
"code": null,
"e": 636,
"s": 559,
"text": "Kafka: we will use the confluent version for kafka as our streaming platform"
},
{
"code": null,
"e": 732,
"s": 636,
"text": "MLFlow: an open-source platform used to monitor and save machine learning models after training"
},
{
"code": null,
"e": 777,
"s": 732,
"text": "Jupyter lab: our environment to run the code"
},
{
"code": null,
"e": 892,
"s": 777,
"text": "We will also need some data for our training. We can use a CSV source from a Kaggle credit card fraud competition."
},
{
"code": null,
"e": 922,
"s": 892,
"text": "TL;DR: The code is on GitHub."
},
{
"code": null,
"e": 1144,
"s": 922,
"text": "Let’s first build our fraud detection model. We will read the CSV data representing credit card transactions and apply a simple binary logistic regression classification between the two classes 0(not fraud) and 1(fraud) ."
},
{
"code": null,
"e": 1715,
"s": 1144,
"text": "df = pd.read_csv('creditcard.csv')df.dtypesTime float64V1 float64V2 float64V3 float64V4 float64V5 float64V6 float64V7 float64V8 float64V9 float64V10 float64V11 float64V12 float64V13 float64V14 float64V15 float64V16 float64V17 float64V18 float64V19 float64V20 float64V21 float64V22 float64V23 float64V24 float64V25 float64V26 float64V27 float64V28 float64Amount float64Class int64"
},
{
"code": null,
"e": 1851,
"s": 1715,
"text": "As we can see, most of the columns that we read are float , except the Class , which is our target variable. Now let’s do the training:"
},
{
"code": null,
"e": 2125,
"s": 1851,
"text": "x_name = df.iloc[:, 1:30].columnsy_name = df.iloc[:1, 30: ].columnsdata_x = df[x_name]data_y = df[y_name]train_x, test_x, train_y, test_y = train_test_split(data_x, data_y, train_size=0.7, test_size=0.3)model = LogisticRegression()model.fit(train_x, train_y.values.ravel())"
},
{
"code": null,
"e": 2270,
"s": 2125,
"text": "For features we use V1 — V28 and Amount . We do the split between train and test data, and fit the model. We can check some performance metrics:"
},
{
"code": null,
"e": 2486,
"s": 2270,
"text": "pred_y = model.predict(test_x)accuracy_score(test_y, pred_y)0.9993094811745842f1_score(test_y, pred_y)0.7773584905660378precision_score(test_y, pred_y)0.8272727272727273recall_score(test_y, pred_y)0.6776315789473685"
},
{
"code": null,
"e": 2642,
"s": 2486,
"text": "If we just use only accuracy as a metric we can shot ourselves in the foot. Always use better performance indicators like f1_score , precision and recall ."
},
{
"code": null,
"e": 2704,
"s": 2642,
"text": "After the training we can save our new fraud detection model:"
},
{
"code": null,
"e": 2759,
"s": 2704,
"text": "mlflow.sklearn.save_model(model, path='./fraud_model')"
},
{
"code": null,
"e": 2842,
"s": 2759,
"text": "We use the sklearn module inside MLFlow as this will help us with the servis part."
},
{
"code": null,
"e": 2924,
"s": 2842,
"text": "Let’s start a terminal in the root of our project and type the following command:"
},
{
"code": null,
"e": 2959,
"s": 2924,
"text": "mlflow models serve -m fraud_model"
},
{
"code": null,
"e": 3309,
"s": 2959,
"text": "This will take a little bit of time, as additionally to deploying a microservice, it will also create a conda environment. This is to ensure that next time when we do the deployment we have our dependencies locked at a certain version and in a separate virtual environment. If everything runs fine, we will notice that we have a url for our service:"
},
{
"code": null,
"e": 3345,
"s": 3309,
"text": "Listening at: http://127.0.0.1:5000"
},
{
"code": null,
"e": 3399,
"s": 3345,
"text": "We can do a quick test from the terminal using cURL :"
},
{
"code": null,
"e": 3816,
"s": 3399,
"text": "curl http://127.0.0.1:5000/invocations -H 'Content-Type: application/json' -d '{ \"columns\":[\"V1\",\"V2\",\"V3\",\"V4\",\"V5\",\"V6\",\"V7\",\"V8\",\"V9\",\"V10\",\"V11\",\"V12\",\"V13\",\"V14\",\"V15\",\"V16\",\"V17\",\"V18\",\"V19\",\"V20\",\"V21\",\"V22\",\"V23\",\"V24\",\"V25\",\"V26\",\"V27\",\"V28\",\"Amount\"], \"data\":[[12.8,0.029,0.48,0.98,6.2,29.1,3.33,1.2,0.39,75.1,0.66,1.2,1.3,44.2,12.8,0.029,0.48,0.98,6.2,29,3.33,1.2,0.39,75.3,0.66,1.2,1.3,44.2,1.1]]}'"
},
{
"code": null,
"e": 3972,
"s": 3816,
"text": "We are sending a POST request using a JSON object containing the feature columns and a set of values. We will get back the answer from the classifier [0] ."
},
{
"code": null,
"e": 4101,
"s": 3972,
"text": "To build the cluster we will use a docker-compose file that will start all the docker containers needed: zookeeper and a broker."
},
{
"code": null,
"e": 4596,
"s": 4101,
"text": "Now very briefly, kafka is a distributed streaming platform capable of handling a large number of messages, that are organized or grouped together into topics. In order to be able to process a topic in parallel, it has to be split into partitions, and the data from these partitions are stored into separate machines called brokers. And finally, zookeeper is used to manage the resources of the brokers in the clusters.To read or write into a kafka cluster we need a broker address and a topic."
},
{
"code": null,
"e": 4817,
"s": 4596,
"text": "The docker-compose will start zookeper on port 2181 , a kafka broker on port 9092. Besides that we use another docker container kafka-create-topic for the sole purpose to create a topic (called test) in the kafka broker."
},
{
"code": null,
"e": 4965,
"s": 4817,
"text": "To start the kafka cluster, we have to run the following command line instruction in the same folder where we have defined the docker compose file:"
},
{
"code": null,
"e": 4983,
"s": 4965,
"text": "docker-compose up"
},
{
"code": null,
"e": 5086,
"s": 4983,
"text": "This will start all the docker containers with logs. We should see something like this in the console:"
},
{
"code": null,
"e": 5242,
"s": 5086,
"text": "To be able to consume data in realtime we first must write some messages into kafka. We will use the confluent_kafka library in python to write a producer:"
},
{
"code": null,
"e": 5288,
"s": 5242,
"text": "We will send JSON messages having the format:"
},
{
"code": null,
"e": 5488,
"s": 5288,
"text": "{ \"columns\":[\"V1\",\"V2\",\"V3\",\"V4\",\"V5\",\"V6\",\"V7\",\"V8\",\"V9\",\"V10\",\"V11\",\"V12\",\"V13\",\"V14\",\"V15\",\"V16\",\"V17\",\"V18\",\"V19\",\"V20\",\"V21\",\"V22\",\"V23\",\"V24\",\"V25\",\"V26\",\"V27\",\"V28\",\"Amount\"], \"data\":[]}"
},
{
"code": null,
"e": 5611,
"s": 5488,
"text": "It is the same format we use for the MLFlow web service, where data can contain multiple lists of values for the features."
},
{
"code": null,
"e": 5859,
"s": 5611,
"text": "For each message we write into the queue we also need to assign a key. We will assign a random one based on the uuid to achieve a good distribution into the cluster. In the end, we also run a flush command to ensure that all the messages are sent."
},
{
"code": null,
"e": 5974,
"s": 5859,
"text": "Once we run the confluent_kafka_producer we should receive a log telling us that the data has been sent correctly:"
},
{
"code": null,
"e": 6014,
"s": 5974,
"text": "we’ve sent 6 messages to 127.0.0.1:9092"
},
{
"code": null,
"e": 6304,
"s": 6014,
"text": "We have reached our final step in the tutorial. With the Faust framework we will run a simple worker that will consume data from Kafka and will apply the prediction on the new features. We need to create a separate python script for this one. First, we define our Faust app, and the topic:"
},
{
"code": null,
"e": 6442,
"s": 6304,
"text": "app = faust.App( 'fraud_detection_app', broker='kafka://localhost:9092', value_serializer='raw',)kafka_topic = app.topic('test')"
},
{
"code": null,
"e": 6598,
"s": 6442,
"text": "We define the broker from where we read and the serializer format. We are happy to use raw as we will just pass the data to the machine learning algorithm."
},
{
"code": null,
"e": 6677,
"s": 6598,
"text": "Now, let’s define the coroutine. In the Faust framework, it’s called anagent :"
},
{
"code": null,
"e": 6913,
"s": 6677,
"text": "The agent is an asynchronous process. We connect to the Kafka topic, and for each value that we read, we do a call to the REST service and obtain a result. As expected, this will run immediately after new values are available in Kafka."
},
{
"code": null,
"e": 7067,
"s": 6913,
"text": "The script is finalised. Let’s name it fraud_detection_worker.py . Now we can run it. From a terminal started in the root of the project we need to type:"
},
{
"code": null,
"e": 7114,
"s": 7067,
"text": "faust -A fraud_detection_worker worker -l info"
},
{
"code": null,
"e": 7239,
"s": 7114,
"text": "This will start a worker, which is an instance of the app. If we need more computing power, we can start additional workers."
},
{
"code": null,
"e": 7311,
"s": 7239,
"text": "If everything is running fine, we will start to see the following logs:"
},
{
"code": null,
"e": 7740,
"s": 7311,
"text": "Input data: b'{\"columns\": [\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\", \"V8\", \"V9\", \"V10\", \"V11\", \"V12\", \"V13\", \"V14\", \"V15\", \"V16\", \"V17\", \"V18\", \"V19\", \"V20\", \"V21\", \"V22\", \"V23\", \"V24\", \"V25\", \"V26\", \"V27\", \"V28\", \"Amount\"], \"data\": [[12.8, 0.029, 0.48, 0.98, 6.2, 29.1, 3.33, 1.2, 0.39, 75.1, 0.66, 11.2, 1.3, 0.2, 12.8, 0.029, 0.45, 0.98, 6.2, 29, 3.33, 1.2, 0.39, 75.3, 0.3, 2.2, 1.3, 2.2, 1.01]]}'Fraud detection result: [0]"
}
] |
Python Regex Metacharacters - GeeksforGeeks | 01 Oct, 2020
Metacharacters are considered as the building blocks of regular expressions. Regular expressions are patterns used to match character combinations in the strings. Metacharacter has special meaning in finding patterns and are mostly used to define the search criteria and any text manipulations.
Some of the mostly used metacharacters along with their uses are as follows:
\w\w\w\w = geek
\w\w\w =! geek
geek[sy] = geeky
geek[sy] != geeki
Regular expressions can be built by metacharacters, and patterns can be processed using a library in Python for Regular Expressions known as “re”.
import re # used to import regular expressions
The inbuilt library can be used to compile patterns, find patterns, etc.
Example: In the below code, we will generate all the patterns based on the given regular expression
Python3
import re '''Meta characters - * - 0 or more+ - 1 or more? - 0 or 1{m} - m times{m,n} - min m and max n''' test_phrase = 'sddsd..sssddd...sdddsddd...dsds...dsssss...sdddd'test_patterns = [r'sd*', # s followed by zero or more d's r'sd+', # s followed by one or more d's r'sd?', # s followed by zero or one d's r'sd{3}', # s followed by three d's r'sd{2,3}', # s followed by two to three d's ] def multi_re_find(test_patterns, test_phrase): for pattern in test_patterns: compiledPattern = re.compile(pattern) print('finding {} in test_phrase'.format(pattern)) print(re.findall(compiledPattern, test_phrase)) multi_re_find(test_patterns, test_phrase)
Output:
finding sd* in test_phrase[‘sdd’, ‘sd’, ‘s’, ‘s’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sd’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘sdddd’]finding sd+ in test_phrase[‘sdd’, ‘sd’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sd’, ‘sdddd’]finding sd? in test_phrase[‘sd’, ‘sd’, ‘s’, ‘s’, ‘sd’, ‘sd’, ‘sd’, ‘sd’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘sd’]finding sd{3} in test_phrase[‘sddd’, ‘sddd’, ‘sddd’, ‘sddd’]finding sd{2,3} in test_phrase[‘sdd’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sddd’]
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 24587,
"s": 24292,
"text": "Metacharacters are considered as the building blocks of regular expressions. Regular expressions are patterns used to match character combinations in the strings. Metacharacter has special meaning in finding patterns and are mostly used to define the search criteria and any text manipulations."
},
{
"code": null,
"e": 24664,
"s": 24587,
"text": "Some of the mostly used metacharacters along with their uses are as follows:"
},
{
"code": null,
"e": 24680,
"s": 24664,
"text": "\\w\\w\\w\\w = geek"
},
{
"code": null,
"e": 24695,
"s": 24680,
"text": "\\w\\w\\w =! geek"
},
{
"code": null,
"e": 24712,
"s": 24695,
"text": "geek[sy] = geeky"
},
{
"code": null,
"e": 24730,
"s": 24712,
"text": "geek[sy] != geeki"
},
{
"code": null,
"e": 24877,
"s": 24730,
"text": "Regular expressions can be built by metacharacters, and patterns can be processed using a library in Python for Regular Expressions known as “re”."
},
{
"code": null,
"e": 24925,
"s": 24877,
"text": "import re # used to import regular expressions"
},
{
"code": null,
"e": 24999,
"s": 24925,
"text": "The inbuilt library can be used to compile patterns, find patterns, etc. "
},
{
"code": null,
"e": 25099,
"s": 24999,
"text": "Example: In the below code, we will generate all the patterns based on the given regular expression"
},
{
"code": null,
"e": 25107,
"s": 25099,
"text": "Python3"
},
{
"code": "import re '''Meta characters - * - 0 or more+ - 1 or more? - 0 or 1{m} - m times{m,n} - min m and max n''' test_phrase = 'sddsd..sssddd...sdddsddd...dsds...dsssss...sdddd'test_patterns = [r'sd*', # s followed by zero or more d's r'sd+', # s followed by one or more d's r'sd?', # s followed by zero or one d's r'sd{3}', # s followed by three d's r'sd{2,3}', # s followed by two to three d's ] def multi_re_find(test_patterns, test_phrase): for pattern in test_patterns: compiledPattern = re.compile(pattern) print('finding {} in test_phrase'.format(pattern)) print(re.findall(compiledPattern, test_phrase)) multi_re_find(test_patterns, test_phrase)",
"e": 25906,
"s": 25107,
"text": null
},
{
"code": null,
"e": 25914,
"s": 25906,
"text": "Output:"
},
{
"code": null,
"e": 26348,
"s": 25914,
"text": "finding sd* in test_phrase[‘sdd’, ‘sd’, ‘s’, ‘s’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sd’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘sdddd’]finding sd+ in test_phrase[‘sdd’, ‘sd’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sd’, ‘sdddd’]finding sd? in test_phrase[‘sd’, ‘sd’, ‘s’, ‘s’, ‘sd’, ‘sd’, ‘sd’, ‘sd’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘sd’]finding sd{3} in test_phrase[‘sddd’, ‘sddd’, ‘sddd’, ‘sddd’]finding sd{2,3} in test_phrase[‘sdd’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sddd’]"
},
{
"code": null,
"e": 26361,
"s": 26348,
"text": "python-regex"
},
{
"code": null,
"e": 26368,
"s": 26361,
"text": "Python"
},
{
"code": null,
"e": 26466,
"s": 26368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26498,
"s": 26466,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26540,
"s": 26498,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26596,
"s": 26540,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26638,
"s": 26596,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26669,
"s": 26638,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26724,
"s": 26669,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26746,
"s": 26724,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26785,
"s": 26746,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26814,
"s": 26785,
"text": "Create a directory in Python"
}
] |
ATM Management System using C++ - GeeksforGeeks | 07 Jul, 2021
ATMs are Automated Teller Machines that are used to carry day-to-day financial transactions. ATMs can be used to withdraw money or to deposit money or even to know the information of an account like the balance amount, etc. They are convenient and easy to use, it allows consumers to perform quick self-service transactions.
In this article, we will discuss the ATM Management System in C++ which is an application that provides users with every aspect that an actual Automated Teller Machine i.e., ATM should have. It is a menu-driven program having ATM functions which include:
Enter Name, Account number, Account type to be shown during transactions.Shows the information about the person who is doing the transaction.Enter amount to deposited in the account.Shows the Balance in the account.Enter amount to be withdrawn from the account, and then it shows available balance.Cancel the transaction.
Enter Name, Account number, Account type to be shown during transactions.
Shows the information about the person who is doing the transaction.
Enter amount to deposited in the account.
Shows the Balance in the account.
Enter amount to be withdrawn from the account, and then it shows available balance.
Cancel the transaction.
Approach: This program uses basic concepts of class, Access Modifiers in C++, data types, variables, Switch Case, etc. Below are the functionalities that are to be implemented:
setvalue(): This function is used here to set the data using basic input and output method in C++ i.e., cout and cin statements which displays and take input from the keyboard i.e., from the user respectively.
showvalue(): This function is used to print the data.
deposit(): This function helps to deposit money in a particular account.
showbal(): This function shows the total balance available after deposition.
withdrawl(): This function helps to withdraw money from the account.
main(): This function there is a simple switch case (to make choices) inside an infinite while loop so that every time user gets to select choices.
Below is the C++ program using the above approach:
C++
// C++ program to implement the ATM// Management System#include <iostream>#include <stdlib.h>#include <string.h>using namespace std;class Bank { // Private variables used inside classprivate: string name; int accnumber; char type[10]; int amount = 0; int tot = 0; // Public variablespublic: // Function to set the person's data void setvalue() { cout << "Enter name\n"; cin.ignore(); // To use space in string getline(cin, name); cout << "Enter Account number\n"; cin >> accnumber; cout << "Enter Account type\n"; cin >> type; cout << "Enter Balance\n"; cin >> tot; } // Function to display the required data void showdata() { cout << "Name:" << name << endl; cout << "Account No:" << accnumber << endl; cout << "Account type:" << type << endl; cout << "Balance:" << tot << endl; } // Function to deposit the amount in ATM void deposit() { cout << "\nEnter amount to be Deposited\n"; cin >> amount; } // Function to show the balance amount void showbal() { tot = tot + amount; cout << "\nTotal balance is: " << tot; } // Function to withdraw the amount in ATM void withdrawl() { int a, avai_balance; cout << "Enter amount to withdraw\n"; cin >> a; avai_balance = tot - a; cout << "Available Balance is" << avai_balance; }}; // Driver Codeint main(){ // Object of class Bank b; int choice; // Infinite while loop to choose // options everytime while (1) { cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~" << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << "~~~WELCOME~~~~~~~~~~~~~~~~~~" << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << "~~~~~~~~~\n\n"; cout << "Enter Your Choice\n"; cout << "\t1. Enter name, Account " << "number, Account type\n"; cout << "\t2. Balance Enquiry\n"; cout << "\t3. Deposit Money\n"; cout << "\t4. Show Total balance\n"; cout << "\t5. Withdraw Money\n"; cout << "\t6. Cancel\n"; cin >> choice; // Choices to select from switch (choice) { case 1: b.setvalue(); break; case 2: b.showdata(); break; case 3: b.deposit(); break; case 4: b.showbal(); break; case 5: b.withdrawl(); break; case 6: exit(1); break; default: cout << "\nInvalid choice\n"; } }}
Output:
Displaying the choices:
For Choice 1:
For Choice 3:
For Choice 2:
For Choice 5:
abhishek0719kadiyan
Technical Scripter 2020
C++
C++ Programs
Project
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Iterators in C++ STL
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
CSV file management using C++ | [
{
"code": null,
"e": 24122,
"s": 24094,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 24447,
"s": 24122,
"text": "ATMs are Automated Teller Machines that are used to carry day-to-day financial transactions. ATMs can be used to withdraw money or to deposit money or even to know the information of an account like the balance amount, etc. They are convenient and easy to use, it allows consumers to perform quick self-service transactions."
},
{
"code": null,
"e": 24702,
"s": 24447,
"text": "In this article, we will discuss the ATM Management System in C++ which is an application that provides users with every aspect that an actual Automated Teller Machine i.e., ATM should have. It is a menu-driven program having ATM functions which include:"
},
{
"code": null,
"e": 25024,
"s": 24702,
"text": "Enter Name, Account number, Account type to be shown during transactions.Shows the information about the person who is doing the transaction.Enter amount to deposited in the account.Shows the Balance in the account.Enter amount to be withdrawn from the account, and then it shows available balance.Cancel the transaction."
},
{
"code": null,
"e": 25098,
"s": 25024,
"text": "Enter Name, Account number, Account type to be shown during transactions."
},
{
"code": null,
"e": 25167,
"s": 25098,
"text": "Shows the information about the person who is doing the transaction."
},
{
"code": null,
"e": 25209,
"s": 25167,
"text": "Enter amount to deposited in the account."
},
{
"code": null,
"e": 25243,
"s": 25209,
"text": "Shows the Balance in the account."
},
{
"code": null,
"e": 25327,
"s": 25243,
"text": "Enter amount to be withdrawn from the account, and then it shows available balance."
},
{
"code": null,
"e": 25351,
"s": 25327,
"text": "Cancel the transaction."
},
{
"code": null,
"e": 25528,
"s": 25351,
"text": "Approach: This program uses basic concepts of class, Access Modifiers in C++, data types, variables, Switch Case, etc. Below are the functionalities that are to be implemented:"
},
{
"code": null,
"e": 25738,
"s": 25528,
"text": "setvalue(): This function is used here to set the data using basic input and output method in C++ i.e., cout and cin statements which displays and take input from the keyboard i.e., from the user respectively."
},
{
"code": null,
"e": 25792,
"s": 25738,
"text": "showvalue(): This function is used to print the data."
},
{
"code": null,
"e": 25865,
"s": 25792,
"text": "deposit(): This function helps to deposit money in a particular account."
},
{
"code": null,
"e": 25942,
"s": 25865,
"text": "showbal(): This function shows the total balance available after deposition."
},
{
"code": null,
"e": 26011,
"s": 25942,
"text": "withdrawl(): This function helps to withdraw money from the account."
},
{
"code": null,
"e": 26159,
"s": 26011,
"text": "main(): This function there is a simple switch case (to make choices) inside an infinite while loop so that every time user gets to select choices."
},
{
"code": null,
"e": 26210,
"s": 26159,
"text": "Below is the C++ program using the above approach:"
},
{
"code": null,
"e": 26214,
"s": 26210,
"text": "C++"
},
{
"code": "// C++ program to implement the ATM// Management System#include <iostream>#include <stdlib.h>#include <string.h>using namespace std;class Bank { // Private variables used inside classprivate: string name; int accnumber; char type[10]; int amount = 0; int tot = 0; // Public variablespublic: // Function to set the person's data void setvalue() { cout << \"Enter name\\n\"; cin.ignore(); // To use space in string getline(cin, name); cout << \"Enter Account number\\n\"; cin >> accnumber; cout << \"Enter Account type\\n\"; cin >> type; cout << \"Enter Balance\\n\"; cin >> tot; } // Function to display the required data void showdata() { cout << \"Name:\" << name << endl; cout << \"Account No:\" << accnumber << endl; cout << \"Account type:\" << type << endl; cout << \"Balance:\" << tot << endl; } // Function to deposit the amount in ATM void deposit() { cout << \"\\nEnter amount to be Deposited\\n\"; cin >> amount; } // Function to show the balance amount void showbal() { tot = tot + amount; cout << \"\\nTotal balance is: \" << tot; } // Function to withdraw the amount in ATM void withdrawl() { int a, avai_balance; cout << \"Enter amount to withdraw\\n\"; cin >> a; avai_balance = tot - a; cout << \"Available Balance is\" << avai_balance; }}; // Driver Codeint main(){ // Object of class Bank b; int choice; // Infinite while loop to choose // options everytime while (1) { cout << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~\" << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << \"~~~WELCOME~~~~~~~~~~~~~~~~~~\" << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << \"~~~~~~~~~\\n\\n\"; cout << \"Enter Your Choice\\n\"; cout << \"\\t1. Enter name, Account \" << \"number, Account type\\n\"; cout << \"\\t2. Balance Enquiry\\n\"; cout << \"\\t3. Deposit Money\\n\"; cout << \"\\t4. Show Total balance\\n\"; cout << \"\\t5. Withdraw Money\\n\"; cout << \"\\t6. Cancel\\n\"; cin >> choice; // Choices to select from switch (choice) { case 1: b.setvalue(); break; case 2: b.showdata(); break; case 3: b.deposit(); break; case 4: b.showbal(); break; case 5: b.withdrawl(); break; case 6: exit(1); break; default: cout << \"\\nInvalid choice\\n\"; } }}",
"e": 28868,
"s": 26214,
"text": null
},
{
"code": null,
"e": 28880,
"s": 28872,
"text": "Output:"
},
{
"code": null,
"e": 28908,
"s": 28882,
"text": "Displaying the choices: "
},
{
"code": null,
"e": 28924,
"s": 28908,
"text": "For Choice 1: "
},
{
"code": null,
"e": 28940,
"s": 28924,
"text": "For Choice 3: "
},
{
"code": null,
"e": 28956,
"s": 28940,
"text": "For Choice 2: "
},
{
"code": null,
"e": 28972,
"s": 28956,
"text": "For Choice 5: "
},
{
"code": null,
"e": 28994,
"s": 28974,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 29018,
"s": 28994,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29022,
"s": 29018,
"text": "C++"
},
{
"code": null,
"e": 29035,
"s": 29022,
"text": "C++ Programs"
},
{
"code": null,
"e": 29043,
"s": 29035,
"text": "Project"
},
{
"code": null,
"e": 29062,
"s": 29043,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29066,
"s": 29062,
"text": "CPP"
},
{
"code": null,
"e": 29164,
"s": 29066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29173,
"s": 29164,
"text": "Comments"
},
{
"code": null,
"e": 29186,
"s": 29173,
"text": "Old Comments"
},
{
"code": null,
"e": 29214,
"s": 29186,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29234,
"s": 29214,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29267,
"s": 29234,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29291,
"s": 29267,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 29312,
"s": 29291,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 29347,
"s": 29312,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29373,
"s": 29347,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 29432,
"s": 29373,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29476,
"s": 29432,
"text": "Program to print ASCII Value of a character"
}
] |
How To Learn ReactJS: A Complete Guide For Beginners - GeeksforGeeks | 25 Aug, 2021
Every front-end developer and web developer knows how frustrating and painful it is to write the same code at multiple places. If they need to add a button on multiple pages they are forced to do a lot of code. Developers using other frameworks face the challenges to rework most codes even when crafting components that changed frequently. Developers wanted a framework or library which allow them to break down complex components and reuse the codes to complete their projects faster. Here React comes in and solved this problem.
React is the most popular javascript library for building user interfaces. It is fast, flexible and it also has a strong community sitting online to help you every time. The coolest thing about React is it’s based on components, you break down your complex code into individual pieces i.e components and that helps developers in organizing their code in a better way. A lot of companies are moving to React and that’s the reason most of the beginners and experienced developers also expanding their knowledge learning this library. Learning this library is a daunting task. You watch a lot of tutorials and you try to get the best material to learn this library but it can become overwhelming if you don’t know the right path or step-by-step process to learn it. We are going to discuss a roadmap to get started with React and the fundamental prerequisites (checklist) to jump into React. Let’s get started...
Basic knowledge of HTML, CSS, and JavaScript.Some ES6 features of Javascript likeLet and ConstArrow FunctionsClass and ‘this’ keywordFundamentals of NodeJS & Code Editors
Basic knowledge of HTML, CSS, and JavaScript.
Some ES6 features of Javascript likeLet and ConstArrow FunctionsClass and ‘this’ keyword
Let and Const
Arrow Functions
Class and ‘this’ keyword
Fundamentals of NodeJS & Code Editors
If you are an experienced developer then skip this section, for beginners here is a quick introduction..
Every front-end developer starts their journey with these three things. These are the basic foundation of foundations of frontend web development and they all work together to create a fully functional web app/website.
Consider a Human body as a website or web app.
HTML can be considered as the structure or “Skeleton”, of the body which tells what has to come where.
CSS defines the style which is the “Skin, Flesh”, tells how a particular segment should look like what should be its Color, Height, Width, etc.,
JavaScript defines the functionality which is the part of the “Brain” which tells each of the parts to do what.
ES6 is the version of JavaScript and there are a lot of features of ES6. To get started with React you need to know about Arrow Functions, Let and Const, Class, and ‘this’ keyword.
Arrow Function: Arrow function allows you to write the shorter syntax for function. It makes your code clean and more readable. Check the code snippet below...
Javascript
// Old methodfunction greet(){ console.log('GeeksforGeeks');}var greet1 = function(){ console.log('GeeksforGeeks');}//ES6 methodvar greet2 = () => { console.log('GeeksforGeeks');}
Let and Const: You will be using ‘let’ and ‘const’ instead of ‘var’ keyword. Both are different than var, in simple words...
Let defines a local variable limiting their scope to the block in which they are declared.
Const defines a constant variable whose values cannot be changed.
Class and ‘this’ Keyword: You will have to learn the Object-Oriented Programming concepts like Class, Method, Objects in ES6. You might have learned about these concepts in other languages such as C++ or Java. Read about this from ES6 | Classes and follow this video tutorial to understand this.If we talk about the ‘this’ keyword so it represents the current object in execution. Make sure that you clear the concept of the ‘this’ keyword which is quite confusing for a lot of developers. Along with that learn what is Call, Apply and Bind methods (used to bind/connect the ‘this’ keyword to an object).
Understanding NodeJS fundamentals is important to work on ReactJS. In simple language, NodeJS is an execution environment for javascript. A lot of people consider that it’s a programming language which is not true. Every browser has JavaScript Engine which is embedded into browsers, for example, Chrome has a V8 engine and Mozilla Firefox has SpiderMonkey. You cannot perform any operation outside the browser like File operations, OS operations, Network Operations and so here Node came into existence. Node allows you to do all these operations outside the browser. It is embedded with chrome’s V8 engine.Now you might have quite familiar with NodeJs so let’s discuss are all the features of Node you must know to learn React.
NPM (Node Package Manager): NPM is a package manager to install node modules and packages to your project just like PIP for python.
IMPORT and EXPORT keywords. Import: Once you will install the Node module using NPM in your project you will have to use the ‘import’ keyword to use that module.Export: Use this keyword when you are creating a module/component and you have to return only a part, not all the methods and variables.
Import: Once you will install the Node module using NPM in your project you will have to use the ‘import’ keyword to use that module.
Export: Use this keyword when you are creating a module/component and you have to return only a part, not all the methods and variables.
Read the article ReactJS | Importing and Exporting to get more help on this topic. You can use any code editor to work on React. A lot of web developers mostly prefer Visual Studio Code — VS CODE — (Highly recommended), Sublime Text, or Atom.
Fundamentals: All the above things we have discussed were the prerequisite of ReactJS. Now once you learn all the above things it’s time to jump into React. Understand the basic concept of React first. We are going to give you an overview here.React is a Javascript library developed by Facebook to build interactive User Interfaces. It follows the Component-based architecture which means you will divide your whole UI part into reusable components, all are made separately and finally fitted into a parent component which is then rendered. Below are some important topics to learn in ReactJS...
Component Architecture (already discussed).
State: Basically ‘state’ holds synchronous variables. If you change the value of a state variable then the change is reflected immediately in all the places that particular variable is used.
Props: are just like arguments passed in a function or method. In React props (arguments) are passed into an HTML tag as input arguments.
Functional Components, Class Components.
Styling(CSS) in React.
learn how to connect to APIs with React apps.
Read the tutorial ReactJS | GeeksforGeeks, React Official Tutorial, and watch the video ReactJS Tutorial. Once you will have a basic understanding of React, you can start building some basic projects such as...
Simple todo-app
Simple calculator app
Build a shopping cart
Display GitHub’s user stats using GitHub API
React Router: React routing will help you to understand how routing works in an application of React. How to load the content of a specific page or how to redirect to a specific page using React Router. For example, to redirect from the ‘home’ page to the ‘blog’ page you will have to set routing so that it can only display the content of the ‘blog’ page. Understand this from the video React Router for Beginners and React Router. Once you have an understanding of React Router you can make some projects like A simple CURD application or Hacker News clone
Webpack: Webpack is a module bundler in Javascript that helps you to maintain dependencies as static files for your project so developers don’t have to do it. Webpack also comes with loaders. Loaders help run specific tasks around your project. Watch the video Webpack Tutorial and read about this on Webpack official docs.
Server Rendering: Learning this concept will help you to create components in the server and render that as HTML in your browser and when all the JavaScript modules are downloaded in the browser, React takes the stage. It’s one of the coolest features to React and it can be used with any of the back-end technologies. Understand this concept from the link React server rendering by Tyler McGinnis.
Redux: In a complex application, you will have to manage states across components. Redux which is a javascript library solves this problem and helps you to maintain the application states. In Redux you store all your states in a single source. Understand this concept in a better way from the link Introduction to React-Redux and React Redux Tutorial for Beginners.
This is all about the roadmap to learn React from the beginning. We hope this was helpful !!!
chaitu17
Pushpender007
react-js
GBlog
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
GET and POST requests using Python
Working with csv files in Python
Types of Software Testing
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24552,
"s": 24524,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 25086,
"s": 24552,
"text": "Every front-end developer and web developer knows how frustrating and painful it is to write the same code at multiple places. If they need to add a button on multiple pages they are forced to do a lot of code. Developers using other frameworks face the challenges to rework most codes even when crafting components that changed frequently. Developers wanted a framework or library which allow them to break down complex components and reuse the codes to complete their projects faster. Here React comes in and solved this problem. "
},
{
"code": null,
"e": 25996,
"s": 25086,
"text": "React is the most popular javascript library for building user interfaces. It is fast, flexible and it also has a strong community sitting online to help you every time. The coolest thing about React is it’s based on components, you break down your complex code into individual pieces i.e components and that helps developers in organizing their code in a better way. A lot of companies are moving to React and that’s the reason most of the beginners and experienced developers also expanding their knowledge learning this library. Learning this library is a daunting task. You watch a lot of tutorials and you try to get the best material to learn this library but it can become overwhelming if you don’t know the right path or step-by-step process to learn it. We are going to discuss a roadmap to get started with React and the fundamental prerequisites (checklist) to jump into React. Let’s get started..."
},
{
"code": null,
"e": 26167,
"s": 25996,
"text": "Basic knowledge of HTML, CSS, and JavaScript.Some ES6 features of Javascript likeLet and ConstArrow FunctionsClass and ‘this’ keywordFundamentals of NodeJS & Code Editors"
},
{
"code": null,
"e": 26213,
"s": 26167,
"text": "Basic knowledge of HTML, CSS, and JavaScript."
},
{
"code": null,
"e": 26302,
"s": 26213,
"text": "Some ES6 features of Javascript likeLet and ConstArrow FunctionsClass and ‘this’ keyword"
},
{
"code": null,
"e": 26316,
"s": 26302,
"text": "Let and Const"
},
{
"code": null,
"e": 26332,
"s": 26316,
"text": "Arrow Functions"
},
{
"code": null,
"e": 26357,
"s": 26332,
"text": "Class and ‘this’ keyword"
},
{
"code": null,
"e": 26395,
"s": 26357,
"text": "Fundamentals of NodeJS & Code Editors"
},
{
"code": null,
"e": 26501,
"s": 26395,
"text": "If you are an experienced developer then skip this section, for beginners here is a quick introduction.. "
},
{
"code": null,
"e": 26720,
"s": 26501,
"text": "Every front-end developer starts their journey with these three things. These are the basic foundation of foundations of frontend web development and they all work together to create a fully functional web app/website."
},
{
"code": null,
"e": 26767,
"s": 26720,
"text": "Consider a Human body as a website or web app."
},
{
"code": null,
"e": 26870,
"s": 26767,
"text": "HTML can be considered as the structure or “Skeleton”, of the body which tells what has to come where."
},
{
"code": null,
"e": 27015,
"s": 26870,
"text": "CSS defines the style which is the “Skin, Flesh”, tells how a particular segment should look like what should be its Color, Height, Width, etc.,"
},
{
"code": null,
"e": 27127,
"s": 27015,
"text": "JavaScript defines the functionality which is the part of the “Brain” which tells each of the parts to do what."
},
{
"code": null,
"e": 27308,
"s": 27127,
"text": "ES6 is the version of JavaScript and there are a lot of features of ES6. To get started with React you need to know about Arrow Functions, Let and Const, Class, and ‘this’ keyword."
},
{
"code": null,
"e": 27468,
"s": 27308,
"text": "Arrow Function: Arrow function allows you to write the shorter syntax for function. It makes your code clean and more readable. Check the code snippet below..."
},
{
"code": null,
"e": 27479,
"s": 27468,
"text": "Javascript"
},
{
"code": "// Old methodfunction greet(){ console.log('GeeksforGeeks');}var greet1 = function(){ console.log('GeeksforGeeks');}//ES6 methodvar greet2 = () => { console.log('GeeksforGeeks');}",
"e": 27668,
"s": 27479,
"text": null
},
{
"code": null,
"e": 27793,
"s": 27668,
"text": "Let and Const: You will be using ‘let’ and ‘const’ instead of ‘var’ keyword. Both are different than var, in simple words..."
},
{
"code": null,
"e": 27884,
"s": 27793,
"text": "Let defines a local variable limiting their scope to the block in which they are declared."
},
{
"code": null,
"e": 27950,
"s": 27884,
"text": "Const defines a constant variable whose values cannot be changed."
},
{
"code": null,
"e": 28555,
"s": 27950,
"text": "Class and ‘this’ Keyword: You will have to learn the Object-Oriented Programming concepts like Class, Method, Objects in ES6. You might have learned about these concepts in other languages such as C++ or Java. Read about this from ES6 | Classes and follow this video tutorial to understand this.If we talk about the ‘this’ keyword so it represents the current object in execution. Make sure that you clear the concept of the ‘this’ keyword which is quite confusing for a lot of developers. Along with that learn what is Call, Apply and Bind methods (used to bind/connect the ‘this’ keyword to an object)."
},
{
"code": null,
"e": 29285,
"s": 28555,
"text": "Understanding NodeJS fundamentals is important to work on ReactJS. In simple language, NodeJS is an execution environment for javascript. A lot of people consider that it’s a programming language which is not true. Every browser has JavaScript Engine which is embedded into browsers, for example, Chrome has a V8 engine and Mozilla Firefox has SpiderMonkey. You cannot perform any operation outside the browser like File operations, OS operations, Network Operations and so here Node came into existence. Node allows you to do all these operations outside the browser. It is embedded with chrome’s V8 engine.Now you might have quite familiar with NodeJs so let’s discuss are all the features of Node you must know to learn React."
},
{
"code": null,
"e": 29417,
"s": 29285,
"text": "NPM (Node Package Manager): NPM is a package manager to install node modules and packages to your project just like PIP for python."
},
{
"code": null,
"e": 29715,
"s": 29417,
"text": "IMPORT and EXPORT keywords. Import: Once you will install the Node module using NPM in your project you will have to use the ‘import’ keyword to use that module.Export: Use this keyword when you are creating a module/component and you have to return only a part, not all the methods and variables."
},
{
"code": null,
"e": 29849,
"s": 29715,
"text": "Import: Once you will install the Node module using NPM in your project you will have to use the ‘import’ keyword to use that module."
},
{
"code": null,
"e": 29986,
"s": 29849,
"text": "Export: Use this keyword when you are creating a module/component and you have to return only a part, not all the methods and variables."
},
{
"code": null,
"e": 30229,
"s": 29986,
"text": "Read the article ReactJS | Importing and Exporting to get more help on this topic. You can use any code editor to work on React. A lot of web developers mostly prefer Visual Studio Code — VS CODE — (Highly recommended), Sublime Text, or Atom."
},
{
"code": null,
"e": 30826,
"s": 30229,
"text": "Fundamentals: All the above things we have discussed were the prerequisite of ReactJS. Now once you learn all the above things it’s time to jump into React. Understand the basic concept of React first. We are going to give you an overview here.React is a Javascript library developed by Facebook to build interactive User Interfaces. It follows the Component-based architecture which means you will divide your whole UI part into reusable components, all are made separately and finally fitted into a parent component which is then rendered. Below are some important topics to learn in ReactJS..."
},
{
"code": null,
"e": 30870,
"s": 30826,
"text": "Component Architecture (already discussed)."
},
{
"code": null,
"e": 31061,
"s": 30870,
"text": "State: Basically ‘state’ holds synchronous variables. If you change the value of a state variable then the change is reflected immediately in all the places that particular variable is used."
},
{
"code": null,
"e": 31199,
"s": 31061,
"text": "Props: are just like arguments passed in a function or method. In React props (arguments) are passed into an HTML tag as input arguments."
},
{
"code": null,
"e": 31240,
"s": 31199,
"text": "Functional Components, Class Components."
},
{
"code": null,
"e": 31263,
"s": 31240,
"text": "Styling(CSS) in React."
},
{
"code": null,
"e": 31309,
"s": 31263,
"text": "learn how to connect to APIs with React apps."
},
{
"code": null,
"e": 31520,
"s": 31309,
"text": "Read the tutorial ReactJS | GeeksforGeeks, React Official Tutorial, and watch the video ReactJS Tutorial. Once you will have a basic understanding of React, you can start building some basic projects such as..."
},
{
"code": null,
"e": 31536,
"s": 31520,
"text": "Simple todo-app"
},
{
"code": null,
"e": 31558,
"s": 31536,
"text": "Simple calculator app"
},
{
"code": null,
"e": 31580,
"s": 31558,
"text": "Build a shopping cart"
},
{
"code": null,
"e": 31625,
"s": 31580,
"text": "Display GitHub’s user stats using GitHub API"
},
{
"code": null,
"e": 32184,
"s": 31625,
"text": "React Router: React routing will help you to understand how routing works in an application of React. How to load the content of a specific page or how to redirect to a specific page using React Router. For example, to redirect from the ‘home’ page to the ‘blog’ page you will have to set routing so that it can only display the content of the ‘blog’ page. Understand this from the video React Router for Beginners and React Router. Once you have an understanding of React Router you can make some projects like A simple CURD application or Hacker News clone"
},
{
"code": null,
"e": 32508,
"s": 32184,
"text": "Webpack: Webpack is a module bundler in Javascript that helps you to maintain dependencies as static files for your project so developers don’t have to do it. Webpack also comes with loaders. Loaders help run specific tasks around your project. Watch the video Webpack Tutorial and read about this on Webpack official docs."
},
{
"code": null,
"e": 32907,
"s": 32508,
"text": "Server Rendering: Learning this concept will help you to create components in the server and render that as HTML in your browser and when all the JavaScript modules are downloaded in the browser, React takes the stage. It’s one of the coolest features to React and it can be used with any of the back-end technologies. Understand this concept from the link React server rendering by Tyler McGinnis."
},
{
"code": null,
"e": 33273,
"s": 32907,
"text": "Redux: In a complex application, you will have to manage states across components. Redux which is a javascript library solves this problem and helps you to maintain the application states. In Redux you store all your states in a single source. Understand this concept in a better way from the link Introduction to React-Redux and React Redux Tutorial for Beginners."
},
{
"code": null,
"e": 33368,
"s": 33273,
"text": "This is all about the roadmap to learn React from the beginning. We hope this was helpful !!! "
},
{
"code": null,
"e": 33377,
"s": 33368,
"text": "chaitu17"
},
{
"code": null,
"e": 33391,
"s": 33377,
"text": "Pushpender007"
},
{
"code": null,
"e": 33400,
"s": 33391,
"text": "react-js"
},
{
"code": null,
"e": 33406,
"s": 33400,
"text": "GBlog"
},
{
"code": null,
"e": 33423,
"s": 33406,
"text": "Web Technologies"
},
{
"code": null,
"e": 33521,
"s": 33423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33530,
"s": 33521,
"text": "Comments"
},
{
"code": null,
"e": 33543,
"s": 33530,
"text": "Old Comments"
},
{
"code": null,
"e": 33585,
"s": 33543,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 33610,
"s": 33585,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33645,
"s": 33610,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 33678,
"s": 33645,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 33704,
"s": 33678,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 33746,
"s": 33704,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 33779,
"s": 33746,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33822,
"s": 33779,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 33872,
"s": 33822,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
MongoDB query to select 10 most recent documents without changing order? | For this, use skip() in MongoDB. Under skip(), set “count() – 10” to get 10 most recent documents. Let us create a collection with documents −
> db.demo500.insertOne({value:10});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749c5987b6e0e9d18f55a")
}
> db.demo500.insertOne({value:1200});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749c8987b6e0e9d18f55b")
}
> db.demo500.insertOne({value:19});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749cb987b6e0e9d18f55c")
}
> db.demo500.insertOne({value:28});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749cf987b6e0e9d18f55d")
}
> db.demo500.insertOne({value:50});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749d1987b6e0e9d18f55e")
}
> db.demo500.insertOne({value:70});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749d4987b6e0e9d18f55f")
}
> db.demo500.insertOne({value:100});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749d7987b6e0e9d18f560")
}
> db.demo500.insertOne({value:10});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749d9987b6e0e9d18f561")
}
> db.demo500.insertOne({value:98});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749dc987b6e0e9d18f562")
}
> db.demo500.insertOne({value:80});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8749e0987b6e0e9d18f563")
}
> db.demo500.insertOne({value:75});{
"acknowledged" : true,
"insertedId" : ObjectId("5e874c73987b6e0e9d18f564")
}
> db.demo500.insertOne({value:68});{
"acknowledged" : true,
"insertedId" : ObjectId("5e874c78987b6e0e9d18f565")
}
Display all documents from a collection with the help of find() method −
> db.demo500.find();
This will produce the following output −
{ "_id" : ObjectId("5e8749c5987b6e0e9d18f55a"), "value" : 10 }
{ "_id" : ObjectId("5e8749c8987b6e0e9d18f55b"), "value" : 1200 }
{ "_id" : ObjectId("5e8749cb987b6e0e9d18f55c"), "value" : 19 }
{ "_id" : ObjectId("5e8749cf987b6e0e9d18f55d"), "value" : 28 }
{ "_id" : ObjectId("5e8749d1987b6e0e9d18f55e"), "value" : 50 }
{ "_id" : ObjectId("5e8749d4987b6e0e9d18f55f"), "value" : 70 }
{ "_id" : ObjectId("5e8749d7987b6e0e9d18f560"), "value" : 100 }
{ "_id" : ObjectId("5e8749d9987b6e0e9d18f561"), "value" : 10 }
{ "_id" : ObjectId("5e8749dc987b6e0e9d18f562"), "value" : 98 }
{ "_id" : ObjectId("5e8749e0987b6e0e9d18f563"), "value" : 80 }
{ "_id" : ObjectId("5e874c73987b6e0e9d18f564"), "value" : 75 }
{ "_id" : ObjectId("5e874c78987b6e0e9d18f565"), "value" : 68 }
Following is the query to select 10 most recent documents without changing the order −
> db.demo500.find().skip(db.demo500.count() - 10);
This will produce the following output −
{ "_id" : ObjectId("5e8749cb987b6e0e9d18f55c"), "value" : 19 }
{ "_id" : ObjectId("5e8749cf987b6e0e9d18f55d"), "value" : 28 }
{ "_id" : ObjectId("5e8749d1987b6e0e9d18f55e"), "value" : 50 }
{ "_id" : ObjectId("5e8749d4987b6e0e9d18f55f"), "value" : 70 }
{ "_id" : ObjectId("5e8749d7987b6e0e9d18f560"), "value" : 100 }
{ "_id" : ObjectId("5e8749d9987b6e0e9d18f561"), "value" : 10 }
{ "_id" : ObjectId("5e8749dc987b6e0e9d18f562"), "value" : 98 }
{ "_id" : ObjectId("5e8749e0987b6e0e9d18f563"), "value" : 80 }
{ "_id" : ObjectId("5e874c73987b6e0e9d18f564"), "value" : 75 }
{ "_id" : ObjectId("5e874c78987b6e0e9d18f565"), "value" : 68 } | [
{
"code": null,
"e": 1205,
"s": 1062,
"text": "For this, use skip() in MongoDB. Under skip(), set “count() – 10” to get 10 most recent documents. Let us create a collection with documents −"
},
{
"code": null,
"e": 2648,
"s": 1205,
"text": "> db.demo500.insertOne({value:10});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749c5987b6e0e9d18f55a\")\n}\n> db.demo500.insertOne({value:1200});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749c8987b6e0e9d18f55b\")\n}\n> db.demo500.insertOne({value:19});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749cb987b6e0e9d18f55c\")\n}\n> db.demo500.insertOne({value:28});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749cf987b6e0e9d18f55d\")\n}\n> db.demo500.insertOne({value:50});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749d1987b6e0e9d18f55e\")\n}\n> db.demo500.insertOne({value:70});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749d4987b6e0e9d18f55f\")\n}\n> db.demo500.insertOne({value:100});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749d7987b6e0e9d18f560\")\n}\n> db.demo500.insertOne({value:10});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749d9987b6e0e9d18f561\")\n}\n> db.demo500.insertOne({value:98});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749dc987b6e0e9d18f562\")\n}\n> db.demo500.insertOne({value:80});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e8749e0987b6e0e9d18f563\")\n}\n> db.demo500.insertOne({value:75});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e874c73987b6e0e9d18f564\")\n}\n> db.demo500.insertOne({value:68});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e874c78987b6e0e9d18f565\")\n}"
},
{
"code": null,
"e": 2721,
"s": 2648,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2742,
"s": 2721,
"text": "> db.demo500.find();"
},
{
"code": null,
"e": 2783,
"s": 2742,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3542,
"s": 2783,
"text": "{ \"_id\" : ObjectId(\"5e8749c5987b6e0e9d18f55a\"), \"value\" : 10 }\n{ \"_id\" : ObjectId(\"5e8749c8987b6e0e9d18f55b\"), \"value\" : 1200 }\n{ \"_id\" : ObjectId(\"5e8749cb987b6e0e9d18f55c\"), \"value\" : 19 }\n{ \"_id\" : ObjectId(\"5e8749cf987b6e0e9d18f55d\"), \"value\" : 28 }\n{ \"_id\" : ObjectId(\"5e8749d1987b6e0e9d18f55e\"), \"value\" : 50 }\n{ \"_id\" : ObjectId(\"5e8749d4987b6e0e9d18f55f\"), \"value\" : 70 }\n{ \"_id\" : ObjectId(\"5e8749d7987b6e0e9d18f560\"), \"value\" : 100 }\n{ \"_id\" : ObjectId(\"5e8749d9987b6e0e9d18f561\"), \"value\" : 10 }\n{ \"_id\" : ObjectId(\"5e8749dc987b6e0e9d18f562\"), \"value\" : 98 }\n{ \"_id\" : ObjectId(\"5e8749e0987b6e0e9d18f563\"), \"value\" : 80 }\n{ \"_id\" : ObjectId(\"5e874c73987b6e0e9d18f564\"), \"value\" : 75 }\n{ \"_id\" : ObjectId(\"5e874c78987b6e0e9d18f565\"), \"value\" : 68 }"
},
{
"code": null,
"e": 3629,
"s": 3542,
"text": "Following is the query to select 10 most recent documents without changing the order −"
},
{
"code": null,
"e": 3680,
"s": 3629,
"text": "> db.demo500.find().skip(db.demo500.count() - 10);"
},
{
"code": null,
"e": 3721,
"s": 3680,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4352,
"s": 3721,
"text": "{ \"_id\" : ObjectId(\"5e8749cb987b6e0e9d18f55c\"), \"value\" : 19 }\n{ \"_id\" : ObjectId(\"5e8749cf987b6e0e9d18f55d\"), \"value\" : 28 }\n{ \"_id\" : ObjectId(\"5e8749d1987b6e0e9d18f55e\"), \"value\" : 50 }\n{ \"_id\" : ObjectId(\"5e8749d4987b6e0e9d18f55f\"), \"value\" : 70 }\n{ \"_id\" : ObjectId(\"5e8749d7987b6e0e9d18f560\"), \"value\" : 100 }\n{ \"_id\" : ObjectId(\"5e8749d9987b6e0e9d18f561\"), \"value\" : 10 }\n{ \"_id\" : ObjectId(\"5e8749dc987b6e0e9d18f562\"), \"value\" : 98 }\n{ \"_id\" : ObjectId(\"5e8749e0987b6e0e9d18f563\"), \"value\" : 80 }\n{ \"_id\" : ObjectId(\"5e874c73987b6e0e9d18f564\"), \"value\" : 75 }\n{ \"_id\" : ObjectId(\"5e874c78987b6e0e9d18f565\"), \"value\" : 68 }"
}
] |
How to duplicate a div using jQuery? | To duplicate a div in jQuery, use the jQuery clone() method.
You can try to run the following code to learn how to duplicate a div using jQuery:
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(){
$("button").click(function(){
$("div").clone().appendTo("body");
});
});
</script>
</head>
<body>
<div>This is a text</div>
<button>Clone div and append</button>
</body>
</html> | [
{
"code": null,
"e": 1123,
"s": 1062,
"text": "To duplicate a div in jQuery, use the jQuery clone() method."
},
{
"code": null,
"e": 1207,
"s": 1123,
"text": "You can try to run the following code to learn how to duplicate a div using jQuery:"
},
{
"code": null,
"e": 1217,
"s": 1207,
"text": "Live Demo"
},
{
"code": null,
"e": 1567,
"s": 1217,
"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 $(\"button\").click(function(){\n $(\"div\").clone().appendTo(\"body\");\n });\n});\n</script>\n</head>\n<body>\n\n<div>This is a text</div>\n<button>Clone div and append</button>\n\n</body>\n</html>"
}
] |
Maximum sum of values of nodes among all connected components of an undirected graph - GeeksforGeeks | 30 Mar, 2022
Given an undirected graph with V vertices and E edges. Every node has been assigned a given value. The task is to find the connected chain with the maximum sum of of values among all the connected components in the graph. Examples:
Input: V = 7, E = 4 Values = {10, 25, 5, 15, 5, 20, 0}
Output : Max Sum value = 35 Explanation: Component {1, 2} – Value {10, 25}: sumValue = 10 + 25 = 35 Component {3, 4, 5} – Value {5, 15, 5}: sumValue = 5 + 15 + 5 = 25 Component {6, 7} – Value {20, 0}: sumValue = 20 + 0 = 20 Max Sum value chain is {1, 2} with values {10, 25}, hence 35 is answer. Input: V = 10, E = 6 Values = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}
Output : Max Sum value = 105
Approach: The idea is to use the Depth First Search traversal method to keep a track of all the connected components. A temporary variable is used to sum up all the values of the individual values of the connected chains. At each traversal of a connected component, the heaviest value till now is compared with the current value and updated accordingly. After all connected components have been traversed, the maximum among all will the answer. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find Maximum sum of values// of nodes among all connected// components of an undirected graph#include <bits/stdc++.h>using namespace std; // Function to implement DFSvoid depthFirst(int v, vector<int> graph[], vector<bool>& visited, int& sum, vector<int> values){ // Marking the visited vertex as true visited[v] = true; // Updating the value of connection sum += values[v - 1]; // Traverse for all adjacent nodes for (auto i : graph[v]) { if (visited[i] == false) { // Recursive call to the DFS algorithm depthFirst(i, graph, visited, sum, values); } }} void maximumSumOfValues(vector<int> graph[], int vertices, vector<int> values){ // Initializing boolean array to mark visited vertices vector<bool> visited(values.size() + 1, false); // maxChain stores the maximum chain size int maxValueSum = INT_MIN; // Following loop invokes DFS algorithm for (int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold temporary values int sum = 0; // DFS algorithm depthFirst(i, graph, visited, sum, values); // Conditional to update max value if (sum > maxValueSum) { maxValueSum = sum; } } } // Printing the heaviest chain value cout << "Max Sum value = "; cout << maxValueSum << "\n";} // Driver function to test above functionint main(){ // Defining the number of edges and vertices int E = 4, V = 7; // Initializing graph in the form of adjacency list vector<int> graph[V+1]; // Assigning the values for each // vertex of the undirected graph vector<int> values; values.push_back(10); values.push_back(25); values.push_back(5); values.push_back(15); values.push_back(5); values.push_back(20); values.push_back(0); // Constructing the undirected graph graph[1].push_back(2); graph[2].push_back(1); graph[3].push_back(4); graph[4].push_back(3); graph[3].push_back(5); graph[5].push_back(3); graph[6].push_back(7); graph[7].push_back(6); maximumSumOfValues(graph, V, values); return 0;}
// Java program to find Maximum sum of// values of nodes among all connected// components of an undirected graphimport java.util.*; class GFG{ static int sum; // Function to implement DFSstatic void depthFirst(int v, Vector<Integer> graph[], boolean []visited, Vector<Integer> values){ // Marking the visited vertex as true visited[v] = true; // Updating the value of connection sum += values.get(v - 1); // Traverse for all adjacent nodes for(int i : graph[v]) { if (visited[i] == false) { // Recursive call to the DFS algorithm depthFirst(i, graph, visited, values); } }} static void maximumSumOfValues(Vector<Integer> graph[], int vertices, Vector<Integer> values){ // Initializing boolean array to // mark visited vertices boolean []visited = new boolean[values.size() + 1]; // maxChain stores the maximum chain size int maxValueSum = Integer.MIN_VALUE; // Following loop invokes DFS algorithm for(int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold temporary values sum = 0; // DFS algorithm depthFirst(i, graph, visited, values); // Conditional to update max value if (sum > maxValueSum) { maxValueSum = sum; } } } // Printing the heaviest chain value System.out.print("Max Sum value = "); System.out.print(maxValueSum + "\n");} // Driver codepublic static void main(String[] args){ // Initializing graph in the form // of adjacency list @SuppressWarnings("unchecked") Vector<Integer> []graph = new Vector[1001]; for(int i = 0; i < graph.length; i++) graph[i] = new Vector<Integer>(); // Defining the number of edges and vertices int E = 4, V = 7; // Assigning the values for each // vertex of the undirected graph Vector<Integer> values = new Vector<Integer>(); values.add(10); values.add(25); values.add(5); values.add(15); values.add(5); values.add(20); values.add(0); // Constructing the undirected graph graph[1].add(2); graph[2].add(1); graph[3].add(4); graph[4].add(3); graph[3].add(5); graph[5].add(3); graph[6].add(7); graph[7].add(6); maximumSumOfValues(graph, V, values);}} // This code is contributed by Rajput-Ji
# Python3 program to find Maximum sum# of values of nodes among all connected# components of an undirected graphimport sys graph = [[] for i in range(1001)]visited = [False] * (1001 + 1)sum = 0 # Function to implement DFSdef depthFirst(v, values): global sum # Marking the visited vertex as true visited[v] = True # Updating the value of connection sum += values[v - 1] # Traverse for all adjacent nodes for i in graph[v]: if (visited[i] == False): # Recursive call to the # DFS algorithm depthFirst(i, values) def maximumSumOfValues(vertices,values): global sum # Initializing boolean array to # mark visited vertices # maxChain stores the maximum chain size maxValueSum = -sys.maxsize - 1 # Following loop invokes DFS algorithm for i in range(1, vertices + 1): if (visited[i] == False): # Variable to hold temporary values # sum = 0 # DFS algorithm depthFirst(i, values) # Conditional to update max value if (sum > maxValueSum): maxValueSum = sum sum = 0 # Printing the heaviest chain value print("Max Sum value = ", end = "") print(maxValueSum) # Driver codeif __name__ == '__main__': # Initializing graph in the # form of adjacency list # Defining the number of # edges and vertices E = 4 V = 7 # Assigning the values for each # vertex of the undirected graph values = [] values.append(10) values.append(25) values.append(5) values.append(15) values.append(5) values.append(20) values.append(0) # Constructing the undirected graph graph[1].append(2) graph[2].append(1) graph[3].append(4) graph[4].append(3) graph[3].append(5) graph[5].append(3) graph[6].append(7) graph[7].append(6) maximumSumOfValues(V, values) # This code is contributed by mohit kumar 29
// C# program to find Maximum sum of// values of nodes among all connected// components of an undirected graphusing System;using System.Collections.Generic; class GFG{ static int sum; // Function to implement DFSstatic void depthFirst(int v, List<int> []graph, bool []visited, List<int> values){ // Marking the visited vertex as true visited[v] = true; // Updating the value of connection sum += values[v - 1]; // Traverse for all adjacent nodes foreach(int i in graph[v]) { if (visited[i] == false) { // Recursive call to the DFS algorithm depthFirst(i, graph, visited, values); } }} static void maximumSumOfValues(List<int> []graph, int vertices, List<int> values){ // Initializing bool array to // mark visited vertices bool []visited = new bool[values.Count + 1]; // maxChain stores the maximum chain size int maxValueSum = int.MinValue; // Following loop invokes DFS algorithm for(int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold temporary values sum = 0; // DFS algorithm depthFirst(i, graph, visited, values); // Conditional to update max value if (sum > maxValueSum) { maxValueSum = sum; } } } // Printing the heaviest chain value Console.Write("Max Sum value = "); Console.Write(maxValueSum + "\n");} // Driver codepublic static void Main(String[] args){ // Initializing graph in the form // of adjacency list List<int> []graph = new List<int>[1001]; for(int i = 0; i < graph.Length; i++) graph[i] = new List<int>(); // Defining the number of edges and vertices int V = 7; // Assigning the values for each // vertex of the undirected graph List<int> values = new List<int>(); values.Add(10); values.Add(25); values.Add(5); values.Add(15); values.Add(5); values.Add(20); values.Add(0); // Constructing the undirected graph graph[1].Add(2); graph[2].Add(1); graph[3].Add(4); graph[4].Add(3); graph[3].Add(5); graph[5].Add(3); graph[6].Add(7); graph[7].Add(6); maximumSumOfValues(graph, V, values);}} // This code is contributed by Amit Katiyar
<script> // JavaScript program to find Maximum sum// of values of nodes among all connected// components of an undirected graph let graph = new Array(1001);for(let i=0;i<1001;i++){ graph[i] = new Array();}let visited = new Array(1001+1).fill(false);let sum = 0 // Function to implement DFSfunction depthFirst(v, values){ // Marking the visited vertex as true visited[v] = true // Updating the value of connection sum += values[v - 1] // Traverse for all adjacent nodes for(let i of graph[v]){ if (visited[i] == false){ // Recursive call to the // DFS algorithm depthFirst(i, values) } }} function maximumSumOfValues(vertices,values){ // Initializing boolean array to // mark visited vertices // maxChain stores the maximum chain size let maxValueSum = Number.MIN_VALUE // Following loop invokes DFS algorithm for(let i=1;i<vertices + 1;i++){ if (visited[i] == false){ // Variable to hold temporary values // sum = 0 // DFS algorithm depthFirst(i, values) // Conditional to update max value if (sum > maxValueSum) maxValueSum = sum sum = 0 } } // Printing the heaviest chain value document.write("Max Sum value = ","") document.write(maxValueSum)} // Driver code // Initializing graph in the// form of adjacency list // Defining the number of// edges and verticeslet E = 4let V = 7 // Assigning the values for each// vertex of the undirected graphlet values = []values.push(10)values.push(25)values.push(5)values.push(15)values.push(5)values.push(20)values.push(0) // Constructing the undirected graphgraph[1].push(2)graph[2].push(1)graph[3].push(4)graph[4].push(3)graph[3].push(5)graph[5].push(3)graph[6].push(7)graph[7].push(6) maximumSumOfValues(V, values) // This code is contributed by shinjanpatra </script>
Max Sum value = 35
Time Complexity: O(E + V) Auxiliary Space: O(E + V)
Rajput-Ji
amit143katiyar
mohit kumar 29
pankajsharmagfg
ashutoshsinghgeeksforgeeks
shinjanpatra
connected-components
Algorithms
Arrays
Competitive Programming
Data Structures
Graph
Data Structures
Arrays
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Write a program to reverse an array or string | [
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n30 Mar, 2022"
},
{
"code": null,
"e": 24924,
"s": 24692,
"text": "Given an undirected graph with V vertices and E edges. Every node has been assigned a given value. The task is to find the connected chain with the maximum sum of of values among all the connected components in the graph. Examples:"
},
{
"code": null,
"e": 24981,
"s": 24924,
"text": "Input: V = 7, E = 4 Values = {10, 25, 5, 15, 5, 20, 0} "
},
{
"code": null,
"e": 25347,
"s": 24981,
"text": "Output : Max Sum value = 35 Explanation: Component {1, 2} – Value {10, 25}: sumValue = 10 + 25 = 35 Component {3, 4, 5} – Value {5, 15, 5}: sumValue = 5 + 15 + 5 = 25 Component {6, 7} – Value {20, 0}: sumValue = 20 + 0 = 20 Max Sum value chain is {1, 2} with values {10, 25}, hence 35 is answer. Input: V = 10, E = 6 Values = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}"
},
{
"code": null,
"e": 25376,
"s": 25347,
"text": "Output : Max Sum value = 105"
},
{
"code": null,
"e": 25872,
"s": 25376,
"text": "Approach: The idea is to use the Depth First Search traversal method to keep a track of all the connected components. A temporary variable is used to sum up all the values of the individual values of the connected chains. At each traversal of a connected component, the heaviest value till now is compared with the current value and updated accordingly. After all connected components have been traversed, the maximum among all will the answer. Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25876,
"s": 25872,
"text": "C++"
},
{
"code": null,
"e": 25881,
"s": 25876,
"text": "Java"
},
{
"code": null,
"e": 25889,
"s": 25881,
"text": "Python3"
},
{
"code": null,
"e": 25892,
"s": 25889,
"text": "C#"
},
{
"code": null,
"e": 25903,
"s": 25892,
"text": "Javascript"
},
{
"code": "// C++ program to find Maximum sum of values// of nodes among all connected// components of an undirected graph#include <bits/stdc++.h>using namespace std; // Function to implement DFSvoid depthFirst(int v, vector<int> graph[], vector<bool>& visited, int& sum, vector<int> values){ // Marking the visited vertex as true visited[v] = true; // Updating the value of connection sum += values[v - 1]; // Traverse for all adjacent nodes for (auto i : graph[v]) { if (visited[i] == false) { // Recursive call to the DFS algorithm depthFirst(i, graph, visited, sum, values); } }} void maximumSumOfValues(vector<int> graph[], int vertices, vector<int> values){ // Initializing boolean array to mark visited vertices vector<bool> visited(values.size() + 1, false); // maxChain stores the maximum chain size int maxValueSum = INT_MIN; // Following loop invokes DFS algorithm for (int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold temporary values int sum = 0; // DFS algorithm depthFirst(i, graph, visited, sum, values); // Conditional to update max value if (sum > maxValueSum) { maxValueSum = sum; } } } // Printing the heaviest chain value cout << \"Max Sum value = \"; cout << maxValueSum << \"\\n\";} // Driver function to test above functionint main(){ // Defining the number of edges and vertices int E = 4, V = 7; // Initializing graph in the form of adjacency list vector<int> graph[V+1]; // Assigning the values for each // vertex of the undirected graph vector<int> values; values.push_back(10); values.push_back(25); values.push_back(5); values.push_back(15); values.push_back(5); values.push_back(20); values.push_back(0); // Constructing the undirected graph graph[1].push_back(2); graph[2].push_back(1); graph[3].push_back(4); graph[4].push_back(3); graph[3].push_back(5); graph[5].push_back(3); graph[6].push_back(7); graph[7].push_back(6); maximumSumOfValues(graph, V, values); return 0;}",
"e": 28227,
"s": 25903,
"text": null
},
{
"code": "// Java program to find Maximum sum of// values of nodes among all connected// components of an undirected graphimport java.util.*; class GFG{ static int sum; // Function to implement DFSstatic void depthFirst(int v, Vector<Integer> graph[], boolean []visited, Vector<Integer> values){ // Marking the visited vertex as true visited[v] = true; // Updating the value of connection sum += values.get(v - 1); // Traverse for all adjacent nodes for(int i : graph[v]) { if (visited[i] == false) { // Recursive call to the DFS algorithm depthFirst(i, graph, visited, values); } }} static void maximumSumOfValues(Vector<Integer> graph[], int vertices, Vector<Integer> values){ // Initializing boolean array to // mark visited vertices boolean []visited = new boolean[values.size() + 1]; // maxChain stores the maximum chain size int maxValueSum = Integer.MIN_VALUE; // Following loop invokes DFS algorithm for(int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold temporary values sum = 0; // DFS algorithm depthFirst(i, graph, visited, values); // Conditional to update max value if (sum > maxValueSum) { maxValueSum = sum; } } } // Printing the heaviest chain value System.out.print(\"Max Sum value = \"); System.out.print(maxValueSum + \"\\n\");} // Driver codepublic static void main(String[] args){ // Initializing graph in the form // of adjacency list @SuppressWarnings(\"unchecked\") Vector<Integer> []graph = new Vector[1001]; for(int i = 0; i < graph.length; i++) graph[i] = new Vector<Integer>(); // Defining the number of edges and vertices int E = 4, V = 7; // Assigning the values for each // vertex of the undirected graph Vector<Integer> values = new Vector<Integer>(); values.add(10); values.add(25); values.add(5); values.add(15); values.add(5); values.add(20); values.add(0); // Constructing the undirected graph graph[1].add(2); graph[2].add(1); graph[3].add(4); graph[4].add(3); graph[3].add(5); graph[5].add(3); graph[6].add(7); graph[7].add(6); maximumSumOfValues(graph, V, values);}} // This code is contributed by Rajput-Ji",
"e": 30801,
"s": 28227,
"text": null
},
{
"code": "# Python3 program to find Maximum sum# of values of nodes among all connected# components of an undirected graphimport sys graph = [[] for i in range(1001)]visited = [False] * (1001 + 1)sum = 0 # Function to implement DFSdef depthFirst(v, values): global sum # Marking the visited vertex as true visited[v] = True # Updating the value of connection sum += values[v - 1] # Traverse for all adjacent nodes for i in graph[v]: if (visited[i] == False): # Recursive call to the # DFS algorithm depthFirst(i, values) def maximumSumOfValues(vertices,values): global sum # Initializing boolean array to # mark visited vertices # maxChain stores the maximum chain size maxValueSum = -sys.maxsize - 1 # Following loop invokes DFS algorithm for i in range(1, vertices + 1): if (visited[i] == False): # Variable to hold temporary values # sum = 0 # DFS algorithm depthFirst(i, values) # Conditional to update max value if (sum > maxValueSum): maxValueSum = sum sum = 0 # Printing the heaviest chain value print(\"Max Sum value = \", end = \"\") print(maxValueSum) # Driver codeif __name__ == '__main__': # Initializing graph in the # form of adjacency list # Defining the number of # edges and vertices E = 4 V = 7 # Assigning the values for each # vertex of the undirected graph values = [] values.append(10) values.append(25) values.append(5) values.append(15) values.append(5) values.append(20) values.append(0) # Constructing the undirected graph graph[1].append(2) graph[2].append(1) graph[3].append(4) graph[4].append(3) graph[3].append(5) graph[5].append(3) graph[6].append(7) graph[7].append(6) maximumSumOfValues(V, values) # This code is contributed by mohit kumar 29",
"e": 32798,
"s": 30801,
"text": null
},
{
"code": "// C# program to find Maximum sum of// values of nodes among all connected// components of an undirected graphusing System;using System.Collections.Generic; class GFG{ static int sum; // Function to implement DFSstatic void depthFirst(int v, List<int> []graph, bool []visited, List<int> values){ // Marking the visited vertex as true visited[v] = true; // Updating the value of connection sum += values[v - 1]; // Traverse for all adjacent nodes foreach(int i in graph[v]) { if (visited[i] == false) { // Recursive call to the DFS algorithm depthFirst(i, graph, visited, values); } }} static void maximumSumOfValues(List<int> []graph, int vertices, List<int> values){ // Initializing bool array to // mark visited vertices bool []visited = new bool[values.Count + 1]; // maxChain stores the maximum chain size int maxValueSum = int.MinValue; // Following loop invokes DFS algorithm for(int i = 1; i <= vertices; i++) { if (visited[i] == false) { // Variable to hold temporary values sum = 0; // DFS algorithm depthFirst(i, graph, visited, values); // Conditional to update max value if (sum > maxValueSum) { maxValueSum = sum; } } } // Printing the heaviest chain value Console.Write(\"Max Sum value = \"); Console.Write(maxValueSum + \"\\n\");} // Driver codepublic static void Main(String[] args){ // Initializing graph in the form // of adjacency list List<int> []graph = new List<int>[1001]; for(int i = 0; i < graph.Length; i++) graph[i] = new List<int>(); // Defining the number of edges and vertices int V = 7; // Assigning the values for each // vertex of the undirected graph List<int> values = new List<int>(); values.Add(10); values.Add(25); values.Add(5); values.Add(15); values.Add(5); values.Add(20); values.Add(0); // Constructing the undirected graph graph[1].Add(2); graph[2].Add(1); graph[3].Add(4); graph[4].Add(3); graph[3].Add(5); graph[5].Add(3); graph[6].Add(7); graph[7].Add(6); maximumSumOfValues(graph, V, values);}} // This code is contributed by Amit Katiyar",
"e": 35296,
"s": 32798,
"text": null
},
{
"code": "<script> // JavaScript program to find Maximum sum// of values of nodes among all connected// components of an undirected graph let graph = new Array(1001);for(let i=0;i<1001;i++){ graph[i] = new Array();}let visited = new Array(1001+1).fill(false);let sum = 0 // Function to implement DFSfunction depthFirst(v, values){ // Marking the visited vertex as true visited[v] = true // Updating the value of connection sum += values[v - 1] // Traverse for all adjacent nodes for(let i of graph[v]){ if (visited[i] == false){ // Recursive call to the // DFS algorithm depthFirst(i, values) } }} function maximumSumOfValues(vertices,values){ // Initializing boolean array to // mark visited vertices // maxChain stores the maximum chain size let maxValueSum = Number.MIN_VALUE // Following loop invokes DFS algorithm for(let i=1;i<vertices + 1;i++){ if (visited[i] == false){ // Variable to hold temporary values // sum = 0 // DFS algorithm depthFirst(i, values) // Conditional to update max value if (sum > maxValueSum) maxValueSum = sum sum = 0 } } // Printing the heaviest chain value document.write(\"Max Sum value = \",\"\") document.write(maxValueSum)} // Driver code // Initializing graph in the// form of adjacency list // Defining the number of// edges and verticeslet E = 4let V = 7 // Assigning the values for each// vertex of the undirected graphlet values = []values.push(10)values.push(25)values.push(5)values.push(15)values.push(5)values.push(20)values.push(0) // Constructing the undirected graphgraph[1].push(2)graph[2].push(1)graph[3].push(4)graph[4].push(3)graph[3].push(5)graph[5].push(3)graph[6].push(7)graph[7].push(6) maximumSumOfValues(V, values) // This code is contributed by shinjanpatra </script>",
"e": 37269,
"s": 35296,
"text": null
},
{
"code": null,
"e": 37288,
"s": 37269,
"text": "Max Sum value = 35"
},
{
"code": null,
"e": 37342,
"s": 37288,
"text": "Time Complexity: O(E + V) Auxiliary Space: O(E + V) "
},
{
"code": null,
"e": 37352,
"s": 37342,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37367,
"s": 37352,
"text": "amit143katiyar"
},
{
"code": null,
"e": 37382,
"s": 37367,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37398,
"s": 37382,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 37425,
"s": 37398,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 37438,
"s": 37425,
"text": "shinjanpatra"
},
{
"code": null,
"e": 37459,
"s": 37438,
"text": "connected-components"
},
{
"code": null,
"e": 37470,
"s": 37459,
"text": "Algorithms"
},
{
"code": null,
"e": 37477,
"s": 37470,
"text": "Arrays"
},
{
"code": null,
"e": 37501,
"s": 37477,
"text": "Competitive Programming"
},
{
"code": null,
"e": 37517,
"s": 37501,
"text": "Data Structures"
},
{
"code": null,
"e": 37523,
"s": 37517,
"text": "Graph"
},
{
"code": null,
"e": 37539,
"s": 37523,
"text": "Data Structures"
},
{
"code": null,
"e": 37546,
"s": 37539,
"text": "Arrays"
},
{
"code": null,
"e": 37552,
"s": 37546,
"text": "Graph"
},
{
"code": null,
"e": 37563,
"s": 37552,
"text": "Algorithms"
},
{
"code": null,
"e": 37661,
"s": 37563,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37670,
"s": 37661,
"text": "Comments"
},
{
"code": null,
"e": 37683,
"s": 37670,
"text": "Old Comments"
},
{
"code": null,
"e": 37708,
"s": 37683,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 37737,
"s": 37708,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 37771,
"s": 37737,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 37814,
"s": 37771,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 37857,
"s": 37814,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 37872,
"s": 37857,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37888,
"s": 37872,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 37915,
"s": 37888,
"text": "Program for array rotation"
},
{
"code": null,
"e": 37963,
"s": 37915,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Find the smallest and second smallest elements in an array - GeeksforGeeks | 10 Jan, 2022
Write an efficient C program to find smallest and second smallest element in an array.
Example:
Input: arr[] = {12, 13, 1, 10, 34, 1}
Output: The smallest element is 1 and
second Smallest element is 10
A Simple Solution is to sort the array in increasing order. The first two elements in sorted array would be two smallest elements. Time complexity of this solution is O(n Log n).A Better Solution is to scan the array twice. In first traversal find the minimum element. Let this element be x. In second traversal, find the smallest element greater than x. Time complexity of this solution is O(n).The above solution requires two traversals of input array. An Efficient Solution can find the minimum two elements in one traversal. Below is complete algorithm.Algorithm:
1) Initialize both first and second smallest as INT_MAX
first = second = INT_MAX
2) Loop through all the elements.
a) If the current element is smaller than first, then update first
and second.
b) Else if the current element is smaller than second then update
second
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find smallest and// second smallest elements#include <bits/stdc++.h>using namespace std; /* For INT_MAX */ void print2Smallest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { cout<<" Invalid Input "; return; } first = second = INT_MAX; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == INT_MAX) cout << "There is no second smallest element\n"; else cout << "The smallest element is " << first << " and second " "Smallest element is " << second << endl;} /* Driver code */int main(){ int arr[] = {12, 13, 1, 10, 34, 1}; int n = sizeof(arr)/sizeof(arr[0]); print2Smallest(arr, n); return 0;} // This is code is contributed by rathbhupendra
// C program to find smallest and second smallest elements#include <stdio.h>#include <limits.h> /* For INT_MAX */ void print2Smallest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf(" Invalid Input "); return; } first = second = INT_MAX; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == INT_MAX) printf("There is no second smallest element\n"); else printf("The smallest element is %d and second " "Smallest element is %d\n", first, second);} /* Driver program to test above function */int main(){ int arr[] = {12, 13, 1, 10, 34, 1}; int n = sizeof(arr)/sizeof(arr[0]); print2Smallest(arr, n); return 0;}
// Java program to find smallest and second smallest elementsimport java.io.*; class SecondSmallest{ /* Function to print first smallest and second smallest elements */ static void print2Smallest(int arr[]) { int first, second, arr_size = arr.length; /* There should be atleast two elements */ if (arr_size < 2) { System.out.println(" Invalid Input "); return; } first = second = Integer.MAX_VALUE; for (int i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == Integer.MAX_VALUE) System.out.println("There is no second" + "smallest element"); else System.out.println("The smallest element is " + first + " and second Smallest" + " element is " + second); } /* Driver program to test above functions */ public static void main (String[] args) { int arr[] = {12, 13, 1, 10, 34, 1}; print2Smallest(arr); }}/*This code is contributed by Devesh Agrawal*/
# Python program to find smallest and second smallest elementsimport math def print2Smallest(arr): # There should be atleast two elements arr_size = len(arr) if arr_size < 2: print ("Invalid Input") return first = second = math.inf for i in range(0, arr_size): # If current element is smaller than first then # update both first and second if arr[i] < first: second = first first = arr[i] # If arr[i] is in between first and second then # update second elif (arr[i] < second and arr[i] != first): second = arr[i]; if (second == math.inf): print ("No second smallest element") else: print ('The smallest element is',first,'and', \ ' second smallest element is',second) # Driver function to test above functionarr = [12, 13, 1, 10, 34, 1]print2Smallest(arr) # This code is contributed by Devesh Agrawal
// C# program to find smallest// and second smallest elementsusing System; class GFG{ /* Function to print first smallest and second smallest elements */ static void print2Smallest(int []arr) { int first, second, arr_size = arr.Length; /* There should be atleast two elements */ if (arr_size < 2) { Console.Write(" Invalid Input "); return; } first = second = int.MaxValue; for (int i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == int.MaxValue) Console.Write("There is no second" + "smallest element"); else Console.Write("The smallest element is " + first + " and second Smallest" + " element is " + second); } /* Driver program to test above functions */ public static void Main() { int []arr = {12, 13, 1, 10, 34, 1}; print2Smallest(arr); }} // This code is contributed by Sam007
<?php// PHP program to find smallest and// second smallest elements function print2Smallest($arr, $arr_size){ $INT_MAX = 2147483647; /* There should be atleast two elements */ if ($arr_size < 2) { echo(" Invalid Input "); return; } $first = $second = $INT_MAX; for ($i = 0; $i < $arr_size ; $i ++) { /* If current element is smaller than first then update both first and second */ if ($arr[$i] < $first) { $second = $first; $first = $arr[$i]; } /* If arr[i] is in between first and second then update second */ else if ($arr[$i] < $second && $arr[$i] != $first) $second = $arr[$i]; } if ($second == $INT_MAX) echo("There is no second smallest element\n"); else echo "The smallest element is ",$first ," and second Smallest element is " , $second;} // Driver Code$arr = array(12, 13, 1, 10, 34, 1);$n = count($arr);print2Smallest($arr, $n) // This code is contributed by Smitha?>
<script> // Javascript program to find smallest and// second smallest elements function print2Smallest( arr, arr_size){ let i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { document.write(" Invalid Input "); return; } first=Number.MAX_VALUE ; second=Number.MAX_VALUE ; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == Number.MAX_VALUE ) document.write("There is no second smallest element\n"); else document.write("The smallest element is " + first + " and second "+ "Smallest element is " + second +'\n');} // Driver program let arr = [ 12, 13, 1, 10, 34, 1 ]; let n = arr.length; print2Smallest(arr, n); </script>
Output :
The smallest element is 1 and second Smallest element is 10
The same approach can be used to find the largest and second largest elements in an array.Time Complexity: O(n)
YouTubeGeeksforGeeks502K subscribersFind the smallest and second smallest elements in an array | 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:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OEgfEDR7BNk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Related Article: Minimum and Second minimum elements using minimum comparisonsPlease write comments if you find any bug in the above program/algorithm or other ways to solve the same problem.
Smitha Dinesh Semwal
rathbhupendra
jana_sayantan
amartyaghoshgfg
Amazon
Arrays
Searching
Amazon
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Write a program to reverse an array or string
Stack Data Structure (Introduction and Program)
Program for array rotation
Binary Search
Linear Search
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
Program to find largest element in an array | [
{
"code": null,
"e": 41275,
"s": 41247,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 41363,
"s": 41275,
"text": "Write an efficient C program to find smallest and second smallest element in an array. "
},
{
"code": null,
"e": 41374,
"s": 41363,
"text": "Example: "
},
{
"code": null,
"e": 41490,
"s": 41374,
"text": "Input: arr[] = {12, 13, 1, 10, 34, 1}\nOutput: The smallest element is 1 and \n second Smallest element is 10"
},
{
"code": null,
"e": 42062,
"s": 41492,
"text": "A Simple Solution is to sort the array in increasing order. The first two elements in sorted array would be two smallest elements. Time complexity of this solution is O(n Log n).A Better Solution is to scan the array twice. In first traversal find the minimum element. Let this element be x. In second traversal, find the smallest element greater than x. Time complexity of this solution is O(n).The above solution requires two traversals of input array. An Efficient Solution can find the minimum two elements in one traversal. Below is complete algorithm.Algorithm: "
},
{
"code": null,
"e": 42352,
"s": 42062,
"text": "1) Initialize both first and second smallest as INT_MAX\n first = second = INT_MAX\n2) Loop through all the elements.\n a) If the current element is smaller than first, then update first \n and second. \n b) Else if the current element is smaller than second then update \n second"
},
{
"code": null,
"e": 42370,
"s": 42352,
"text": "Implementation: "
},
{
"code": null,
"e": 42374,
"s": 42370,
"text": "C++"
},
{
"code": null,
"e": 42376,
"s": 42374,
"text": "C"
},
{
"code": null,
"e": 42381,
"s": 42376,
"text": "Java"
},
{
"code": null,
"e": 42389,
"s": 42381,
"text": "Python3"
},
{
"code": null,
"e": 42392,
"s": 42389,
"text": "C#"
},
{
"code": null,
"e": 42396,
"s": 42392,
"text": "PHP"
},
{
"code": null,
"e": 42407,
"s": 42396,
"text": "Javascript"
},
{
"code": "// C++ program to find smallest and// second smallest elements#include <bits/stdc++.h>using namespace std; /* For INT_MAX */ void print2Smallest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { cout<<\" Invalid Input \"; return; } first = second = INT_MAX; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == INT_MAX) cout << \"There is no second smallest element\\n\"; else cout << \"The smallest element is \" << first << \" and second \" \"Smallest element is \" << second << endl;} /* Driver code */int main(){ int arr[] = {12, 13, 1, 10, 34, 1}; int n = sizeof(arr)/sizeof(arr[0]); print2Smallest(arr, n); return 0;} // This is code is contributed by rathbhupendra",
"e": 43568,
"s": 42407,
"text": null
},
{
"code": "// C program to find smallest and second smallest elements#include <stdio.h>#include <limits.h> /* For INT_MAX */ void print2Smallest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf(\" Invalid Input \"); return; } first = second = INT_MAX; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == INT_MAX) printf(\"There is no second smallest element\\n\"); else printf(\"The smallest element is %d and second \" \"Smallest element is %d\\n\", first, second);} /* Driver program to test above function */int main(){ int arr[] = {12, 13, 1, 10, 34, 1}; int n = sizeof(arr)/sizeof(arr[0]); print2Smallest(arr, n); return 0;}",
"e": 44696,
"s": 43568,
"text": null
},
{
"code": "// Java program to find smallest and second smallest elementsimport java.io.*; class SecondSmallest{ /* Function to print first smallest and second smallest elements */ static void print2Smallest(int arr[]) { int first, second, arr_size = arr.length; /* There should be atleast two elements */ if (arr_size < 2) { System.out.println(\" Invalid Input \"); return; } first = second = Integer.MAX_VALUE; for (int i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == Integer.MAX_VALUE) System.out.println(\"There is no second\" + \"smallest element\"); else System.out.println(\"The smallest element is \" + first + \" and second Smallest\" + \" element is \" + second); } /* Driver program to test above functions */ public static void main (String[] args) { int arr[] = {12, 13, 1, 10, 34, 1}; print2Smallest(arr); }}/*This code is contributed by Devesh Agrawal*/",
"e": 46201,
"s": 44696,
"text": null
},
{
"code": "# Python program to find smallest and second smallest elementsimport math def print2Smallest(arr): # There should be atleast two elements arr_size = len(arr) if arr_size < 2: print (\"Invalid Input\") return first = second = math.inf for i in range(0, arr_size): # If current element is smaller than first then # update both first and second if arr[i] < first: second = first first = arr[i] # If arr[i] is in between first and second then # update second elif (arr[i] < second and arr[i] != first): second = arr[i]; if (second == math.inf): print (\"No second smallest element\") else: print ('The smallest element is',first,'and', \\ ' second smallest element is',second) # Driver function to test above functionarr = [12, 13, 1, 10, 34, 1]print2Smallest(arr) # This code is contributed by Devesh Agrawal",
"e": 47144,
"s": 46201,
"text": null
},
{
"code": "// C# program to find smallest// and second smallest elementsusing System; class GFG{ /* Function to print first smallest and second smallest elements */ static void print2Smallest(int []arr) { int first, second, arr_size = arr.Length; /* There should be atleast two elements */ if (arr_size < 2) { Console.Write(\" Invalid Input \"); return; } first = second = int.MaxValue; for (int i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == int.MaxValue) Console.Write(\"There is no second\" + \"smallest element\"); else Console.Write(\"The smallest element is \" + first + \" and second Smallest\" + \" element is \" + second); } /* Driver program to test above functions */ public static void Main() { int []arr = {12, 13, 1, 10, 34, 1}; print2Smallest(arr); }} // This code is contributed by Sam007",
"e": 48585,
"s": 47144,
"text": null
},
{
"code": "<?php// PHP program to find smallest and// second smallest elements function print2Smallest($arr, $arr_size){ $INT_MAX = 2147483647; /* There should be atleast two elements */ if ($arr_size < 2) { echo(\" Invalid Input \"); return; } $first = $second = $INT_MAX; for ($i = 0; $i < $arr_size ; $i ++) { /* If current element is smaller than first then update both first and second */ if ($arr[$i] < $first) { $second = $first; $first = $arr[$i]; } /* If arr[i] is in between first and second then update second */ else if ($arr[$i] < $second && $arr[$i] != $first) $second = $arr[$i]; } if ($second == $INT_MAX) echo(\"There is no second smallest element\\n\"); else echo \"The smallest element is \",$first ,\" and second Smallest element is \" , $second;} // Driver Code$arr = array(12, 13, 1, 10, 34, 1);$n = count($arr);print2Smallest($arr, $n) // This code is contributed by Smitha?>",
"e": 49737,
"s": 48585,
"text": null
},
{
"code": "<script> // Javascript program to find smallest and// second smallest elements function print2Smallest( arr, arr_size){ let i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { document.write(\" Invalid Input \"); return; } first=Number.MAX_VALUE ; second=Number.MAX_VALUE ; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == Number.MAX_VALUE ) document.write(\"There is no second smallest element\\n\"); else document.write(\"The smallest element is \" + first + \" and second \"+ \"Smallest element is \" + second +'\\n');} // Driver program let arr = [ 12, 13, 1, 10, 34, 1 ]; let n = arr.length; print2Smallest(arr, n); </script>",
"e": 50842,
"s": 49737,
"text": null
},
{
"code": null,
"e": 50852,
"s": 50842,
"text": "Output : "
},
{
"code": null,
"e": 50912,
"s": 50852,
"text": "The smallest element is 1 and second Smallest element is 10"
},
{
"code": null,
"e": 51025,
"s": 50912,
"text": "The same approach can be used to find the largest and second largest elements in an array.Time Complexity: O(n) "
},
{
"code": null,
"e": 51882,
"s": 51025,
"text": "YouTubeGeeksforGeeks502K subscribersFind the smallest and second smallest elements in an array | 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:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=OEgfEDR7BNk\" 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": 52075,
"s": 51882,
"text": "Related Article: Minimum and Second minimum elements using minimum comparisonsPlease write comments if you find any bug in the above program/algorithm or other ways to solve the same problem. "
},
{
"code": null,
"e": 52096,
"s": 52075,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 52110,
"s": 52096,
"text": "rathbhupendra"
},
{
"code": null,
"e": 52124,
"s": 52110,
"text": "jana_sayantan"
},
{
"code": null,
"e": 52140,
"s": 52124,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 52147,
"s": 52140,
"text": "Amazon"
},
{
"code": null,
"e": 52154,
"s": 52147,
"text": "Arrays"
},
{
"code": null,
"e": 52164,
"s": 52154,
"text": "Searching"
},
{
"code": null,
"e": 52171,
"s": 52164,
"text": "Amazon"
},
{
"code": null,
"e": 52178,
"s": 52171,
"text": "Arrays"
},
{
"code": null,
"e": 52188,
"s": 52178,
"text": "Searching"
},
{
"code": null,
"e": 52286,
"s": 52188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52301,
"s": 52286,
"text": "Arrays in Java"
},
{
"code": null,
"e": 52317,
"s": 52301,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 52363,
"s": 52317,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 52411,
"s": 52363,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 52438,
"s": 52411,
"text": "Program for array rotation"
},
{
"code": null,
"e": 52452,
"s": 52438,
"text": "Binary Search"
},
{
"code": null,
"e": 52466,
"s": 52452,
"text": "Linear Search"
},
{
"code": null,
"e": 52490,
"s": 52466,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 52546,
"s": 52490,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
iOS - Image View | Image view is used for displaying a single image or animated sequence of images.
image
highlightedImage
userInteractionEnabled
animationImages
animationRepeatCount
- (id)initWithImage:(UIImage *)image
- (id)initWithImage:(UIImage *)image highlightedImage: (UIImage *)highlightedImage
- (void)startAnimating
- (void)stopAnimating
-(void)addImageView {
UIImageView *imgview = [[UIImageView alloc]
initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"AppleUSA1.jpg"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];
}
This method explains how to animate images in imageView.
-(void)addImageViewWithAnimation {
UIImageView *imgview = [[UIImageView alloc]
initWithFrame:CGRectMake(10, 10, 300, 400)];
// set an animation
imgview.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"AppleUSA1.jpg"],
[UIImage imageNamed:@"AppleUSA2.jpg"], nil];
imgview.animationDuration = 4.0;
imgview.contentMode = UIViewContentModeCenter;
[imgview startAnimating];
[self.view addSubview:imgview];
}
Note −
We have to add images named as "AppleUSA1.jpg" and "AppleUSA2.jpg" to our project, which can be done by dragging the image to our navigator area where our project files are listed.
Update viewDidLoad in ViewController.m as follows −
(void)viewDidLoad {
[super viewDidLoad];
[self addImageView];
}
When we run the application, we'll get the following output −
You can try calling addImageViewWithAnimation instead of addImageView method to see the animation effect of image view.
23 Lectures
1.5 hours
Ashish Sharma
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
69 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2172,
"s": 2091,
"text": "Image view is used for displaying a single image or animated sequence of images."
},
{
"code": null,
"e": 2178,
"s": 2172,
"text": "image"
},
{
"code": null,
"e": 2195,
"s": 2178,
"text": "highlightedImage"
},
{
"code": null,
"e": 2218,
"s": 2195,
"text": "userInteractionEnabled"
},
{
"code": null,
"e": 2234,
"s": 2218,
"text": "animationImages"
},
{
"code": null,
"e": 2255,
"s": 2234,
"text": "animationRepeatCount"
},
{
"code": null,
"e": 2421,
"s": 2255,
"text": "- (id)initWithImage:(UIImage *)image\n- (id)initWithImage:(UIImage *)image highlightedImage: (UIImage *)highlightedImage\n- (void)startAnimating\n- (void)stopAnimating\n"
},
{
"code": null,
"e": 2697,
"s": 2421,
"text": "-(void)addImageView {\n UIImageView *imgview = [[UIImageView alloc]\n initWithFrame:CGRectMake(10, 10, 300, 400)];\n [imgview setImage:[UIImage imageNamed:@\"AppleUSA1.jpg\"]];\n [imgview setContentMode:UIViewContentModeScaleAspectFit];\n [self.view addSubview:imgview];\n}"
},
{
"code": null,
"e": 2754,
"s": 2697,
"text": "This method explains how to animate images in imageView."
},
{
"code": null,
"e": 3209,
"s": 2754,
"text": "-(void)addImageViewWithAnimation {\n UIImageView *imgview = [[UIImageView alloc]\n initWithFrame:CGRectMake(10, 10, 300, 400)];\n \n // set an animation\n imgview.animationImages = [NSArray arrayWithObjects:\n [UIImage imageNamed:@\"AppleUSA1.jpg\"],\n [UIImage imageNamed:@\"AppleUSA2.jpg\"], nil];\n imgview.animationDuration = 4.0;\n imgview.contentMode = UIViewContentModeCenter;\n [imgview startAnimating];\n [self.view addSubview:imgview];\n}"
},
{
"code": null,
"e": 3216,
"s": 3209,
"text": "Note −"
},
{
"code": null,
"e": 3397,
"s": 3216,
"text": "We have to add images named as \"AppleUSA1.jpg\" and \"AppleUSA2.jpg\" to our project, which can be done by dragging the image to our navigator area where our project files are listed."
},
{
"code": null,
"e": 3449,
"s": 3397,
"text": "Update viewDidLoad in ViewController.m as follows −"
},
{
"code": null,
"e": 3519,
"s": 3449,
"text": "(void)viewDidLoad {\n [super viewDidLoad];\n [self addImageView];\n}"
},
{
"code": null,
"e": 3581,
"s": 3519,
"text": "When we run the application, we'll get the following output −"
},
{
"code": null,
"e": 3701,
"s": 3581,
"text": "You can try calling addImageViewWithAnimation instead of addImageView method to see the animation effect of image view."
},
{
"code": null,
"e": 3736,
"s": 3701,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3751,
"s": 3736,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 3783,
"s": 3751,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3800,
"s": 3783,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3835,
"s": 3800,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3852,
"s": 3835,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3887,
"s": 3852,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3904,
"s": 3887,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3937,
"s": 3904,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3954,
"s": 3937,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3987,
"s": 3954,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4004,
"s": 3987,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4011,
"s": 4004,
"text": " Print"
},
{
"code": null,
"e": 4022,
"s": 4011,
"text": " Add Notes"
}
] |
GraphQL - Type System | GraphQL is a strongly typed language. Type System defines various data types that can be used in a GraphQL application. The type system helps to define the schema, which is a contract between client and server. The commonly used GraphQL data types are as follows −
Scalar
Stores a single value
Object
Shows what kind of object can be fetched
Query
Entry point type to other specific types
Mutation
Entry point for data manipulation
Enum
Useful in a situation where you need the user to pick from a prescribed list of options
Scalar types are primitive data types that can store only a single value. The default scalar types that GraphQL offers are −
Int − Signed 32-bit Integer
Int − Signed 32-bit Integer
Float − Signed double precision floating point value
Float − Signed double precision floating point value
String − UTF - 8-character sequence
String − UTF - 8-character sequence
Boolean − True or false
Boolean − True or false
ID − A unique identifier, often used as a unique identifier to fetch an object or as the key for a cache.
ID − A unique identifier, often used as a unique identifier to fetch an object or as the key for a cache.
The syntax for defining a scalar type is as follows −
field: data_type
The snippet given below defines a field named greeting which returns String value.
greeting: String
The object type is the most common type used in a schema and represents a group of fields. Each field inside an object type maps to another type, thereby allowing nested types. In other words, an object type is composed of multiple scalar types or object types.
The syntax for defining an object type is given below −
type object_type_name
{
field1: data_type
field2:data_type
....
fieldn:data_type
}
You can consider the following code snippet −
--Define an object type--
type Student {
stud_id:ID
firstname: String
age: Int
score:Float
}
--Defining a GraphQL schema--
type Query
{
stud_details:[Student]
}
The example given above defines an object data-type Student. The stud_details field in the root Query schema will return a list of Student objects.
A GraphQL query is used to fetch data. It is like requesting a resource in REST-based APIs. To keep it simple, the Query type is the request sent from a client application to the GraphQL server. GraphQL uses the Schema Definition Language (SDL) to define a Query. Query type is one of the many root-level types in GraphQL.
The syntax for defining a Query is as given below −
type Query {
field1: data_type
field2:data_type
field2(param1:data_type,param2:data_type,...paramN:data_type):data_type
}
An example of defining a Query −
type Query {
greeting: String
}
Mutations are operations sent to the server to create, update or delete data. These are analogous to the PUT, POST, PATCH and DELETE verbs to call REST-based APIs.
Mutation is one of the root-level data-types in GraphQL. The Query type defines the entry-points for data-fetching operations whereas the Mutation type specifies the entry points for data-manipulation operations.
The syntax for defining a Mutation type is given below −
type Mutation {
field1: data_type
field2(param1:data_type,param2:data_type,...paramN:data_type):data_type
}
For example, we can define a mutation type to add a new Student as below −
type Mutation {
addStudent(firstName: String, lastName: String): Student
}
An Enum is similar to a scalar type. Enums are useful in a situation where the value for a field must be from a prescribed list of options.
The syntax for defining an Enum type is −
type enum_name{
value1
value2
}
Following snippet illustrates how an enum type can be defined −
type Days_of_Week{
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
}
Lists can be used to represent an array of values of specific type. Lists are defined with a type modifier [] that wraps object types, scalars, and enums.
The following syntax can be used to define a list type −
field:[data_type]
The below example defines a list type todos −
type Query {
todos: [String]
}
By default, each of the core scalar types can be set to null. In other words, these types can either return a value of the specified type or they can have no value. To override this default and specify that a field must be defined, an exclamation mark (!) can be appended to a type. This ensures the presence of value in results returned by the query.
The following syntax can be used to define a non-nullable field −
field:data_type!
In the below example, stud_id is declared as a mandatory field.
type Student {
stud_id:ID!
firstName:String
lastName:String
fullName:String
college:College
}
43 Lectures
3 hours
Nilay Mehta
53 Lectures
3 hours
Asfend Yar
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2216,
"s": 1951,
"text": "GraphQL is a strongly typed language. Type System defines various data types that can be used in a GraphQL application. The type system helps to define the schema, which is a contract between client and server. The commonly used GraphQL data types are as follows −"
},
{
"code": null,
"e": 2223,
"s": 2216,
"text": "Scalar"
},
{
"code": null,
"e": 2245,
"s": 2223,
"text": "Stores a single value"
},
{
"code": null,
"e": 2252,
"s": 2245,
"text": "Object"
},
{
"code": null,
"e": 2293,
"s": 2252,
"text": "Shows what kind of object can be fetched"
},
{
"code": null,
"e": 2299,
"s": 2293,
"text": "Query"
},
{
"code": null,
"e": 2340,
"s": 2299,
"text": "Entry point type to other specific types"
},
{
"code": null,
"e": 2349,
"s": 2340,
"text": "Mutation"
},
{
"code": null,
"e": 2383,
"s": 2349,
"text": "Entry point for data manipulation"
},
{
"code": null,
"e": 2388,
"s": 2383,
"text": "Enum"
},
{
"code": null,
"e": 2476,
"s": 2388,
"text": "Useful in a situation where you need the user to pick from a prescribed list of options"
},
{
"code": null,
"e": 2601,
"s": 2476,
"text": "Scalar types are primitive data types that can store only a single value. The default scalar types that GraphQL offers are −"
},
{
"code": null,
"e": 2629,
"s": 2601,
"text": "Int − Signed 32-bit Integer"
},
{
"code": null,
"e": 2657,
"s": 2629,
"text": "Int − Signed 32-bit Integer"
},
{
"code": null,
"e": 2710,
"s": 2657,
"text": "Float − Signed double precision floating point value"
},
{
"code": null,
"e": 2763,
"s": 2710,
"text": "Float − Signed double precision floating point value"
},
{
"code": null,
"e": 2799,
"s": 2763,
"text": "String − UTF - 8-character sequence"
},
{
"code": null,
"e": 2835,
"s": 2799,
"text": "String − UTF - 8-character sequence"
},
{
"code": null,
"e": 2859,
"s": 2835,
"text": "Boolean − True or false"
},
{
"code": null,
"e": 2883,
"s": 2859,
"text": "Boolean − True or false"
},
{
"code": null,
"e": 2989,
"s": 2883,
"text": "ID − A unique identifier, often used as a unique identifier to fetch an object or as the key for a cache."
},
{
"code": null,
"e": 3095,
"s": 2989,
"text": "ID − A unique identifier, often used as a unique identifier to fetch an object or as the key for a cache."
},
{
"code": null,
"e": 3149,
"s": 3095,
"text": "The syntax for defining a scalar type is as follows −"
},
{
"code": null,
"e": 3167,
"s": 3149,
"text": "field: data_type\n"
},
{
"code": null,
"e": 3250,
"s": 3167,
"text": "The snippet given below defines a field named greeting which returns String value."
},
{
"code": null,
"e": 3268,
"s": 3250,
"text": "greeting: String\n"
},
{
"code": null,
"e": 3530,
"s": 3268,
"text": "The object type is the most common type used in a schema and represents a group of fields. Each field inside an object type maps to another type, thereby allowing nested types. In other words, an object type is composed of multiple scalar types or object types."
},
{
"code": null,
"e": 3586,
"s": 3530,
"text": "The syntax for defining an object type is given below −"
},
{
"code": null,
"e": 3683,
"s": 3586,
"text": "type object_type_name\n{\n field1: data_type\n field2:data_type \n ....\n fieldn:data_type\n}\n"
},
{
"code": null,
"e": 3729,
"s": 3683,
"text": "You can consider the following code snippet −"
},
{
"code": null,
"e": 3836,
"s": 3729,
"text": "--Define an object type--\n\ntype Student {\n stud_id:ID\n firstname: String\n age: Int\n score:Float\n}\n"
},
{
"code": null,
"e": 3911,
"s": 3836,
"text": "--Defining a GraphQL schema-- \n\ntype Query\n{\n stud_details:[Student]\n}\n"
},
{
"code": null,
"e": 4059,
"s": 3911,
"text": "The example given above defines an object data-type Student. The stud_details field in the root Query schema will return a list of Student objects."
},
{
"code": null,
"e": 4382,
"s": 4059,
"text": "A GraphQL query is used to fetch data. It is like requesting a resource in REST-based APIs. To keep it simple, the Query type is the request sent from a client application to the GraphQL server. GraphQL uses the Schema Definition Language (SDL) to define a Query. Query type is one of the many root-level types in GraphQL."
},
{
"code": null,
"e": 4434,
"s": 4382,
"text": "The syntax for defining a Query is as given below −"
},
{
"code": null,
"e": 4566,
"s": 4434,
"text": "type Query {\n field1: data_type\n field2:data_type\n field2(param1:data_type,param2:data_type,...paramN:data_type):data_type\n}\n"
},
{
"code": null,
"e": 4599,
"s": 4566,
"text": "An example of defining a Query −"
},
{
"code": null,
"e": 4635,
"s": 4599,
"text": "type Query {\n greeting: String\n}"
},
{
"code": null,
"e": 4799,
"s": 4635,
"text": "Mutations are operations sent to the server to create, update or delete data. These are analogous to the PUT, POST, PATCH and DELETE verbs to call REST-based APIs."
},
{
"code": null,
"e": 5012,
"s": 4799,
"text": "Mutation is one of the root-level data-types in GraphQL. The Query type defines the entry-points for data-fetching operations whereas the Mutation type specifies the entry points for data-manipulation operations."
},
{
"code": null,
"e": 5069,
"s": 5012,
"text": "The syntax for defining a Mutation type is given below −"
},
{
"code": null,
"e": 5185,
"s": 5069,
"text": "type Mutation {\n field1: data_type\n field2(param1:data_type,param2:data_type,...paramN:data_type):data_type \n}\n"
},
{
"code": null,
"e": 5260,
"s": 5185,
"text": "For example, we can define a mutation type to add a new Student as below −"
},
{
"code": null,
"e": 5338,
"s": 5260,
"text": "type Mutation {\n addStudent(firstName: String, lastName: String): Student\n}"
},
{
"code": null,
"e": 5478,
"s": 5338,
"text": "An Enum is similar to a scalar type. Enums are useful in a situation where the value for a field must be from a prescribed list of options."
},
{
"code": null,
"e": 5520,
"s": 5478,
"text": "The syntax for defining an Enum type is −"
},
{
"code": null,
"e": 5559,
"s": 5520,
"text": "type enum_name{\n value1\n value2\n}\n"
},
{
"code": null,
"e": 5623,
"s": 5559,
"text": "Following snippet illustrates how an enum type can be defined −"
},
{
"code": null,
"e": 5722,
"s": 5623,
"text": "type Days_of_Week{\n SUNDAY\n MONDAY\n TUESDAY\n WEDNESDAY\n THURSDAY\n FRIDAY\n SATURDAY\n}"
},
{
"code": null,
"e": 5877,
"s": 5722,
"text": "Lists can be used to represent an array of values of specific type. Lists are defined with a type modifier [] that wraps object types, scalars, and enums."
},
{
"code": null,
"e": 5934,
"s": 5877,
"text": "The following syntax can be used to define a list type −"
},
{
"code": null,
"e": 5953,
"s": 5934,
"text": "field:[data_type]\n"
},
{
"code": null,
"e": 5999,
"s": 5953,
"text": "The below example defines a list type todos −"
},
{
"code": null,
"e": 6033,
"s": 5999,
"text": "type Query {\n todos: [String]\n}"
},
{
"code": null,
"e": 6385,
"s": 6033,
"text": "By default, each of the core scalar types can be set to null. In other words, these types can either return a value of the specified type or they can have no value. To override this default and specify that a field must be defined, an exclamation mark (!) can be appended to a type. This ensures the presence of value in results returned by the query."
},
{
"code": null,
"e": 6451,
"s": 6385,
"text": "The following syntax can be used to define a non-nullable field −"
},
{
"code": null,
"e": 6469,
"s": 6451,
"text": "field:data_type!\n"
},
{
"code": null,
"e": 6533,
"s": 6469,
"text": "In the below example, stud_id is declared as a mandatory field."
},
{
"code": null,
"e": 6642,
"s": 6533,
"text": "type Student {\n stud_id:ID!\n firstName:String\n lastName:String\n fullName:String\n college:College\n}"
},
{
"code": null,
"e": 6675,
"s": 6642,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6688,
"s": 6675,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6721,
"s": 6688,
"text": "\n 53 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6733,
"s": 6721,
"text": " Asfend Yar"
},
{
"code": null,
"e": 6766,
"s": 6733,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6784,
"s": 6766,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 6791,
"s": 6784,
"text": " Print"
},
{
"code": null,
"e": 6802,
"s": 6791,
"text": " Add Notes"
}
] |
RxJS - Working with Subscription | When the observable is created, to execute the observable we need to subscribe to it.
Here, is a simple example of how to subscribe to an observable.
import { of } from 'rxjs';
import { count } from 'rxjs/operators';
let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
final_val.subscribe(x => console.log("The count is "+x));
The count is 6
The subscription has one method called unsubscribe(). A call to unsubscribe() method will remove all the resources used for that observable i.e. the observable will get canceled. Here, is a working example of using unsubscribe() method.
import { of } from 'rxjs';
import { count } from 'rxjs/operators';
let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
let test = final_val.subscribe(x => console.log("The count is "+x));
test.unsubscribe();
The subscription is stored in the variable test. We have used test.unsubscribe() the observable.
The count is 6
51 Lectures
4 hours
Daniel Stern
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1910,
"s": 1824,
"text": "When the observable is created, to execute the observable we need to subscribe to it."
},
{
"code": null,
"e": 1974,
"s": 1910,
"text": "Here, is a simple example of how to subscribe to an observable."
},
{
"code": null,
"e": 2180,
"s": 1974,
"text": "import { of } from 'rxjs';\nimport { count } from 'rxjs/operators';\n\nlet all_nums = of(1, 7, 5, 10, 10, 20);\nlet final_val = all_nums.pipe(count());\nfinal_val.subscribe(x => console.log(\"The count is \"+x));"
},
{
"code": null,
"e": 2196,
"s": 2180,
"text": "The count is 6\n"
},
{
"code": null,
"e": 2433,
"s": 2196,
"text": "The subscription has one method called unsubscribe(). A call to unsubscribe() method will remove all the resources used for that observable i.e. the observable will get canceled. Here, is a working example of using unsubscribe() method."
},
{
"code": null,
"e": 2670,
"s": 2433,
"text": "import { of } from 'rxjs';\nimport { count } from 'rxjs/operators';\n\nlet all_nums = of(1, 7, 5, 10, 10, 20);\nlet final_val = all_nums.pipe(count());\nlet test = final_val.subscribe(x => console.log(\"The count is \"+x));\ntest.unsubscribe();"
},
{
"code": null,
"e": 2767,
"s": 2670,
"text": "The subscription is stored in the variable test. We have used test.unsubscribe() the observable."
},
{
"code": null,
"e": 2783,
"s": 2767,
"text": "The count is 6\n"
},
{
"code": null,
"e": 2816,
"s": 2783,
"text": "\n 51 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2830,
"s": 2816,
"text": " Daniel Stern"
},
{
"code": null,
"e": 2837,
"s": 2830,
"text": " Print"
},
{
"code": null,
"e": 2848,
"s": 2837,
"text": " Add Notes"
}
] |
How to update parent state in ReactJS? | In this article, we are going to see how to update the parent state from a child component in a React application.
To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly.
In this example, we will build a React application which takes the state and the method to update it from the parent component and pass it to the children component and after handling it we will pass the updated state to the parent component.
App.jsx
import React, { useLayoutEffect, useState } from 'react';
const App = () => {
const [name, setName] = useState('Rahul');
return (
<div>
{name} has email id of [email protected]
<div>
<Child name={name} change={setName} />
</div>
</div>
);
};
const Child = ({ name, change }) => {
const [newName, setNewName] = useState(name);
return (
<div>
<input
placeholder="Enter new name"
value={newName}
onChange={(e) => setNewName(e.target.value)}
/>
<button onClick={() => change(newName )}>Change</button>
</div>
);
};
export default App;
In the above example, whenever the user types in the new name, then it changes and updates the state of the child component and when clicked on the change button, then it will update the state of the parent component accordingly.
This will produce the following result. | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "In this article, we are going to see how to update the parent state from a child component in a React application."
},
{
"code": null,
"e": 1399,
"s": 1177,
"text": "To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly."
},
{
"code": null,
"e": 1642,
"s": 1399,
"text": "In this example, we will build a React application which takes the state and the method to update it from the parent component and pass it to the children component and after handling it we will pass the updated state to the parent component."
},
{
"code": null,
"e": 1650,
"s": 1642,
"text": "App.jsx"
},
{
"code": null,
"e": 2303,
"s": 1650,
"text": "import React, { useLayoutEffect, useState } from 'react';\nconst App = () => {\n const [name, setName] = useState('Rahul');\n return (\n <div>\n {name} has email id of [email protected]\n <div>\n <Child name={name} change={setName} />\n </div>\n </div>\n );\n};\n\nconst Child = ({ name, change }) => {\n const [newName, setNewName] = useState(name);\n return (\n <div>\n <input\n placeholder=\"Enter new name\"\n value={newName}\n onChange={(e) => setNewName(e.target.value)}\n />\n <button onClick={() => change(newName )}>Change</button>\n </div>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 2533,
"s": 2303,
"text": "In the above example, whenever the user types in the new name, then it changes and updates the state of the child component and when clicked on the change button, then it will update the state of the parent component accordingly."
},
{
"code": null,
"e": 2573,
"s": 2533,
"text": "This will produce the following result."
}
] |
Find the number of consecutive zero at the end after multiplying n numbers in Python | Suppose we have an array with n numbers, we have to return the number of consecutive zero’s at the end after multiplying all the n numbers.
So, if the input is like [200, 20, 5, 30, 40, 14], then the output will be 6 as 200 * 20 * 5 * 30 * 40 * 14 = 336000000, there are six 0s at the end.
To solve this, we will follow these steps −
Define a function count_fact_two() . This will take n
Define a function count_fact_two() . This will take n
count := 0
count := 0
while n mod 2 is 0, docount := count + 1n := n / 2 (only the quotient as integer)
while n mod 2 is 0, do
count := count + 1
count := count + 1
n := n / 2 (only the quotient as integer)
n := n / 2 (only the quotient as integer)
return count
return count
Define a function count_fact_five() . This will take n
Define a function count_fact_five() . This will take n
count := 0
count := 0
while n mod 5 is 0, docount := count + 1n := n / 5 (only the quotient as integer)
while n mod 5 is 0, do
count := count + 1
count := count + 1
n := n / 5 (only the quotient as integer)
n := n / 5 (only the quotient as integer)
return count
return count
From the main method, do the following −
From the main method, do the following −
n := size of A
n := size of A
twos := 0, fives := 0
twos := 0, fives := 0
for i in range 0 to n, dotwos := twos + count_fact_two(A[i])fives := fives + count_fact_five(A[i])
for i in range 0 to n, do
twos := twos + count_fact_two(A[i])
twos := twos + count_fact_two(A[i])
fives := fives + count_fact_five(A[i])
fives := fives + count_fact_five(A[i])
if twos − fives, thenreturn twos
if twos − fives, then
return twos
return twos
otherwise,return fives
otherwise,
return fives
return fives
Let us see the following implementation to get better understanding −
Live Demo
def count_fact_two( n ):
count = 0
while n % 2 == 0:
count+=1
n = n // 2
return count
def count_fact_five( n ):
count = 0
while n % 5 == 0:
count += 1
n = n // 5
return count
def get_consecutive_zeros(A):
n = len(A)
twos = 0
fives = 0
for i in range(n):
twos += count_fact_two(A[i])
fives += count_fact_five(A[i])
if twos < fives:
return twos
else:
return fives
A = [200, 20, 5, 30, 40, 14]
print(get_consecutive_zeros(A))
[200, 20, 5, 30, 40, 14]
6 | [
{
"code": null,
"e": 1202,
"s": 1062,
"text": "Suppose we have an array with n numbers, we have to return the number of consecutive zero’s at the end after multiplying all the n numbers."
},
{
"code": null,
"e": 1352,
"s": 1202,
"text": "So, if the input is like [200, 20, 5, 30, 40, 14], then the output will be 6 as 200 * 20 * 5 * 30 * 40 * 14 = 336000000, there are six 0s at the end."
},
{
"code": null,
"e": 1396,
"s": 1352,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1450,
"s": 1396,
"text": "Define a function count_fact_two() . This will take n"
},
{
"code": null,
"e": 1504,
"s": 1450,
"text": "Define a function count_fact_two() . This will take n"
},
{
"code": null,
"e": 1515,
"s": 1504,
"text": "count := 0"
},
{
"code": null,
"e": 1526,
"s": 1515,
"text": "count := 0"
},
{
"code": null,
"e": 1608,
"s": 1526,
"text": "while n mod 2 is 0, docount := count + 1n := n / 2 (only the quotient as integer)"
},
{
"code": null,
"e": 1631,
"s": 1608,
"text": "while n mod 2 is 0, do"
},
{
"code": null,
"e": 1650,
"s": 1631,
"text": "count := count + 1"
},
{
"code": null,
"e": 1669,
"s": 1650,
"text": "count := count + 1"
},
{
"code": null,
"e": 1711,
"s": 1669,
"text": "n := n / 2 (only the quotient as integer)"
},
{
"code": null,
"e": 1753,
"s": 1711,
"text": "n := n / 2 (only the quotient as integer)"
},
{
"code": null,
"e": 1766,
"s": 1753,
"text": "return count"
},
{
"code": null,
"e": 1779,
"s": 1766,
"text": "return count"
},
{
"code": null,
"e": 1834,
"s": 1779,
"text": "Define a function count_fact_five() . This will take n"
},
{
"code": null,
"e": 1889,
"s": 1834,
"text": "Define a function count_fact_five() . This will take n"
},
{
"code": null,
"e": 1900,
"s": 1889,
"text": "count := 0"
},
{
"code": null,
"e": 1911,
"s": 1900,
"text": "count := 0"
},
{
"code": null,
"e": 1993,
"s": 1911,
"text": "while n mod 5 is 0, docount := count + 1n := n / 5 (only the quotient as integer)"
},
{
"code": null,
"e": 2016,
"s": 1993,
"text": "while n mod 5 is 0, do"
},
{
"code": null,
"e": 2035,
"s": 2016,
"text": "count := count + 1"
},
{
"code": null,
"e": 2054,
"s": 2035,
"text": "count := count + 1"
},
{
"code": null,
"e": 2096,
"s": 2054,
"text": "n := n / 5 (only the quotient as integer)"
},
{
"code": null,
"e": 2138,
"s": 2096,
"text": "n := n / 5 (only the quotient as integer)"
},
{
"code": null,
"e": 2151,
"s": 2138,
"text": "return count"
},
{
"code": null,
"e": 2164,
"s": 2151,
"text": "return count"
},
{
"code": null,
"e": 2205,
"s": 2164,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 2246,
"s": 2205,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 2261,
"s": 2246,
"text": "n := size of A"
},
{
"code": null,
"e": 2276,
"s": 2261,
"text": "n := size of A"
},
{
"code": null,
"e": 2298,
"s": 2276,
"text": "twos := 0, fives := 0"
},
{
"code": null,
"e": 2320,
"s": 2298,
"text": "twos := 0, fives := 0"
},
{
"code": null,
"e": 2419,
"s": 2320,
"text": "for i in range 0 to n, dotwos := twos + count_fact_two(A[i])fives := fives + count_fact_five(A[i])"
},
{
"code": null,
"e": 2445,
"s": 2419,
"text": "for i in range 0 to n, do"
},
{
"code": null,
"e": 2481,
"s": 2445,
"text": "twos := twos + count_fact_two(A[i])"
},
{
"code": null,
"e": 2517,
"s": 2481,
"text": "twos := twos + count_fact_two(A[i])"
},
{
"code": null,
"e": 2556,
"s": 2517,
"text": "fives := fives + count_fact_five(A[i])"
},
{
"code": null,
"e": 2595,
"s": 2556,
"text": "fives := fives + count_fact_five(A[i])"
},
{
"code": null,
"e": 2628,
"s": 2595,
"text": "if twos − fives, thenreturn twos"
},
{
"code": null,
"e": 2650,
"s": 2628,
"text": "if twos − fives, then"
},
{
"code": null,
"e": 2662,
"s": 2650,
"text": "return twos"
},
{
"code": null,
"e": 2674,
"s": 2662,
"text": "return twos"
},
{
"code": null,
"e": 2697,
"s": 2674,
"text": "otherwise,return fives"
},
{
"code": null,
"e": 2708,
"s": 2697,
"text": "otherwise,"
},
{
"code": null,
"e": 2721,
"s": 2708,
"text": "return fives"
},
{
"code": null,
"e": 2734,
"s": 2721,
"text": "return fives"
},
{
"code": null,
"e": 2804,
"s": 2734,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2815,
"s": 2804,
"text": " Live Demo"
},
{
"code": null,
"e": 3322,
"s": 2815,
"text": "def count_fact_two( n ):\n count = 0\n while n % 2 == 0:\n count+=1\n n = n // 2\n return count\ndef count_fact_five( n ):\n count = 0\n while n % 5 == 0:\n count += 1\n n = n // 5\n return count\ndef get_consecutive_zeros(A):\n n = len(A)\n twos = 0\n fives = 0\n for i in range(n):\n twos += count_fact_two(A[i])\n fives += count_fact_five(A[i])\n if twos < fives:\n return twos\n else:\n return fives\nA = [200, 20, 5, 30, 40, 14]\nprint(get_consecutive_zeros(A))"
},
{
"code": null,
"e": 3347,
"s": 3322,
"text": "[200, 20, 5, 30, 40, 14]"
},
{
"code": null,
"e": 3349,
"s": 3347,
"text": "6"
}
] |
Materialize - Cards | Materialize provides different CSS classes to apply various predefined visual and behavioral enhancements to display various types of cards. Following table mentions the available classes and their effects.
card
Identifies div element as a Materialize card container. Required on "outer" div.
card-content
Identifies div as a card content container and is required on "inner" div.
card-title
Identifies div as a card title container and is required on "inner" title div.
card-action
Identifies div as a card actions container and assigns appropriate text characteristics to actions text. Required on "inner" actions div; content goes directly inside the div with no intervening containers.
card-image
Identifies div as a card image container and is required on "inner" div.
card-reveal
Identifies div as a revealed text container.
activator
Identifies div as a revealed text container and image to be revealer. Used to show contextual information related to image.
card-panel
Identifies div as a simple card with shadows and padding.
card-small
Identifies div as a small sized card. Height − 300px;
card-medium
Identifies div as a medium sized card. Height − 400px;
card-larger
Identifies div as a large sized card. Height − 500px;
The following example showcases the use of card classes to showcase various types of cards.
<!DOCTYPE html>
<html>
<head>
<title>The Materialize Cards Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
</head>
<body class="container">
<div class="row">
<div class="col s12 m6">
<div class="card blue-grey lighten-4">
<div class="card-content">
<span class="card-title"><h3>Learn HTML5</h3></span>
<p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p>
</div>
<div class="card-action">
<button class="btn waves-effect waves-light blue-grey"><i class="material-icons">share</i></button>
<a class="right blue-grey-text" href="http://www.tutorialspoint.com">www.tutorialspoint.com</a>
</div>
</div>
</div>
<div class="col s12 m6">
<div class="card blue-grey lighten-4">
<div class="card-image">
<img src="html5-mini-logo.jpg">
</div>
<div class="card-content">
<p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p>
</div>
<div class="card-action">
<button class="btn waves-effect waves-light blue-grey"><i class="material-icons">share</i></button>
<a class="right blue-grey-text" href="http://www.tutorialspoint.com">www.tutorialspoint.com</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s12 m6">
<div class="card blue-grey lighten-4">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="html5-mini-logo.jpg">
</div>
<div class="card-content activator">
<p>Click the image to reveal more information.</p>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">HTML5<i class="material-icons right">close</i></span>
<p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p>
</div>
<div class="card-action">
<button class="btn waves-effect waves-light blue-grey"><i class="material-icons">share</i></button>
<a class="right blue-grey-text" href="http://www.tutorialspoint.com">www.tutorialspoint.com</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s12 m3">
<div class="card-panel teal">
<span class="white-text">Simple Card</span>
</div>
</div>
<div class="col s12 m3">
<div class="card small teal">
<span class="white-text">Small Card</span>
</div>
</div>
<div class="col s12 m3">
<div class="card medium teal">
<span class="white-text">Medium Card</span>
</div>
</div>
<div class="col s12 m3">
<div class="card large teal">
<span class="white-text">Large Card</span>
</div>
</div>
</div>
</body>
</html>
Verify the output.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2394,
"s": 2187,
"text": "Materialize provides different CSS classes to apply various predefined visual and behavioral enhancements to display various types of cards. Following table mentions the available classes and their effects."
},
{
"code": null,
"e": 2399,
"s": 2394,
"text": "card"
},
{
"code": null,
"e": 2480,
"s": 2399,
"text": "Identifies div element as a Materialize card container. Required on \"outer\" div."
},
{
"code": null,
"e": 2493,
"s": 2480,
"text": "card-content"
},
{
"code": null,
"e": 2568,
"s": 2493,
"text": "Identifies div as a card content container and is required on \"inner\" div."
},
{
"code": null,
"e": 2579,
"s": 2568,
"text": "card-title"
},
{
"code": null,
"e": 2658,
"s": 2579,
"text": "Identifies div as a card title container and is required on \"inner\" title div."
},
{
"code": null,
"e": 2670,
"s": 2658,
"text": "card-action"
},
{
"code": null,
"e": 2877,
"s": 2670,
"text": "Identifies div as a card actions container and assigns appropriate text characteristics to actions text. Required on \"inner\" actions div; content goes directly inside the div with no intervening containers."
},
{
"code": null,
"e": 2888,
"s": 2877,
"text": "card-image"
},
{
"code": null,
"e": 2961,
"s": 2888,
"text": "Identifies div as a card image container and is required on \"inner\" div."
},
{
"code": null,
"e": 2973,
"s": 2961,
"text": "card-reveal"
},
{
"code": null,
"e": 3018,
"s": 2973,
"text": "Identifies div as a revealed text container."
},
{
"code": null,
"e": 3028,
"s": 3018,
"text": "activator"
},
{
"code": null,
"e": 3152,
"s": 3028,
"text": "Identifies div as a revealed text container and image to be revealer. Used to show contextual information related to image."
},
{
"code": null,
"e": 3163,
"s": 3152,
"text": "card-panel"
},
{
"code": null,
"e": 3221,
"s": 3163,
"text": "Identifies div as a simple card with shadows and padding."
},
{
"code": null,
"e": 3232,
"s": 3221,
"text": "card-small"
},
{
"code": null,
"e": 3286,
"s": 3232,
"text": "Identifies div as a small sized card. Height − 300px;"
},
{
"code": null,
"e": 3298,
"s": 3286,
"text": "card-medium"
},
{
"code": null,
"e": 3353,
"s": 3298,
"text": "Identifies div as a medium sized card. Height − 400px;"
},
{
"code": null,
"e": 3365,
"s": 3353,
"text": "card-larger"
},
{
"code": null,
"e": 3419,
"s": 3365,
"text": "Identifies div as a large sized card. Height − 500px;"
},
{
"code": null,
"e": 3511,
"s": 3419,
"text": "The following example showcases the use of card classes to showcase various types of cards."
},
{
"code": null,
"e": 7551,
"s": 3511,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>The Materialize Cards Example</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js\"></script>\n </head>\n <body class=\"container\">\n <div class=\"row\">\n <div class=\"col s12 m6\">\n <div class=\"card blue-grey lighten-4\">\n <div class=\"card-content\">\n <span class=\"card-title\"><h3>Learn HTML5</h3></span>\n <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p>\n </div>\n <div class=\"card-action\">\n <button class=\"btn waves-effect waves-light blue-grey\"><i class=\"material-icons\">share</i></button>\n <a class=\"right blue-grey-text\" href=\"http://www.tutorialspoint.com\">www.tutorialspoint.com</a>\n </div>\n </div>\n </div>\n <div class=\"col s12 m6\">\n <div class=\"card blue-grey lighten-4\">\n <div class=\"card-image\">\n <img src=\"html5-mini-logo.jpg\">\n </div>\n <div class=\"card-content\">\n <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p>\n </div>\n <div class=\"card-action\">\n <button class=\"btn waves-effect waves-light blue-grey\"><i class=\"material-icons\">share</i></button>\n <a class=\"right blue-grey-text\" href=\"http://www.tutorialspoint.com\">www.tutorialspoint.com</a>\n </div>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col s12 m6\">\n <div class=\"card blue-grey lighten-4\">\n <div class=\"card-image waves-effect waves-block waves-light\">\n <img class=\"activator\" src=\"html5-mini-logo.jpg\">\n </div>\n <div class=\"card-content activator\">\n <p>Click the image to reveal more information.</p>\n </div>\n <div class=\"card-reveal\">\n <span class=\"card-title grey-text text-darken-4\">HTML5<i class=\"material-icons right\">close</i></span>\n <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p>\n </div>\n <div class=\"card-action\">\n <button class=\"btn waves-effect waves-light blue-grey\"><i class=\"material-icons\">share</i></button>\n <a class=\"right blue-grey-text\" href=\"http://www.tutorialspoint.com\">www.tutorialspoint.com</a>\n </div>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col s12 m3\">\n <div class=\"card-panel teal\">\n <span class=\"white-text\">Simple Card</span>\n </div>\n </div>\n <div class=\"col s12 m3\">\n <div class=\"card small teal\">\n <span class=\"white-text\">Small Card</span>\n </div>\n </div>\n <div class=\"col s12 m3\">\n <div class=\"card medium teal\">\n <span class=\"white-text\">Medium Card</span>\n </div>\n </div>\n <div class=\"col s12 m3\">\n <div class=\"card large teal\">\n <span class=\"white-text\">Large Card</span>\n </div>\n </div>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 7570,
"s": 7551,
"text": "Verify the output."
},
{
"code": null,
"e": 7577,
"s": 7570,
"text": " Print"
},
{
"code": null,
"e": 7588,
"s": 7577,
"text": " Add Notes"
}
] |
Convert string from lowercase to uppercase in R programming - toupper() function - GeeksforGeeks | 10 May, 2020
toupper() method in R programming is used to convert the lowercase string to uppercase string.
Syntax: toupper(s)
Return: Returns the uppercase string.
Example 1:
# R program to convert string# from lowercase to uppercase # Given Stringgfg <- "Geeks For Geeks" # Using toupper() methodanswer <- toupper(gfg) print(answer)
Output:
[1] "GEEKS FOR GEEKS"
Example 2:
# R program to convert string# from lowercase to uppercase # Given Stringgfg <- "The quick brown fox jumps over the lazy dog" # Using toupper() methodanswer <- toupper(gfg) print(answer)
Output:
[1] "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
Replace Specific Characters in String in R | [
{
"code": null,
"e": 24545,
"s": 24517,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24640,
"s": 24545,
"text": "toupper() method in R programming is used to convert the lowercase string to uppercase string."
},
{
"code": null,
"e": 24659,
"s": 24640,
"text": "Syntax: toupper(s)"
},
{
"code": null,
"e": 24697,
"s": 24659,
"text": "Return: Returns the uppercase string."
},
{
"code": null,
"e": 24708,
"s": 24697,
"text": "Example 1:"
},
{
"code": "# R program to convert string# from lowercase to uppercase # Given Stringgfg <- \"Geeks For Geeks\" # Using toupper() methodanswer <- toupper(gfg) print(answer)",
"e": 24870,
"s": 24708,
"text": null
},
{
"code": null,
"e": 24878,
"s": 24870,
"text": "Output:"
},
{
"code": null,
"e": 24901,
"s": 24878,
"text": "[1] \"GEEKS FOR GEEKS\"\n"
},
{
"code": null,
"e": 24912,
"s": 24901,
"text": "Example 2:"
},
{
"code": "# R program to convert string# from lowercase to uppercase # Given Stringgfg <- \"The quick brown fox jumps over the lazy dog\" # Using toupper() methodanswer <- toupper(gfg) print(answer)",
"e": 25102,
"s": 24912,
"text": null
},
{
"code": null,
"e": 25110,
"s": 25102,
"text": "Output:"
},
{
"code": null,
"e": 25161,
"s": 25110,
"text": "[1] \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\"\n"
},
{
"code": null,
"e": 25172,
"s": 25161,
"text": "R Language"
},
{
"code": null,
"e": 25270,
"s": 25172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25279,
"s": 25270,
"text": "Comments"
},
{
"code": null,
"e": 25292,
"s": 25279,
"text": "Old Comments"
},
{
"code": null,
"e": 25336,
"s": 25292,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 25388,
"s": 25336,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 25440,
"s": 25388,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 25472,
"s": 25440,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 25510,
"s": 25472,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 25568,
"s": 25510,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 25603,
"s": 25568,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 25639,
"s": 25603,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 25688,
"s": 25639,
"text": "Remove rows with NA in one column of R DataFrame"
}
] |
Python unittest - assertNotEqual() function - GeeksforGeeks | 29 Aug, 2020
assertNotEqual() in Python is a unittest library function that is used in unit testing to check the inequality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are unequal assertNotEqual() will return true else return false.
Syntax:
assertNotEqual(firstValue, secondValue, message)
Parameters: assertNotEqual() accept three parameters which are listed below with explanation:
firstValue: variable of any type which is used in the comparison by function
secondValue: variable of any type which is used in the comparison by function
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_negative(self): firstValue = "geeks" secondValue = "geeksg" # error message in case if test case got failed message = "First value and second value are not unequal !" # assertNotEqual() to check unequality of first & second value self.assertNotEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p1.py", line 12, in test_negative
self.assertNotEqual(firstValue, secondValue, message)
AssertionError: 'geeks' == 'geeks' : First value and second value are not unequal!
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Example 2: Positive Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_positive(self): firstValue = "geeks" secondValue = "geeks" # error message in case if test case got failed message = "First value and second value are not unequal !" # assertNotEqual() to check equality of first & second value self.assertNotEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 24890,
"s": 24862,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 25216,
"s": 24890,
"text": "assertNotEqual() in Python is a unittest library function that is used in unit testing to check the inequality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are unequal assertNotEqual() will return true else return false."
},
{
"code": null,
"e": 25224,
"s": 25216,
"text": "Syntax:"
},
{
"code": null,
"e": 25273,
"s": 25224,
"text": "assertNotEqual(firstValue, secondValue, message)"
},
{
"code": null,
"e": 25367,
"s": 25273,
"text": "Parameters: assertNotEqual() accept three parameters which are listed below with explanation:"
},
{
"code": null,
"e": 25444,
"s": 25367,
"text": "firstValue: variable of any type which is used in the comparison by function"
},
{
"code": null,
"e": 25522,
"s": 25444,
"text": "secondValue: variable of any type which is used in the comparison by function"
},
{
"code": null,
"e": 25613,
"s": 25522,
"text": "message: a string sentence as a message which got displayed when the test case got failed."
},
{
"code": null,
"e": 25729,
"s": 25613,
"text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:"
},
{
"code": null,
"e": 25759,
"s": 25729,
"text": "Example 1: Negative Test case"
},
{
"code": null,
"e": 25767,
"s": 25759,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_negative(self): firstValue = \"geeks\" secondValue = \"geeksg\" # error message in case if test case got failed message = \"First value and second value are not unequal !\" # assertNotEqual() to check unequality of first & second value self.assertNotEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()",
"e": 26278,
"s": 25767,
"text": null
},
{
"code": null,
"e": 26286,
"s": 26278,
"text": "Output:"
},
{
"code": null,
"e": 26814,
"s": 26286,
"text": "F\n======================================================================\nFAIL: test_negative (__main__.TestStringMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 12, in test_negative\n self.assertNotEqual(firstValue, secondValue, message)\nAssertionError: 'geeks' == 'geeks' : First value and second value are not unequal!\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n\n\n"
},
{
"code": null,
"e": 26844,
"s": 26814,
"text": "Example 2: Positive Test case"
},
{
"code": null,
"e": 26852,
"s": 26844,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_positive(self): firstValue = \"geeks\" secondValue = \"geeks\" # error message in case if test case got failed message = \"First value and second value are not unequal !\" # assertNotEqual() to check equality of first & second value self.assertNotEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()",
"e": 27360,
"s": 26852,
"text": null
},
{
"code": null,
"e": 27368,
"s": 27360,
"text": "Output:"
},
{
"code": null,
"e": 27468,
"s": 27368,
"text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n\n"
},
{
"code": null,
"e": 27527,
"s": 27468,
"text": "Reference: https://docs.python.org/3/library/unittest.html"
},
{
"code": null,
"e": 27551,
"s": 27527,
"text": "Python unittest-library"
},
{
"code": null,
"e": 27558,
"s": 27551,
"text": "Python"
},
{
"code": null,
"e": 27656,
"s": 27558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27674,
"s": 27656,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27706,
"s": 27674,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27728,
"s": 27706,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27770,
"s": 27728,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27796,
"s": 27770,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27840,
"s": 27796,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27877,
"s": 27840,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27906,
"s": 27877,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27942,
"s": 27906,
"text": "Convert integer to string in Python"
}
] |
Smallest Positive missing number | Practice | GeeksforGeeks | You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array.
Example 1:
Input:
N = 5
arr[] = {1,2,3,4,5}
Output: 6
Explanation: Smallest positive missing
number is 6.
Example 2:
Input:
N = 5
arr[] = {0,-10,1,3,-20}
Output: 2
Explanation: Smallest positive missing
number is 2.
Your Task:
The task is to complete the function missingNumber() which returns the smallest positive missing number in the array.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 106
-106 <= arr[i] <= 106
0
abuzart199913 hours ago
Easy Java Solution:
int miss = 1; Arrays.sort(arr); for(int i = 0;i<size;i++){ if(arr[i]>0&&miss==arr[i]) miss++; } return miss;
0
bharathk1n7t1 day ago
int missingNumber(int[] array, int n) { var vs = array.Where(x => x > 0).OrderBy(x => x).AsEnumerable(); var result = 0; if (vs.Any(x => x == 1)) { for (int j = 0; j <= vs.Count() - 1; j++) { if (vs.Any(x => x == result) || j == 0) { result = vs.ElementAt(j) + 1; }
} } else { return 1; } return result; }
+5
kaganesh122 days ago
easiest way to do this is as follows:
int missingNumber(int arr[], int n) { sort(arr,arr+n); int count=1; for (int i=0;i<n;i++) { if (arr[i]==count) count++; } return count; }
-1
hrishabhgarg0074 days ago
class Solution{ //Function to find the smallest positive number missing from the array. static int missingNumber(int arr[], int size) { Arrays.sort(arr); int i=0,res=1; while(i<size){ if(arr[i]<res){ i++; } else if(arr[i]==res){ res++; } else{ return res; } } return(res);}}
-2
akyadav133984 days ago
int missingNumber(int a[], int n) { int i; int j=1; sort(a,a+n); for(i=0;i<n;i++) { if(a[i]<=0)continue; if(j==a[i]) {j++; } } return j; }
+1
shivamsingh001414 days ago
class Solution
{
public:
//Function to find the smallest positive number missing from the array.
int missingNumber(int arr[], int n)
{
for(int i = 0; i < n; i++) {
while(arr[i] > 0 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) {
swap(arr[i], arr[arr[i] - 1]);
}
}
for(int i = 0; i < n; i++) {
if(arr[i] != i + 1) return i + 1;
}
return n + 1;
}
};
0
ruchikajamwal03195 days ago
class Solution{ public: //Function to find the smallest positive number missing from the array. int missingNumber(int arr[], int n) { // Your code here int temp=0; for(int i=0;i<n;i++){ if(arr[i]>=1 && arr[i]<=n && arr[i]!=arr[arr[i]-1]){ swap(arr[i],arr[arr[i]-1]); i--; } } for(int i=0;i<n;i++){ if(arr[i]!=i+1){ return i+1; } } return n+1; }};
0
sahiltushamar6 days ago
Can Anyone Correct the mistake, Logical Error Segmentation Fault.
int missingNumber(int arr[], int n) { int i=1; int N = INT_MAX; bool check[N]; for(i=1;i<=N;i++){ check[i]=false; } for(i=1;i<=n;i++){ if(arr[i]>=1){ check[arr[i]]=true; } } int count=-1; for(i=1;i<=N;i++){ if(check[i]==true){ count++ ; } } return count; }
0
aks766251 week ago
int missingNumber(int arr[], int n)
{
int temp=0;
for(int i=0;i<n;i++){
if(arr[i]>=1 && arr[i]<=n && arr[i]!=arr[arr[i]-1]){
swap(arr[i],arr[arr[i]-1]);
i--;
}
}
for(int i=0;i<n;i++){
if(arr[i]!=i+1){
return i+1;
}
}
return n+1;
}
-1
jubin kumar soni1 week ago
int missingNumber(int arr[], int n)
{
// Your code here
unordered_set<int> us;
int res = 1;
for(int i=0;i<n;i++)
{
if(arr[i] == res)
{
res = res + 1;
while(us.find(res) != us.end())
{
res = res + 1;
}
}
else if(arr[i] > 0)
{
us.insert(arr[i]);
}
/*
if(arr[i] > res)
{
// pass
}
*/
}
return res;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 367,
"s": 238,
"text": "You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array."
},
{
"code": null,
"e": 378,
"s": 367,
"text": "Example 1:"
},
{
"code": null,
"e": 475,
"s": 378,
"text": "Input:\nN = 5\narr[] = {1,2,3,4,5}\nOutput: 6\nExplanation: Smallest positive missing \nnumber is 6.\n"
},
{
"code": null,
"e": 486,
"s": 475,
"text": "Example 2:"
},
{
"code": null,
"e": 586,
"s": 486,
"text": "Input:\nN = 5\narr[] = {0,-10,1,3,-20}\nOutput: 2\nExplanation: Smallest positive missing \nnumber is 2."
},
{
"code": null,
"e": 715,
"s": 586,
"text": "Your Task:\nThe task is to complete the function missingNumber() which returns the smallest positive missing number in the array."
},
{
"code": null,
"e": 779,
"s": 715,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 828,
"s": 779,
"text": "Constraints:\n1 <= N <= 106\n-106 <= arr[i] <= 106"
},
{
"code": null,
"e": 832,
"s": 830,
"text": "0"
},
{
"code": null,
"e": 856,
"s": 832,
"text": "abuzart199913 hours ago"
},
{
"code": null,
"e": 876,
"s": 856,
"text": "Easy Java Solution:"
},
{
"code": null,
"e": 1035,
"s": 878,
"text": "int miss = 1; Arrays.sort(arr); for(int i = 0;i<size;i++){ if(arr[i]>0&&miss==arr[i]) miss++; } return miss;"
},
{
"code": null,
"e": 1037,
"s": 1035,
"text": "0"
},
{
"code": null,
"e": 1059,
"s": 1037,
"text": "bharathk1n7t1 day ago"
},
{
"code": null,
"e": 1486,
"s": 1059,
"text": "int missingNumber(int[] array, int n) { var vs = array.Where(x => x > 0).OrderBy(x => x).AsEnumerable(); var result = 0; if (vs.Any(x => x == 1)) { for (int j = 0; j <= vs.Count() - 1; j++) { if (vs.Any(x => x == result) || j == 0) { result = vs.ElementAt(j) + 1; }"
},
{
"code": null,
"e": 1611,
"s": 1486,
"text": " } } else { return 1; } return result; }"
},
{
"code": null,
"e": 1614,
"s": 1611,
"text": "+5"
},
{
"code": null,
"e": 1635,
"s": 1614,
"text": "kaganesh122 days ago"
},
{
"code": null,
"e": 1673,
"s": 1635,
"text": "easiest way to do this is as follows:"
},
{
"code": null,
"e": 1882,
"s": 1675,
"text": "int missingNumber(int arr[], int n) { sort(arr,arr+n); int count=1; for (int i=0;i<n;i++) { if (arr[i]==count) count++; } return count; } "
},
{
"code": null,
"e": 1885,
"s": 1882,
"text": "-1"
},
{
"code": null,
"e": 1911,
"s": 1885,
"text": "hrishabhgarg0074 days ago"
},
{
"code": null,
"e": 2324,
"s": 1911,
"text": "class Solution{ //Function to find the smallest positive number missing from the array. static int missingNumber(int arr[], int size) { Arrays.sort(arr); int i=0,res=1; while(i<size){ if(arr[i]<res){ i++; } else if(arr[i]==res){ res++; } else{ return res; } } return(res);}}"
},
{
"code": null,
"e": 2327,
"s": 2324,
"text": "-2"
},
{
"code": null,
"e": 2350,
"s": 2327,
"text": "akyadav133984 days ago"
},
{
"code": null,
"e": 2602,
"s": 2350,
"text": " int missingNumber(int a[], int n) { int i; int j=1; sort(a,a+n); for(i=0;i<n;i++) { if(a[i]<=0)continue; if(j==a[i]) {j++; } } return j; } "
},
{
"code": null,
"e": 2605,
"s": 2602,
"text": "+1"
},
{
"code": null,
"e": 2632,
"s": 2605,
"text": "shivamsingh001414 days ago"
},
{
"code": null,
"e": 3112,
"s": 2632,
"text": "class Solution\n{\n public:\n //Function to find the smallest positive number missing from the array.\n int missingNumber(int arr[], int n) \n { \n for(int i = 0; i < n; i++) {\n while(arr[i] > 0 && arr[i] <= n && arr[i] != arr[arr[i] - 1]) {\n swap(arr[i], arr[arr[i] - 1]);\n }\n }\n \n for(int i = 0; i < n; i++) {\n if(arr[i] != i + 1) return i + 1;\n }\n \n return n + 1;\n } \n};"
},
{
"code": null,
"e": 3114,
"s": 3112,
"text": "0"
},
{
"code": null,
"e": 3142,
"s": 3114,
"text": "ruchikajamwal03195 days ago"
},
{
"code": null,
"e": 3633,
"s": 3142,
"text": "class Solution{ public: //Function to find the smallest positive number missing from the array. int missingNumber(int arr[], int n) { // Your code here int temp=0; for(int i=0;i<n;i++){ if(arr[i]>=1 && arr[i]<=n && arr[i]!=arr[arr[i]-1]){ swap(arr[i],arr[arr[i]-1]); i--; } } for(int i=0;i<n;i++){ if(arr[i]!=i+1){ return i+1; } } return n+1; }}; "
},
{
"code": null,
"e": 3635,
"s": 3633,
"text": "0"
},
{
"code": null,
"e": 3659,
"s": 3635,
"text": "sahiltushamar6 days ago"
},
{
"code": null,
"e": 3725,
"s": 3659,
"text": "Can Anyone Correct the mistake, Logical Error Segmentation Fault."
},
{
"code": null,
"e": 4133,
"s": 3725,
"text": "int missingNumber(int arr[], int n) { int i=1; int N = INT_MAX; bool check[N]; for(i=1;i<=N;i++){ check[i]=false; } for(i=1;i<=n;i++){ if(arr[i]>=1){ check[arr[i]]=true; } } int count=-1; for(i=1;i<=N;i++){ if(check[i]==true){ count++ ; } } return count; } "
},
{
"code": null,
"e": 4137,
"s": 4135,
"text": "0"
},
{
"code": null,
"e": 4156,
"s": 4137,
"text": "aks766251 week ago"
},
{
"code": null,
"e": 4560,
"s": 4156,
"text": "int missingNumber(int arr[], int n) \n { \n int temp=0;\n for(int i=0;i<n;i++){\n if(arr[i]>=1 && arr[i]<=n && arr[i]!=arr[arr[i]-1]){\n swap(arr[i],arr[arr[i]-1]);\n i--;\n }\n }\n \n for(int i=0;i<n;i++){\n if(arr[i]!=i+1){\n return i+1;\n }\n }\n \n return n+1;\n } "
},
{
"code": null,
"e": 4563,
"s": 4560,
"text": "-1"
},
{
"code": null,
"e": 4590,
"s": 4563,
"text": "jubin kumar soni1 week ago"
},
{
"code": null,
"e": 5224,
"s": 4590,
"text": "int missingNumber(int arr[], int n) \n { \n // Your code here\n unordered_set<int> us;\n int res = 1;\n for(int i=0;i<n;i++)\n {\n if(arr[i] == res)\n {\n res = res + 1;\n while(us.find(res) != us.end())\n {\n res = res + 1;\n }\n }\n else if(arr[i] > 0)\n {\n us.insert(arr[i]);\n }\n \n /*\n if(arr[i] > res)\n {\n // pass\n }\n */\n }\n \n return res;\n } "
},
{
"code": null,
"e": 5370,
"s": 5224,
"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": 5406,
"s": 5370,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5416,
"s": 5406,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5426,
"s": 5416,
"text": "\nContest\n"
},
{
"code": null,
"e": 5489,
"s": 5426,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5674,
"s": 5489,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5958,
"s": 5674,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6104,
"s": 5958,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6181,
"s": 6104,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6222,
"s": 6181,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6250,
"s": 6222,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6321,
"s": 6250,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 6508,
"s": 6321,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Effect of adding whitespace in the scanf() function in C | 19 May, 2021
In this article, we will discuss the scenarios regarding adding white space before or after the format specifier in a scanf() function in C Programming Language.
Adding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed.
scanf("%d ");
scanf(" %d");
scanf("%d\n"); This is different
from scanf("%d"); function.
Example 1: The scanf function after reading the number starts reading further until it finds a non-whitespace character on the input and prints the first number that was typed.
Adding whitespace or “\n” after format specifier in scanf functionscanf(“%d “); or scanf(“%d\n”, );
Below is the C program to implement the above approach:
C
// C program to demonstrate the// above approach #include <stdio.h> // Driver Codeint main(){ // Declaring integer variable a int a; // Reading value in "a" using scanf // and adding whitespace after // format specifier scanf("%d ", &a); // Or scanf("%d\n", &a); // Both work the same and // print the same value printf("%d", a); return 0;}
Output:
Explanation: In the above example, when the program is executed, first the program will ask for the first input.
In this case, 2 is entered, after that whitespace is given and still there is no output rather waiting for the next input.
When 3 is entered, the output is printed which is the first number that is entered i.e., 2.
Similarly, is the case when after entering the first input i.e., 2 in the above case, if the user presses enter button and goes to the next line, the program is still waiting for the input and after entering the second input the result is printed.
Example 2: The scanf function ignores the whitespace character and reads the element only once.
Adding whitespace before format specifier in scanf functionscanf(” %d”);
Below is the C program to implement the above approach:
C
// C program to demonstrate the// above approach#include <stdio.h> // Driver Codeint main(){ // Declaring integer variable int a; // Reading value in a using scanf // and adding whitespace before // format specifier scanf(" %d", &a); // Printing value of a printf("%d", a); return 0;}
Output:
Explanation: In this code, there is an output as soon as the number is entered because almost all the whitespaces before format specifier are ignored by scanf %-conversions except for “%c”, “%n”, and “%[“. Hence, it is advised to avoid whitespaces in scanf function as much as possible unless one is confident of its use and necessity.
C Basics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 216,
"s": 54,
"text": "In this article, we will discuss the scenarios regarding adding white space before or after the format specifier in a scanf() function in C Programming Language."
},
{
"code": null,
"e": 398,
"s": 216,
"text": "Adding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed."
},
{
"code": null,
"e": 488,
"s": 398,
"text": "scanf(\"%d \");\nscanf(\" %d\");\n\nscanf(\"%d\\n\"); This is different\nfrom scanf(\"%d\"); function."
},
{
"code": null,
"e": 665,
"s": 488,
"text": "Example 1: The scanf function after reading the number starts reading further until it finds a non-whitespace character on the input and prints the first number that was typed."
},
{
"code": null,
"e": 774,
"s": 665,
"text": "Adding whitespace or “\\n” after format specifier in scanf functionscanf(“%d “); or scanf(“%d\\n”, );"
},
{
"code": null,
"e": 830,
"s": 774,
"text": "Below is the C program to implement the above approach:"
},
{
"code": null,
"e": 832,
"s": 830,
"text": "C"
},
{
"code": "// C program to demonstrate the// above approach #include <stdio.h> // Driver Codeint main(){ // Declaring integer variable a int a; // Reading value in \"a\" using scanf // and adding whitespace after // format specifier scanf(\"%d \", &a); // Or scanf(\"%d\\n\", &a); // Both work the same and // print the same value printf(\"%d\", a); return 0;}",
"e": 1216,
"s": 832,
"text": null
},
{
"code": null,
"e": 1224,
"s": 1216,
"text": "Output:"
},
{
"code": null,
"e": 1337,
"s": 1224,
"text": "Explanation: In the above example, when the program is executed, first the program will ask for the first input."
},
{
"code": null,
"e": 1460,
"s": 1337,
"text": "In this case, 2 is entered, after that whitespace is given and still there is no output rather waiting for the next input."
},
{
"code": null,
"e": 1552,
"s": 1460,
"text": "When 3 is entered, the output is printed which is the first number that is entered i.e., 2."
},
{
"code": null,
"e": 1800,
"s": 1552,
"text": "Similarly, is the case when after entering the first input i.e., 2 in the above case, if the user presses enter button and goes to the next line, the program is still waiting for the input and after entering the second input the result is printed."
},
{
"code": null,
"e": 1896,
"s": 1800,
"text": "Example 2: The scanf function ignores the whitespace character and reads the element only once."
},
{
"code": null,
"e": 1969,
"s": 1896,
"text": "Adding whitespace before format specifier in scanf functionscanf(” %d”);"
},
{
"code": null,
"e": 2025,
"s": 1969,
"text": "Below is the C program to implement the above approach:"
},
{
"code": null,
"e": 2027,
"s": 2025,
"text": "C"
},
{
"code": "// C program to demonstrate the// above approach#include <stdio.h> // Driver Codeint main(){ // Declaring integer variable int a; // Reading value in a using scanf // and adding whitespace before // format specifier scanf(\" %d\", &a); // Printing value of a printf(\"%d\", a); return 0;}",
"e": 2346,
"s": 2027,
"text": null
},
{
"code": null,
"e": 2354,
"s": 2346,
"text": "Output:"
},
{
"code": null,
"e": 2690,
"s": 2354,
"text": "Explanation: In this code, there is an output as soon as the number is entered because almost all the whitespaces before format specifier are ignored by scanf %-conversions except for “%c”, “%n”, and “%[“. Hence, it is advised to avoid whitespaces in scanf function as much as possible unless one is confident of its use and necessity."
},
{
"code": null,
"e": 2699,
"s": 2690,
"text": "C Basics"
},
{
"code": null,
"e": 2710,
"s": 2699,
"text": "C Language"
},
{
"code": null,
"e": 2721,
"s": 2710,
"text": "C Programs"
}
] |
How can I loop through all rows of a table in MySQL? | To loop through all rows of a table, use stored procedure in MySQL. The syntax is as follows −
delimiter //
CREATE PROCEDURE yourProcedureName()
BEGIN
DECLARE anyVariableName1 INT DEFAULT 0;
DECLARE anyVariableName2 INT DEFAULT 0;
SELECT COUNT(*) FROM yourTableName1 INTO anyVariableName1;
SET anyVariableName2 =0;
WHILE anyVariableName2 < anyVariableName1 DO
INSERT INTO yourTableName2(yourColumnName,...N) SELECT (yourColumnName1,...N)
FROM yourTableName1 LIMIT anyVariableName2,1;
SET anyVariableName2 = anyVariableName2+1;
END WHILE;
End;
//
To understand the above syntax, let us create two tables i.e. one has records and the second table will have records from the loop using stored procedures.
The following is the query to create first table −
mysql> create table AllRows
-> (
-> Id int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.46 sec)
Insert some records in the first table using insert command. The query is as follows −
mysql> insert into AllRows values(1,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into AllRows values(100,'Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into AllRows values(300,'Sam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into AllRows values(400,'Mike');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from AllRows;
+------+-------+
| Id | Name |
+------+-------+
| 1 | John |
| 100 | Carol |
| 300 | Sam |
| 400 | Mike |
+------+-------+
4 rows in set (0.00 sec)
Here is the query to create a second table. The query to create a table is as follows −
mysql> create table SecondTableRows
-> (
-> StudentId int,
-> StudentName varchar(100)
-> );
Query OK, 0 rows affected (0.54 sec)
Now you can loop through all rows of a table using stored procedure. The stored procedure is as follows −
mysql> delimiter //
mysql> CREATE PROCEDURE Sp_AllRowsOfATable()
-> BEGIN
-> DECLARE lastRows INT DEFAULT 0;
-> DECLARE startRows INT DEFAULT 0;
-> SELECT COUNT(*) FROM AllRows INTO lastRows;
-> SET startRows=0;
-> WHILE startRows <lastRows DO
-> INSERT INTO SecondTableRows(StudentId) SELECT (Id) FROM AllRows LIMIT
startRows ,1;
-> SET startRows= startRows+1;
-> END WHILE;
-> End;
-> //
Query OK, 0 rows affected (0.22 sec)
mysql> delimiter ;
Call stored procedure using CALL command. The syntax is as follows −
CALL yourStoredProcedureName;
Call the above stored procedure to loop through all rows of the first table. The query is as follows −
mysql> call Sp_AllRowsOfATable();
Query OK, 1 row affected (0.61 sec)
After calling the stored procedure, let us check what happened with the second table. The query is as follows −
mysql> select StudentId from SecondTableRows;
+-----------+
| StudentId |
+-----------+
| 1 |
| 100 |
| 300 |
| 400 |
+-----------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1282,
"s": 1187,
"text": "To loop through all rows of a table, use stored procedure in MySQL. The syntax is as follows −"
},
{
"code": null,
"e": 1739,
"s": 1282,
"text": "delimiter //\nCREATE PROCEDURE yourProcedureName()\nBEGIN\nDECLARE anyVariableName1 INT DEFAULT 0;\nDECLARE anyVariableName2 INT DEFAULT 0;\nSELECT COUNT(*) FROM yourTableName1 INTO anyVariableName1;\nSET anyVariableName2 =0;\nWHILE anyVariableName2 < anyVariableName1 DO\n INSERT INTO yourTableName2(yourColumnName,...N) SELECT (yourColumnName1,...N)\nFROM yourTableName1 LIMIT anyVariableName2,1;\n SET anyVariableName2 = anyVariableName2+1;\nEND WHILE;\nEnd;\n//"
},
{
"code": null,
"e": 1895,
"s": 1739,
"text": "To understand the above syntax, let us create two tables i.e. one has records and the second table will have records from the loop using stored procedures."
},
{
"code": null,
"e": 1946,
"s": 1895,
"text": "The following is the query to create first table −"
},
{
"code": null,
"e": 2066,
"s": 1946,
"text": "mysql> create table AllRows\n -> (\n -> Id int,\n -> Name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.46 sec)"
},
{
"code": null,
"e": 2153,
"s": 2066,
"text": "Insert some records in the first table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2486,
"s": 2153,
"text": "mysql> insert into AllRows values(1,'John');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into AllRows values(100,'Carol');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into AllRows values(300,'Sam');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into AllRows values(400,'Mike');\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 2571,
"s": 2486,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2600,
"s": 2571,
"text": "mysql> select *from AllRows;"
},
{
"code": null,
"e": 2762,
"s": 2600,
"text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 1 | John |\n| 100 | Carol |\n| 300 | Sam |\n| 400 | Mike | \n+------+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2850,
"s": 2762,
"text": "Here is the query to create a second table. The query to create a table is as follows −"
},
{
"code": null,
"e": 2992,
"s": 2850,
"text": "mysql> create table SecondTableRows\n -> (\n -> StudentId int,\n -> StudentName varchar(100)\n -> );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 3098,
"s": 2992,
"text": "Now you can loop through all rows of a table using stored procedure. The stored procedure is as follows −"
},
{
"code": null,
"e": 3577,
"s": 3098,
"text": "mysql> delimiter //\nmysql> CREATE PROCEDURE Sp_AllRowsOfATable()\n -> BEGIN\n -> DECLARE lastRows INT DEFAULT 0;\n -> DECLARE startRows INT DEFAULT 0;\n -> SELECT COUNT(*) FROM AllRows INTO lastRows;\n -> SET startRows=0;\n -> WHILE startRows <lastRows DO\n -> INSERT INTO SecondTableRows(StudentId) SELECT (Id) FROM AllRows LIMIT\nstartRows ,1;\n -> SET startRows= startRows+1;\n -> END WHILE;\n -> End;\n -> //\nQuery OK, 0 rows affected (0.22 sec)\nmysql> delimiter ;"
},
{
"code": null,
"e": 3646,
"s": 3577,
"text": "Call stored procedure using CALL command. The syntax is as follows −"
},
{
"code": null,
"e": 3676,
"s": 3646,
"text": "CALL yourStoredProcedureName;"
},
{
"code": null,
"e": 3779,
"s": 3676,
"text": "Call the above stored procedure to loop through all rows of the first table. The query is as follows −"
},
{
"code": null,
"e": 3849,
"s": 3779,
"text": "mysql> call Sp_AllRowsOfATable();\nQuery OK, 1 row affected (0.61 sec)"
},
{
"code": null,
"e": 3961,
"s": 3849,
"text": "After calling the stored procedure, let us check what happened with the second table. The query is as follows −"
},
{
"code": null,
"e": 4007,
"s": 3961,
"text": "mysql> select StudentId from SecondTableRows;"
},
{
"code": null,
"e": 4144,
"s": 4007,
"text": "+-----------+\n| StudentId |\n+-----------+\n| 1 |\n| 100 |\n| 300 |\n| 400 |\n+-----------+\n4 rows in set (0.00 sec)"
}
] |
Scope of Variable in R | 22 Apr, 2020
In R, variables are the containers for storing data values. They are reference, or pointers, to an object in memory which means that whenever a variable is assigned to an instance, it gets mapped to that instance. A variable in R can store a vector, a group of vectors or a combination of many R objects.
Example:
# R program to demonstrate # variable assignment # Assignment using equal operatorvar1 = c(0, 1, 2, 3)print(var1) # Assignment using leftward operatorvar2 <- c("Python", "R")print(var2) # A Vector Assignmenta = c(1, 2, 3, 4)print(a)b = c("Debi", "Sandeep", "Subham", "Shiba")print(b) # A group of vectors Assignment using listc = list(a, b)print(c)
Output:
[1] 0 1 2 3
[1] "Python" "R"
[1] 1 2 3 4
[1] "Debi" "Sandeep" "Subham" "Shiba"
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"
The variable name in R has to be Alphanumeric characters with an exception of underscore(‘_’) and period(‘.’), the special characters which can be used in the variable names.
The variable name has to be started always with an alphabet.
Other special characters like(‘!’, ‘@’, ‘#’, ‘$’) are not allowed in the variable names.
Example:
# R program to demonstrate # rules for naming the variables # Correct namingb2 = 7 # Correct namingAmiya_Profession = "Student" # Correct namingAmiya.Profession = "Student" # Wrong naming2b = 7 # Wrong namingAmiya@Profession = "Student"
Above code when executed will generate an error because of the wrong naming of variables.
Error: unexpected symbol in "2b"
Execution halted
The location where we can find a variable and also access it if required is called the scope of a variable. There are mainly two types of variable scopes:
Global Variables: Global variables are those variables that exist throughout the execution of a program. It can be changed and accessed from any part of the program.
Local Variables: Local variables are those variables that exist only within a certain part of a program like a function and are released when the function call ends.
As the name suggests, Global Variables can be accessed from any part of the program.
They are available throughout the lifetime of a program.
They are declared anywhere in the program outside all of the functions or blocks.
Declaring global variables: Global variables are usually declared outside of all of the functions and blocks. They can be accessed from any portion of the program.
# R program to illustrate # usage of global variables # global variable global = 5 # global variable accessed from # within a function display = function(){ print(global)} display() # changing value of global variable global = 10 display()
Output:
[1] 5
[1] 10
In the above code, the variable ‘global‘ is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program.
Variables defined within a function or block are said to be local to those functions.
Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block.
Declaring local variables: Local variables are declared inside a block.
Example:
# R program to illustrate # usage of local variables func = function(){ # this variable is local to the # function func() and cannot be # accessed outside this function age = 18 } print(age)
Output:
Error in print(age) : object 'age' not found
The above program displays an error saying “object ‘age’ not found”. The variable age was declared within the function “func()” so it is local to that function and not visible to the portion of the program outside this function.
To correct the above error we have to display the value of variable age from the function “func()” only.
Example:
# R program to illustrate # usage of local variables func = function(){ # this variable is local to the # function func() and cannot be # accessed outside this function age = 18 print(age)} cat("Age is:\n")func()
Output:
Age is:
[1] 18
Global Variables can be accessed from anywhere in the code unlike local variables that have a scope restricted to the block of code in which they are created.
Example:
f = function() { # a is a local variable here a <-1}f() # Can't access outside the functionprint(a) # This'll give error
Output:
Error in print(a) : object 'a' not found
In the above code, we see that we are unable to access variable “a” outside the function as it’s assigned by an assignment operator(<-) that makes “a” as a local variable. To make assignments to global variables, a super assignment operator(<<-) is used.
How super assignment operator works?When using this operator within a function, it searches for the variable in the parent environment frame, if not found it keeps on searching the next level until it reaches the global environment. If the variable is still not found, it is created and assigned at the global level.
Example:
# R program to illustrate# Scope of variables outer_function = function(){ inner_function = function(){ # Note that "<<-" operator here # makes a as global variable a <<- 10 print(a) } inner_function() print(a)}outer_function() # Can access outside the functionprint(a)
Output:
[1] 10
[1] 10
[1] 10
When the statement “a <<- 10” is encountered within inner_function(), it looks for the variable “a” in the outer_function() environment. When the search fails, it searches in R_GlobalEnv. Since “a” is not defined in this global environment as well, it is created and assigned there which is now referenced and printed from within inner_function() as well as outer_function().
Picked
R-Variables
Programming Language
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "In R, variables are the containers for storing data values. They are reference, or pointers, to an object in memory which means that whenever a variable is assigned to an instance, it gets mapped to that instance. A variable in R can store a vector, a group of vectors or a combination of many R objects."
},
{
"code": null,
"e": 342,
"s": 333,
"text": "Example:"
},
{
"code": "# R program to demonstrate # variable assignment # Assignment using equal operatorvar1 = c(0, 1, 2, 3)print(var1) # Assignment using leftward operatorvar2 <- c(\"Python\", \"R\")print(var2) # A Vector Assignmenta = c(1, 2, 3, 4)print(a)b = c(\"Debi\", \"Sandeep\", \"Subham\", \"Shiba\")print(b) # A group of vectors Assignment using listc = list(a, b)print(c)",
"e": 697,
"s": 342,
"text": null
},
{
"code": null,
"e": 705,
"s": 697,
"text": "Output:"
},
{
"code": null,
"e": 865,
"s": 705,
"text": "[1] 0 1 2 3\n[1] \"Python\" \"R\" \n[1] 1 2 3 4\n[1] \"Debi\" \"Sandeep\" \"Subham\" \"Shiba\" \n[[1]]\n[1] 1 2 3 4\n\n[[2]]\n[1] \"Debi\" \"Sandeep\" \"Subham\" \"Shiba\" \n"
},
{
"code": null,
"e": 1040,
"s": 865,
"text": "The variable name in R has to be Alphanumeric characters with an exception of underscore(‘_’) and period(‘.’), the special characters which can be used in the variable names."
},
{
"code": null,
"e": 1101,
"s": 1040,
"text": "The variable name has to be started always with an alphabet."
},
{
"code": null,
"e": 1190,
"s": 1101,
"text": "Other special characters like(‘!’, ‘@’, ‘#’, ‘$’) are not allowed in the variable names."
},
{
"code": null,
"e": 1199,
"s": 1190,
"text": "Example:"
},
{
"code": "# R program to demonstrate # rules for naming the variables # Correct namingb2 = 7 # Correct namingAmiya_Profession = \"Student\" # Correct namingAmiya.Profession = \"Student\" # Wrong naming2b = 7 # Wrong namingAmiya@Profession = \"Student\" ",
"e": 1447,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1537,
"s": 1447,
"text": "Above code when executed will generate an error because of the wrong naming of variables."
},
{
"code": null,
"e": 1588,
"s": 1537,
"text": "Error: unexpected symbol in \"2b\"\nExecution halted\n"
},
{
"code": null,
"e": 1743,
"s": 1588,
"text": "The location where we can find a variable and also access it if required is called the scope of a variable. There are mainly two types of variable scopes:"
},
{
"code": null,
"e": 1909,
"s": 1743,
"text": "Global Variables: Global variables are those variables that exist throughout the execution of a program. It can be changed and accessed from any part of the program."
},
{
"code": null,
"e": 2075,
"s": 1909,
"text": "Local Variables: Local variables are those variables that exist only within a certain part of a program like a function and are released when the function call ends."
},
{
"code": null,
"e": 2160,
"s": 2075,
"text": "As the name suggests, Global Variables can be accessed from any part of the program."
},
{
"code": null,
"e": 2217,
"s": 2160,
"text": "They are available throughout the lifetime of a program."
},
{
"code": null,
"e": 2299,
"s": 2217,
"text": "They are declared anywhere in the program outside all of the functions or blocks."
},
{
"code": null,
"e": 2463,
"s": 2299,
"text": "Declaring global variables: Global variables are usually declared outside of all of the functions and blocks. They can be accessed from any portion of the program."
},
{
"code": "# R program to illustrate # usage of global variables # global variable global = 5 # global variable accessed from # within a function display = function(){ print(global)} display() # changing value of global variable global = 10 display()",
"e": 2715,
"s": 2463,
"text": null
},
{
"code": null,
"e": 2723,
"s": 2715,
"text": "Output:"
},
{
"code": null,
"e": 2737,
"s": 2723,
"text": "[1] 5\n[1] 10\n"
},
{
"code": null,
"e": 2933,
"s": 2737,
"text": "In the above code, the variable ‘global‘ is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program."
},
{
"code": null,
"e": 3019,
"s": 2933,
"text": "Variables defined within a function or block are said to be local to those functions."
},
{
"code": null,
"e": 3152,
"s": 3019,
"text": "Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block."
},
{
"code": null,
"e": 3224,
"s": 3152,
"text": "Declaring local variables: Local variables are declared inside a block."
},
{
"code": null,
"e": 3233,
"s": 3224,
"text": "Example:"
},
{
"code": "# R program to illustrate # usage of local variables func = function(){ # this variable is local to the # function func() and cannot be # accessed outside this function age = 18 } print(age)",
"e": 3441,
"s": 3233,
"text": null
},
{
"code": null,
"e": 3449,
"s": 3441,
"text": "Output:"
},
{
"code": null,
"e": 3495,
"s": 3449,
"text": "Error in print(age) : object 'age' not found\n"
},
{
"code": null,
"e": 3724,
"s": 3495,
"text": "The above program displays an error saying “object ‘age’ not found”. The variable age was declared within the function “func()” so it is local to that function and not visible to the portion of the program outside this function."
},
{
"code": null,
"e": 3829,
"s": 3724,
"text": "To correct the above error we have to display the value of variable age from the function “func()” only."
},
{
"code": null,
"e": 3838,
"s": 3829,
"text": "Example:"
},
{
"code": "# R program to illustrate # usage of local variables func = function(){ # this variable is local to the # function func() and cannot be # accessed outside this function age = 18 print(age)} cat(\"Age is:\\n\")func()",
"e": 4070,
"s": 3838,
"text": null
},
{
"code": null,
"e": 4078,
"s": 4070,
"text": "Output:"
},
{
"code": null,
"e": 4094,
"s": 4078,
"text": "Age is:\n[1] 18\n"
},
{
"code": null,
"e": 4253,
"s": 4094,
"text": "Global Variables can be accessed from anywhere in the code unlike local variables that have a scope restricted to the block of code in which they are created."
},
{
"code": null,
"e": 4262,
"s": 4253,
"text": "Example:"
},
{
"code": "f = function() { # a is a local variable here a <-1}f() # Can't access outside the functionprint(a) # This'll give error",
"e": 4388,
"s": 4262,
"text": null
},
{
"code": null,
"e": 4396,
"s": 4388,
"text": "Output:"
},
{
"code": null,
"e": 4438,
"s": 4396,
"text": "Error in print(a) : object 'a' not found\n"
},
{
"code": null,
"e": 4693,
"s": 4438,
"text": "In the above code, we see that we are unable to access variable “a” outside the function as it’s assigned by an assignment operator(<-) that makes “a” as a local variable. To make assignments to global variables, a super assignment operator(<<-) is used."
},
{
"code": null,
"e": 5010,
"s": 4693,
"text": "How super assignment operator works?When using this operator within a function, it searches for the variable in the parent environment frame, if not found it keeps on searching the next level until it reaches the global environment. If the variable is still not found, it is created and assigned at the global level."
},
{
"code": null,
"e": 5019,
"s": 5010,
"text": "Example:"
},
{
"code": "# R program to illustrate# Scope of variables outer_function = function(){ inner_function = function(){ # Note that \"<<-\" operator here # makes a as global variable a <<- 10 print(a) } inner_function() print(a)}outer_function() # Can access outside the functionprint(a)",
"e": 5307,
"s": 5019,
"text": null
},
{
"code": null,
"e": 5315,
"s": 5307,
"text": "Output:"
},
{
"code": null,
"e": 5337,
"s": 5315,
"text": "[1] 10\n[1] 10\n[1] 10\n"
},
{
"code": null,
"e": 5713,
"s": 5337,
"text": "When the statement “a <<- 10” is encountered within inner_function(), it looks for the variable “a” in the outer_function() environment. When the search fails, it searches in R_GlobalEnv. Since “a” is not defined in this global environment as well, it is created and assigned there which is now referenced and printed from within inner_function() as well as outer_function()."
},
{
"code": null,
"e": 5720,
"s": 5713,
"text": "Picked"
},
{
"code": null,
"e": 5732,
"s": 5720,
"text": "R-Variables"
},
{
"code": null,
"e": 5753,
"s": 5732,
"text": "Programming Language"
},
{
"code": null,
"e": 5764,
"s": 5753,
"text": "R Language"
},
{
"code": null,
"e": 5780,
"s": 5764,
"text": "Write From Home"
}
] |
How Can We Calculate Age Without DATEDIF Function? | 09 May, 2021
In this article, we’ll explore different ways of finding age in Excel, other than the usual way of finding age using DATEDIF function. For this we can use one of the two ways:
Using simple mathematics
Using the YEAR function
We can easily find age of a person using simple Math. All we need to do is, subtract the DOB from current date and divide it by 365.25
So, the formula would be:
= (TODAY()-date_of_birth)/365.25
Example:
In this case, the formula to calculate age would be:
=(TODAY()-A2)/365.25
With the current date of 26.04.2021, the age of above person is 16 years.
Remarks:
1. This formula returns the age in decimal form. In order to get age in integer form, we can wrap the formula in INT function. The syntax would be:
= INT((TODAY()- date_of_birth)/365.25)
2. This formula will produce wrong result if you try to find age of someone who hasn’t lived through a leap year.
YEARFRAC function in Excel returns a decimal value that represents fractional years between two dates. We can use this function to calculate age.
Syntax:
= INT(YEARFRAC(date_of_birth, TODAY()))
Example:
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Get Length of Array in Excel VBA?
How to Normalize Data in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Introduction to Excel Spreadsheet
How to make a 3 Axis Graph using Excel?
Macros in Excel
How to Extract the Last Word From a Cell in Excel? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 228,
"s": 52,
"text": "In this article, we’ll explore different ways of finding age in Excel, other than the usual way of finding age using DATEDIF function. For this we can use one of the two ways:"
},
{
"code": null,
"e": 253,
"s": 228,
"text": "Using simple mathematics"
},
{
"code": null,
"e": 277,
"s": 253,
"text": "Using the YEAR function"
},
{
"code": null,
"e": 412,
"s": 277,
"text": "We can easily find age of a person using simple Math. All we need to do is, subtract the DOB from current date and divide it by 365.25"
},
{
"code": null,
"e": 438,
"s": 412,
"text": "So, the formula would be:"
},
{
"code": null,
"e": 471,
"s": 438,
"text": "= (TODAY()-date_of_birth)/365.25"
},
{
"code": null,
"e": 480,
"s": 471,
"text": "Example:"
},
{
"code": null,
"e": 533,
"s": 480,
"text": "In this case, the formula to calculate age would be:"
},
{
"code": null,
"e": 554,
"s": 533,
"text": "=(TODAY()-A2)/365.25"
},
{
"code": null,
"e": 628,
"s": 554,
"text": "With the current date of 26.04.2021, the age of above person is 16 years."
},
{
"code": null,
"e": 637,
"s": 628,
"text": "Remarks:"
},
{
"code": null,
"e": 785,
"s": 637,
"text": "1. This formula returns the age in decimal form. In order to get age in integer form, we can wrap the formula in INT function. The syntax would be:"
},
{
"code": null,
"e": 824,
"s": 785,
"text": "= INT((TODAY()- date_of_birth)/365.25)"
},
{
"code": null,
"e": 938,
"s": 824,
"text": "2. This formula will produce wrong result if you try to find age of someone who hasn’t lived through a leap year."
},
{
"code": null,
"e": 1084,
"s": 938,
"text": "YEARFRAC function in Excel returns a decimal value that represents fractional years between two dates. We can use this function to calculate age."
},
{
"code": null,
"e": 1132,
"s": 1084,
"text": "Syntax:\n= INT(YEARFRAC(date_of_birth, TODAY()))"
},
{
"code": null,
"e": 1141,
"s": 1132,
"text": "Example:"
},
{
"code": null,
"e": 1148,
"s": 1141,
"text": "Picked"
},
{
"code": null,
"e": 1154,
"s": 1148,
"text": "Excel"
},
{
"code": null,
"e": 1252,
"s": 1154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1290,
"s": 1252,
"text": "How to Delete Blank Columns in Excel?"
},
{
"code": null,
"e": 1331,
"s": 1290,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 1363,
"s": 1331,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 1418,
"s": 1363,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 1446,
"s": 1418,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 1504,
"s": 1446,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 1538,
"s": 1504,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 1578,
"s": 1538,
"text": "How to make a 3 Axis Graph using Excel?"
},
{
"code": null,
"e": 1594,
"s": 1578,
"text": "Macros in Excel"
}
] |
Drop login in SQL Server | 18 Aug, 2020
The DROP LOGIN statement could be used to delete an user or login that used to connect to a SQL Server instance.
Syntax –
DROP LOGIN loginname;
GO
Permissions :The user which is deleting the login must have ALTER ANY LOGIN permission on the server.
Note –A login which is currently logged into SQL Server cannot be dropped.
If you try to drop login which is currently using SQL Server, the DROP LOGIN statement will raise below error.
Drop failed for Login “loginname”
Let us assume, we have created below login:
CREATE LOGIN geeks
WITH PASSWORD = ‘gEe@kF0rG##ks’;
Below example shows how to use DROP LOGIN statement in SQL Server.
Example –
DROP LOGIN geeks;
DROP LOGIN used in above example would delete the login called geeks from SQL server. This DROP LOGIN statement will only run if geeks is not the current user.
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "The DROP LOGIN statement could be used to delete an user or login that used to connect to a SQL Server instance."
},
{
"code": null,
"e": 150,
"s": 141,
"text": "Syntax –"
},
{
"code": null,
"e": 176,
"s": 150,
"text": "DROP LOGIN loginname;\nGO "
},
{
"code": null,
"e": 278,
"s": 176,
"text": "Permissions :The user which is deleting the login must have ALTER ANY LOGIN permission on the server."
},
{
"code": null,
"e": 353,
"s": 278,
"text": "Note –A login which is currently logged into SQL Server cannot be dropped."
},
{
"code": null,
"e": 464,
"s": 353,
"text": "If you try to drop login which is currently using SQL Server, the DROP LOGIN statement will raise below error."
},
{
"code": null,
"e": 498,
"s": 464,
"text": "Drop failed for Login “loginname”"
},
{
"code": null,
"e": 542,
"s": 498,
"text": "Let us assume, we have created below login:"
},
{
"code": null,
"e": 597,
"s": 542,
"text": "CREATE LOGIN geeks \nWITH PASSWORD = ‘gEe@kF0rG##ks’; "
},
{
"code": null,
"e": 664,
"s": 597,
"text": "Below example shows how to use DROP LOGIN statement in SQL Server."
},
{
"code": null,
"e": 674,
"s": 664,
"text": "Example –"
},
{
"code": null,
"e": 693,
"s": 674,
"text": "DROP LOGIN geeks; "
},
{
"code": null,
"e": 853,
"s": 693,
"text": "DROP LOGIN used in above example would delete the login called geeks from SQL server. This DROP LOGIN statement will only run if geeks is not the current user."
},
{
"code": null,
"e": 864,
"s": 853,
"text": "SQL-Server"
},
{
"code": null,
"e": 868,
"s": 864,
"text": "SQL"
},
{
"code": null,
"e": 872,
"s": 868,
"text": "SQL"
}
] |
What is MIPS(Million of Instructions Per Second)? | 07 Jul, 2022
It may be a strategy for measuring the raw speed of a computer’s processor. Since the MIPS estimation doesn’t take into consideration other components such as the computer’s I/O speed or processor engineering, it isn’t continuously a reasonable way to degree the execution of a computer. For this case, a computer evaluated at 100 MIPS may be able to compute certain capacities quicker than another computer evaluated at 120 MIPS.
The MIPS estimation has been utilized by computer producers like IBM to degree the “cost of computing.” The value of computers is decided in MIPS per dollar. Interests, the esteem of computers in MIPS per dollar has consistently multiplied on a yearly premise for a final couple of decades.
Required inputs for calculating MIPS are the
Number of instructions per second can be performed by a processor
CPU processor speed (cycles per second), Ex (1 GHz, 2 GHz).
CPI (average clock cycles per instruction).
Execution time.
Step 1: Perform the Divide operation between no. of instructions and Execution time and store the value (Let X) in a variable.
Step 2: Perform the Divide operation between that variable (X) and 1 million for finding millions of instructions per second. Example:
if a computer completed 2 million instructions in 0.10 seconds .
X = 2 million/0.10 = 20 million.
No of MISP = X/1 million (as the name tells about it)
No of MISP=20 million/1 million =20.
Step 1: Perform the Divide operation between the number of cycles per second (CPU) and the number of cycles per instruction (CPI) and store the value (X) in a variable.
Step 2: Perform a Divide operation between that variable and 1 million for finding millions of instructions per second. Example:
If a computer with a CPU of 400 megahertz had a CPI of 2.
X = 400/2=200
No of MISP=X/1 million
No of MISP = 0.0002
Advantages of MIPS:
It is easy to understand and measure
It helps in the calculation of CPU processor speed (cycles per second), CPI (average clock cycles per instruction) and Execution time.
It handles when the amount of work is large.
Disadvantages of MIPS:
It may not reflect real execution, since simple instructions do way better.
It is an older, obsolete measure of a computer’s speed and power.
rakeshdhariwal61
Picked
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 460,
"s": 28,
"text": "It may be a strategy for measuring the raw speed of a computer’s processor. Since the MIPS estimation doesn’t take into consideration other components such as the computer’s I/O speed or processor engineering, it isn’t continuously a reasonable way to degree the execution of a computer. For this case, a computer evaluated at 100 MIPS may be able to compute certain capacities quicker than another computer evaluated at 120 MIPS. "
},
{
"code": null,
"e": 751,
"s": 460,
"text": "The MIPS estimation has been utilized by computer producers like IBM to degree the “cost of computing.” The value of computers is decided in MIPS per dollar. Interests, the esteem of computers in MIPS per dollar has consistently multiplied on a yearly premise for a final couple of decades."
},
{
"code": null,
"e": 796,
"s": 751,
"text": "Required inputs for calculating MIPS are the"
},
{
"code": null,
"e": 864,
"s": 796,
"text": " Number of instructions per second can be performed by a processor "
},
{
"code": null,
"e": 925,
"s": 864,
"text": " CPU processor speed (cycles per second), Ex (1 GHz, 2 GHz)."
},
{
"code": null,
"e": 970,
"s": 925,
"text": " CPI (average clock cycles per instruction)."
},
{
"code": null,
"e": 988,
"s": 970,
"text": " Execution time. "
},
{
"code": null,
"e": 1117,
"s": 988,
"text": "Step 1: Perform the Divide operation between no. of instructions and Execution time and store the value (Let X) in a variable. "
},
{
"code": null,
"e": 1252,
"s": 1117,
"text": "Step 2: Perform the Divide operation between that variable (X) and 1 million for finding millions of instructions per second. Example:"
},
{
"code": null,
"e": 1442,
"s": 1252,
"text": "if a computer completed 2 million instructions in 0.10 seconds .\nX = 2 million/0.10 = 20 million. \nNo of MISP = X/1 million (as the name tells about it)\nNo of MISP=20 million/1 million =20."
},
{
"code": null,
"e": 1612,
"s": 1442,
"text": "Step 1: Perform the Divide operation between the number of cycles per second (CPU) and the number of cycles per instruction (CPI) and store the value (X) in a variable. "
},
{
"code": null,
"e": 1741,
"s": 1612,
"text": "Step 2: Perform a Divide operation between that variable and 1 million for finding millions of instructions per second. Example:"
},
{
"code": null,
"e": 1859,
"s": 1741,
"text": "If a computer with a CPU of 400 megahertz had a CPI of 2.\nX = 400/2=200 \nNo of MISP=X/1 million\nNo of MISP = 0.0002"
},
{
"code": null,
"e": 1879,
"s": 1859,
"text": "Advantages of MIPS:"
},
{
"code": null,
"e": 1916,
"s": 1879,
"text": "It is easy to understand and measure"
},
{
"code": null,
"e": 2051,
"s": 1916,
"text": "It helps in the calculation of CPU processor speed (cycles per second), CPI (average clock cycles per instruction) and Execution time."
},
{
"code": null,
"e": 2096,
"s": 2051,
"text": "It handles when the amount of work is large."
},
{
"code": null,
"e": 2119,
"s": 2096,
"text": "Disadvantages of MIPS:"
},
{
"code": null,
"e": 2195,
"s": 2119,
"text": "It may not reflect real execution, since simple instructions do way better."
},
{
"code": null,
"e": 2261,
"s": 2195,
"text": "It is an older, obsolete measure of a computer’s speed and power."
},
{
"code": null,
"e": 2278,
"s": 2261,
"text": "rakeshdhariwal61"
},
{
"code": null,
"e": 2285,
"s": 2278,
"text": "Picked"
},
{
"code": null,
"e": 2303,
"s": 2285,
"text": "Operating Systems"
},
{
"code": null,
"e": 2321,
"s": 2303,
"text": "Operating Systems"
}
] |
Python – Least Frequent Character in String | 30 Jun, 2022
This article gives us the methods to find the frequency of minimum occurring character in a python string. This is quite important utility nowadays and knowledge of it is always useful. Let’s discuss certain ways in which this task can be performed.
Method 1 : Naive method + min()
In this method, we simply iterate through the string and form a key in a dictionary of newly occurred element or if element is already occurred, we increase its value by 1. We find minimum occurring character by using min() on values.
Python3
# Python 3 code to demonstrate# Least Frequent Character in String# naive method # initializing stringtest_str = "GeeksforGeeks" # printing original stringprint ("The original string is : " + test_str) # using naive method to get# Least Frequent Character in Stringall_freq = {}for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1res = min(all_freq, key = all_freq.get) # printing resultprint ("The minimum of all characters in GeeksforGeeks is : " + str(res))
The original string is : GeeksforGeeks
The minimum of all characters in GeeksforGeeks is : f
Method 2 : Using collections.Counter() + min()
The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required. We find minimum occurring character by using min() on values.
Python3
# Python 3 code to demonstrate# Least Frequent Character in String# collections.Counter() + min()from collections import Counter # initializing stringtest_str = "GeeksforGeeks" # printing original stringprint ("The original string is : " + test_str) # using collections.Counter() + min() to get# Least Frequent Character in Stringres = Counter(test_str)res = min(res, key = res.get) # printing resultprint ("The minimum of all characters in GeeksforGeeks is : " + str(res))
The original string is : GeeksforGeeks
The minimum of all characters in GeeksforGeeks is : f
nidhi_biet
vinayedula
Python string-programs
Python
Python Programs
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 303,
"s": 52,
"text": "This article gives us the methods to find the frequency of minimum occurring character in a python string. This is quite important utility nowadays and knowledge of it is always useful. Let’s discuss certain ways in which this task can be performed. "
},
{
"code": null,
"e": 336,
"s": 303,
"text": "Method 1 : Naive method + min() "
},
{
"code": null,
"e": 572,
"s": 336,
"text": "In this method, we simply iterate through the string and form a key in a dictionary of newly occurred element or if element is already occurred, we increase its value by 1. We find minimum occurring character by using min() on values. "
},
{
"code": null,
"e": 580,
"s": 572,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# Least Frequent Character in String# naive method # initializing stringtest_str = \"GeeksforGeeks\" # printing original stringprint (\"The original string is : \" + test_str) # using naive method to get# Least Frequent Character in Stringall_freq = {}for i in test_str: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1res = min(all_freq, key = all_freq.get) # printing resultprint (\"The minimum of all characters in GeeksforGeeks is : \" + str(res))",
"e": 1084,
"s": 580,
"text": null
},
{
"code": null,
"e": 1177,
"s": 1084,
"text": "The original string is : GeeksforGeeks\nThe minimum of all characters in GeeksforGeeks is : f"
},
{
"code": null,
"e": 1226,
"s": 1177,
"text": " Method 2 : Using collections.Counter() + min() "
},
{
"code": null,
"e": 1485,
"s": 1226,
"text": "The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required. We find minimum occurring character by using min() on values. "
},
{
"code": null,
"e": 1493,
"s": 1485,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# Least Frequent Character in String# collections.Counter() + min()from collections import Counter # initializing stringtest_str = \"GeeksforGeeks\" # printing original stringprint (\"The original string is : \" + test_str) # using collections.Counter() + min() to get# Least Frequent Character in Stringres = Counter(test_str)res = min(res, key = res.get) # printing resultprint (\"The minimum of all characters in GeeksforGeeks is : \" + str(res))",
"e": 1967,
"s": 1493,
"text": null
},
{
"code": null,
"e": 2060,
"s": 1967,
"text": "The original string is : GeeksforGeeks\nThe minimum of all characters in GeeksforGeeks is : f"
},
{
"code": null,
"e": 2071,
"s": 2060,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2082,
"s": 2071,
"text": "vinayedula"
},
{
"code": null,
"e": 2105,
"s": 2082,
"text": "Python string-programs"
},
{
"code": null,
"e": 2112,
"s": 2105,
"text": "Python"
},
{
"code": null,
"e": 2128,
"s": 2112,
"text": "Python Programs"
},
{
"code": null,
"e": 2226,
"s": 2128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2258,
"s": 2226,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2285,
"s": 2258,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2306,
"s": 2285,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2329,
"s": 2306,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2360,
"s": 2329,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2382,
"s": 2360,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2421,
"s": 2382,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2459,
"s": 2421,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2508,
"s": 2459,
"text": "Python | Convert string dictionary to dictionary"
}
] |
std::string::insert() in C++ | 10 Sep, 2018
insert() is used to insert characters in string at specified position. It supports various syntaxes to facilitate same, here we will describe them.
Syntax 1: Inserts the characters of str starting from index idx.
string& string::insert (size_type idx, const string& str)
idx :is the index number
str : is the string from which characters is to be picked to insert
Returns *this.
Errors:
Throws out_of_range if idx > size().
Throws length_error if the resulting size exceeds the maximum number of characters.
// CPP code for insert (size_type idx, const string& str) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str1, string str2){ // Inserts str2 in str1 starting // from 6th index of str1 str1.insert(6, str2); cout << "Using insert : "; cout << str1;} // Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks "); cout << "Original String : " << str1 << endl; insertDemo(str1, str2); return 0;}
Output:
Original String : Hello World!
Using insert : Hello GeeksforGeeks World!
Syntax 2: Inserts at most, str_num characters of str, starting with index str_idx.
string& string::insert (size_type idx, const string& str, size_type str_idx,
size_type str_num)
idx : is the index number where insertion is to be made.
str : is the string from which characters are to be picked to insert.
str_idx : is the index number in str.
str_num : is the number of characters to be inserted from str.
Returns *this.
Errors:
Throws out_of_range if idx > size().
Throws out_of_range if str_idx > str.size().
Throws length_error if the resulting size exceeds the maximum number of characters.
// CPP code for insert (size_type idx, const string& str, // size_type str_idx, size_type str_num) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str1, string str2){ // Inserts 6 characters from index number // 8 of str2 at index number 6 of str1 str1.insert(6, str2, 8, 6); cout << "Using insert : "; cout << str1;} // Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks "); cout << "Original String : " << str1 << endl; insertDemo(str1, str2); return 0;}
Output:
Original String : Hello World!
Using insert : Hello Geeks World!
Syntax 3: Inserts the characters of the C-string cstr so that the new characters start with index idx.
string& string::insert (size_ type idx, const char* cstr)
idx : is the index number where insertion is to be made.
*cstr : is the pointer to the C-string which is to be inserted.
Returns *this.
Errors:
Throws out_of_range if idx > size().
Throws length_error if the resulting size exceeds the maximum number of characters.
Note: cstr may not be a null pointer (NULL).
// CPP code for insert(size_ type idx, const char* cstr) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts " are " at 5th index of str str.insert(5, " are "); cout << "Using insert : "; cout << str;} // Driver codeint main(){ string str("GeeksforGeeks "); cout << "Original String : " << str << endl; insertDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
Using insert : Geeks are forGeeks
Syntax 4: Inserts chars_len characters of the character array chars so that the new characters start with index idx.
string& string::insert (size_type idx, const char* chars, size_type chars_len)
idx : index number where insertion is to be made.
*chars : is the pointer to the array.
chars_len : is the number of characters to be inserted from character array.
Returns : *this
Errors:
Throws out_of_range if idx > size().
Throws length_error if the resulting size exceeds the maximum number of characters.
Note : chars must have at least chars_len characters.
// CPP code for insert (size_type idx, const char* chars, // size_type chars_len) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts 10 characters from" are here " // at 5th index of str str.insert(5, " are here ", 10); cout << "Using insert : "; cout << str;} // Driver codeint main(){ string str("GeeksforGeeks "); cout << "Original String : " << str << endl; insertDemo(str); return 0;}
Output:
Original String : GeeksforGeeks
Using insert : Geeks are here forGeeks
Syntax 5: Inserts num occurrences of character c at the position specified by idx.
string& string ::insert (size_type idx, size_type num, char c)
idx : is the index number where insertion is to be made.
c : is the character to be inserted.
num : is the number of repetition of character c
Returns : *this
Errors:
Throw out_of_range if idx > size().
Throw length_error if the resulting size exceeds the maximum number of characters.
// CPP code for :insert (size_type idx, size_type num, char c) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts at 5th index, // 5 occurrences of '$' str.insert(5, 5, '$'); cout << "Using insert : "; cout << str;} // Driver codeint main(){ string str("**********"); cout << "Original String : " << str << endl; insertDemo(str); return 0;}
Output:
Original String : **********
Using insert : *****$$$$$*****
Syntax 6: Inserts num occurrences of character c at the position specified by iterator pos.
void string ::insert (iterator pos, size_type num, char c)
pos : is the position of iterator.
c : is the character which is to be inserted.
Returns : *this
Errors:
Throws out_of_range if pos > size().
Throws length_error if the resulting size exceeds the maximum number of characters.
// CPP code for :insert (iterator pos, size_type num, char c)#include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts 5 occurrences of '$' // at position str.begin() + 5 str.insert(str.begin() + 5, 5, '$'); cout << "Using insert : "; cout << str;} // Driver codeint main(){ string str("**********"); cout << "Original String : " << str << endl; insertDemo(str); return 0;}
Output:
Original String : **********
Using insert : *****$$$$$*****
Syntax 7: Inserts a copy of character c before the character to which iterator pos refers.
iterator string ::insert (iterator pos, char c )
pos : is the position of iterator.
c : is the character which is to be inserted.
Returns : iterator pointing to the first character inserted.
Error:
Throws length_error if the resulting size exceeds the maximum number of characters.
// CPP code for :insert (iterator pos, char c )#include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ std::string::iterator pos; // Inserts '$' at position // str.begin() + 5 pos = str.insert(str.begin()+5,'$'); cout << "Using insert : "; cout << str << endl; cout << "Value at Iterator returned : " << *pos; } // Driver codeint main(){ string str("**********"); cout << "Original String : " << str << endl; insertDemo(str); return 0;}
Output:
Original String : **********
Using insert : *****$*****
Value at Iterator returned : $
Syntax 8: Inserts all characters of the range [ beg,end ) before the character to which iterator pos refers.
void string ::insert (iterator pos, InputIterator beg, InputIterator end )
pos : is the iterator position.
beg, end : Input iterators to the initial and final positions in a sequence.
Error:
Throws length_error if the resulting size exceeds the maximum number of characters.
// CPP code for insertinsert (iterator pos, InputIterator beg,// InputIterator end ) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str1, string str2){ // Inserts str2.begin() + 5 , str2.end() - 6 // at position str1.begin() + 6 str1.insert(str1.begin() + 6, str2.begin() + 5 , str2.end() - 6); cout << "Using insert : "; cout << str1;} // Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks "); cout << "Original String : " << str1 << endl; insertDemo(str1, str2); return 0;}
Output:
Original String : Hello World!
Using insert : Hello forWorld!
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) 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.
Lavish Saluja
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Object Oriented Programming in C++
Inheritance in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Sep, 2018"
},
{
"code": null,
"e": 200,
"s": 52,
"text": "insert() is used to insert characters in string at specified position. It supports various syntaxes to facilitate same, here we will describe them."
},
{
"code": null,
"e": 265,
"s": 200,
"text": "Syntax 1: Inserts the characters of str starting from index idx."
},
{
"code": null,
"e": 563,
"s": 265,
"text": "string& string::insert (size_type idx, const string& str)\nidx :is the index number\nstr : is the string from which characters is to be picked to insert \nReturns *this.\nErrors: \nThrows out_of_range if idx > size().\nThrows length_error if the resulting size exceeds the maximum number of characters.\n"
},
{
"code": "// CPP code for insert (size_type idx, const string& str) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str1, string str2){ // Inserts str2 in str1 starting // from 6th index of str1 str1.insert(6, str2); cout << \"Using insert : \"; cout << str1;} // Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks \"); cout << \"Original String : \" << str1 << endl; insertDemo(str1, str2); return 0;}",
"e": 1092,
"s": 563,
"text": null
},
{
"code": null,
"e": 1100,
"s": 1092,
"text": "Output:"
},
{
"code": null,
"e": 1176,
"s": 1100,
"text": "Original String : Hello World! \nUsing insert : Hello GeeksforGeeks World! \n"
},
{
"code": null,
"e": 1259,
"s": 1176,
"text": "Syntax 2: Inserts at most, str_num characters of str, starting with index str_idx."
},
{
"code": null,
"e": 1833,
"s": 1259,
"text": "string& string::insert (size_type idx, const string& str, size_type str_idx,\n size_type str_num)\nidx : is the index number where insertion is to be made.\nstr : is the string from which characters are to be picked to insert.\nstr_idx : is the index number in str.\nstr_num : is the number of characters to be inserted from str.\nReturns *this.\nErrors: \nThrows out_of_range if idx > size().\nThrows out_of_range if str_idx > str.size().\nThrows length_error if the resulting size exceeds the maximum number of characters.\n"
},
{
"code": "// CPP code for insert (size_type idx, const string& str, // size_type str_idx, size_type str_num) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str1, string str2){ // Inserts 6 characters from index number // 8 of str2 at index number 6 of str1 str1.insert(6, str2, 8, 6); cout << \"Using insert : \"; cout << str1;} // Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks \"); cout << \"Original String : \" << str1 << endl; insertDemo(str1, str2); return 0;}",
"e": 2431,
"s": 1833,
"text": null
},
{
"code": null,
"e": 2439,
"s": 2431,
"text": "Output:"
},
{
"code": null,
"e": 2507,
"s": 2439,
"text": "Original String : Hello World! \nUsing insert : Hello Geeks World! \n"
},
{
"code": null,
"e": 2610,
"s": 2507,
"text": "Syntax 3: Inserts the characters of the C-string cstr so that the new characters start with index idx."
},
{
"code": null,
"e": 2935,
"s": 2610,
"text": "string& string::insert (size_ type idx, const char* cstr)\nidx : is the index number where insertion is to be made.\n*cstr : is the pointer to the C-string which is to be inserted.\nReturns *this.\nErrors: \nThrows out_of_range if idx > size().\nThrows length_error if the resulting size exceeds the maximum number of characters.\n"
},
{
"code": null,
"e": 2980,
"s": 2935,
"text": "Note: cstr may not be a null pointer (NULL)."
},
{
"code": "// CPP code for insert(size_ type idx, const char* cstr) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts \" are \" at 5th index of str str.insert(5, \" are \"); cout << \"Using insert : \"; cout << str;} // Driver codeint main(){ string str(\"GeeksforGeeks \"); cout << \"Original String : \" << str << endl; insertDemo(str); return 0;}",
"e": 3429,
"s": 2980,
"text": null
},
{
"code": null,
"e": 3437,
"s": 3429,
"text": "Output:"
},
{
"code": null,
"e": 3506,
"s": 3437,
"text": "Original String : GeeksforGeeks \nUsing insert : Geeks are forGeeks \n"
},
{
"code": null,
"e": 3623,
"s": 3506,
"text": "Syntax 4: Inserts chars_len characters of the character array chars so that the new characters start with index idx."
},
{
"code": null,
"e": 4014,
"s": 3623,
"text": "string& string::insert (size_type idx, const char* chars, size_type chars_len)\nidx : index number where insertion is to be made.\n*chars : is the pointer to the array.\nchars_len : is the number of characters to be inserted from character array.\nReturns : *this\nErrors: \nThrows out_of_range if idx > size().\nThrows length_error if the resulting size exceeds the maximum number of characters.\n"
},
{
"code": null,
"e": 4068,
"s": 4014,
"text": "Note : chars must have at least chars_len characters."
},
{
"code": "// CPP code for insert (size_type idx, const char* chars, // size_type chars_len) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts 10 characters from\" are here \" // at 5th index of str str.insert(5, \" are here \", 10); cout << \"Using insert : \"; cout << str;} // Driver codeint main(){ string str(\"GeeksforGeeks \"); cout << \"Original String : \" << str << endl; insertDemo(str); return 0;}",
"e": 4580,
"s": 4068,
"text": null
},
{
"code": null,
"e": 4588,
"s": 4580,
"text": "Output:"
},
{
"code": null,
"e": 4662,
"s": 4588,
"text": "Original String : GeeksforGeeks \nUsing insert : Geeks are here forGeeks \n"
},
{
"code": null,
"e": 4745,
"s": 4662,
"text": "Syntax 5: Inserts num occurrences of character c at the position specified by idx."
},
{
"code": null,
"e": 5095,
"s": 4745,
"text": "string& string ::insert (size_type idx, size_type num, char c)\nidx : is the index number where insertion is to be made.\nc : is the character to be inserted.\nnum : is the number of repetition of character c\nReturns : *this\nErrors: \nThrow out_of_range if idx > size().\nThrow length_error if the resulting size exceeds the maximum number of characters."
},
{
"code": "// CPP code for :insert (size_type idx, size_type num, char c) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts at 5th index, // 5 occurrences of '$' str.insert(5, 5, '$'); cout << \"Using insert : \"; cout << str;} // Driver codeint main(){ string str(\"**********\"); cout << \"Original String : \" << str << endl; insertDemo(str); return 0;}",
"e": 5558,
"s": 5095,
"text": null
},
{
"code": null,
"e": 5566,
"s": 5558,
"text": "Output:"
},
{
"code": null,
"e": 5627,
"s": 5566,
"text": "Original String : **********\nUsing insert : *****$$$$$*****\n"
},
{
"code": null,
"e": 5719,
"s": 5627,
"text": "Syntax 6: Inserts num occurrences of character c at the position specified by iterator pos."
},
{
"code": null,
"e": 6006,
"s": 5719,
"text": "void string ::insert (iterator pos, size_type num, char c)\npos : is the position of iterator.\nc : is the character which is to be inserted.\nReturns : *this\nErrors: \nThrows out_of_range if pos > size().\nThrows length_error if the resulting size exceeds the maximum number of characters.\n"
},
{
"code": "// CPP code for :insert (iterator pos, size_type num, char c)#include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ // Inserts 5 occurrences of '$' // at position str.begin() + 5 str.insert(str.begin() + 5, 5, '$'); cout << \"Using insert : \"; cout << str;} // Driver codeint main(){ string str(\"**********\"); cout << \"Original String : \" << str << endl; insertDemo(str); return 0;}",
"e": 6493,
"s": 6006,
"text": null
},
{
"code": null,
"e": 6501,
"s": 6493,
"text": "Output:"
},
{
"code": null,
"e": 6562,
"s": 6501,
"text": "Original String : **********\nUsing insert : *****$$$$$*****\n"
},
{
"code": null,
"e": 6653,
"s": 6562,
"text": "Syntax 7: Inserts a copy of character c before the character to which iterator pos refers."
},
{
"code": null,
"e": 6938,
"s": 6653,
"text": "iterator string ::insert (iterator pos, char c )\npos : is the position of iterator.\nc : is the character which is to be inserted.\nReturns : iterator pointing to the first character inserted.\nError: \nThrows length_error if the resulting size exceeds the maximum number of characters.\n"
},
{
"code": "// CPP code for :insert (iterator pos, char c )#include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str){ std::string::iterator pos; // Inserts '$' at position // str.begin() + 5 pos = str.insert(str.begin()+5,'$'); cout << \"Using insert : \"; cout << str << endl; cout << \"Value at Iterator returned : \" << *pos; } // Driver codeint main(){ string str(\"**********\"); cout << \"Original String : \" << str << endl; insertDemo(str); return 0;}",
"e": 7491,
"s": 6938,
"text": null
},
{
"code": null,
"e": 7499,
"s": 7491,
"text": "Output:"
},
{
"code": null,
"e": 7587,
"s": 7499,
"text": "Original String : **********\nUsing insert : *****$*****\nValue at Iterator returned : $\n"
},
{
"code": null,
"e": 7696,
"s": 7587,
"text": "Syntax 8: Inserts all characters of the range [ beg,end ) before the character to which iterator pos refers."
},
{
"code": null,
"e": 7973,
"s": 7696,
"text": "void string ::insert (iterator pos, InputIterator beg, InputIterator end )\npos : is the iterator position.\nbeg, end : Input iterators to the initial and final positions in a sequence.\nError: \nThrows length_error if the resulting size exceeds the maximum number of characters.\n"
},
{
"code": "// CPP code for insertinsert (iterator pos, InputIterator beg,// InputIterator end ) #include <iostream>#include <string> using namespace std; // Function to demonstrate insertvoid insertDemo(string str1, string str2){ // Inserts str2.begin() + 5 , str2.end() - 6 // at position str1.begin() + 6 str1.insert(str1.begin() + 6, str2.begin() + 5 , str2.end() - 6); cout << \"Using insert : \"; cout << str1;} // Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks \"); cout << \"Original String : \" << str1 << endl; insertDemo(str1, str2); return 0;}",
"e": 8593,
"s": 7973,
"text": null
},
{
"code": null,
"e": 8601,
"s": 8593,
"text": "Output:"
},
{
"code": null,
"e": 8666,
"s": 8601,
"text": "Original String : Hello World! \nUsing insert : Hello forWorld! \n"
},
{
"code": null,
"e": 8984,
"s": 8666,
"text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) 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": 9109,
"s": 8984,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9123,
"s": 9109,
"text": "Lavish Saluja"
},
{
"code": null,
"e": 9143,
"s": 9123,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 9147,
"s": 9143,
"text": "STL"
},
{
"code": null,
"e": 9151,
"s": 9147,
"text": "C++"
},
{
"code": null,
"e": 9155,
"s": 9151,
"text": "STL"
},
{
"code": null,
"e": 9159,
"s": 9155,
"text": "CPP"
},
{
"code": null,
"e": 9257,
"s": 9159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9284,
"s": 9257,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 9338,
"s": 9284,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9381,
"s": 9338,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9415,
"s": 9381,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 9440,
"s": 9415,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 9457,
"s": 9440,
"text": "Substring in C++"
},
{
"code": null,
"e": 9492,
"s": 9457,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 9511,
"s": 9492,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 9551,
"s": 9511,
"text": "The C++ Standard Template Library (STL)"
}
] |
Python | Get unique values from a list | 08 Jul, 2022
Given a list, print all the unique numbers in any order.
Examples:
Input : 10 20 10 30 40 40
Output : 10 20 30 40
Input : 1 2 1 1 3 4 3 3 5
Output : 1 2 3 4 5
Method 1 : Traversal of list
Using traversal, we can traverse for every element in the list and check if the element is in the unique_list already if it is not over there, then we can append it in the unique_list. This is done using one for loop and other if statement which check if the value is in the unique list or not which is equivalent to another for loop.
Python
# Python program to check if two # to get unique values from list# using traversal # function to get unique valuesdef unique(list1): # initialize a null list unique_list = [] # traverse for all elements for x in list1: # check if exists in unique_list or not if x not in unique_list: unique_list.append(x) # print list for x in unique_list: print x, # driver codelist1 = [10, 20, 10, 30, 40, 40]print("the unique values from 1st list is")unique(list1) list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]print("\nthe unique values from 2nd list is")unique(list2)
Output:
the unique values from 1st list is
10 20 30 40
the unique values from 2nd list is
1 2 3 4 5
Method 2 : Using Set
Using set() property of Python, we can easily check for the unique values. Insert the values of the list in a set. Set only stores a value once even if it is inserted more than once. After inserting all the values in the set by list_set=set(list1), convert this set to a list to print it.
Python
# Python program to check if two # to get unique values from list# using set # function to get unique valuesdef unique(list1): # insert the list to the set list_set = set(list1) # convert the set to the list unique_list = (list(list_set)) for x in unique_list: print x, # driver codelist1 = [10, 20, 10, 30, 40, 40]print("the unique values from 1st list is")unique(list1) list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]print("\nthe unique values from 2nd list is")unique(list2)
Output:
the unique values from 1st list is
40 10 20 30
the unique values from 2nd list is
1 2 3 4 5
Method 3 : Using numpy.unique
Using Python’s import numpy, the unique elements in the array are also obtained. In first step convert the list to x=numpy.array(list) and then use numpy.unique(x) function to get the unique values from the list. numpy.unique() returns only the unique values in the list.
Python3
#Python program to check if two # to get unique values from list# using numpy.unique import numpy as np # function to get unique valuesdef unique(list1): x = np.array(list1) print(np.unique(x)) # driver codelist1 = [10, 20, 10, 30, 40, 40]print("the unique values from 1st list is")unique(list1) list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]print("\nthe unique values from 2nd list is")unique(list2)
Output
the unique values from 1st list is
[10 20 30 40]
the unique values from 2nd list is
[1 2 3 4 5]
Method #4: Using collections.Counter()
Using python import Counter() from collections print all the keys of Counter elements or we print directly by using “*” symbol.
Below is the implementation of above approach.
Python3
# Python program to check if two# to get unique values from list# importing counter from collectionsfrom collections import Counter # Function to get unique valuesdef unique(list1): # Print directly by using * symbol print(*Counter(list1)) # driver codelist1 = [10, 20, 10, 30, 40, 40]print("the unique values from 1st list is")unique(list1) list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]print("\nthe unique values from 2nd list is")unique(list2) # This code is contributed by vikkycirus
Output:
the unique values from 1st list is
10 20 30 40
the unique values from 2nd list is
1 2 3 4 5
vikkycirus
gabaa406
kk773572498
simmytarika5
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 109,
"s": 52,
"text": "Given a list, print all the unique numbers in any order."
},
{
"code": null,
"e": 120,
"s": 109,
"text": "Examples: "
},
{
"code": null,
"e": 217,
"s": 120,
"text": "Input : 10 20 10 30 40 40\nOutput : 10 20 30 40 \n\nInput : 1 2 1 1 3 4 3 3 5 \nOutput : 1 2 3 4 5 "
},
{
"code": null,
"e": 246,
"s": 217,
"text": "Method 1 : Traversal of list"
},
{
"code": null,
"e": 583,
"s": 246,
"text": "Using traversal, we can traverse for every element in the list and check if the element is in the unique_list already if it is not over there, then we can append it in the unique_list. This is done using one for loop and other if statement which check if the value is in the unique list or not which is equivalent to another for loop. "
},
{
"code": null,
"e": 590,
"s": 583,
"text": "Python"
},
{
"code": "# Python program to check if two # to get unique values from list# using traversal # function to get unique valuesdef unique(list1): # initialize a null list unique_list = [] # traverse for all elements for x in list1: # check if exists in unique_list or not if x not in unique_list: unique_list.append(x) # print list for x in unique_list: print x, # driver codelist1 = [10, 20, 10, 30, 40, 40]print(\"the unique values from 1st list is\")unique(list1) list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]print(\"\\nthe unique values from 2nd list is\")unique(list2)",
"e": 1209,
"s": 590,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1209,
"text": "Output: "
},
{
"code": null,
"e": 1311,
"s": 1218,
"text": "the unique values from 1st list is\n10 20 30 40 \nthe unique values from 2nd list is\n1 2 3 4 5"
},
{
"code": null,
"e": 1332,
"s": 1311,
"text": "Method 2 : Using Set"
},
{
"code": null,
"e": 1622,
"s": 1332,
"text": "Using set() property of Python, we can easily check for the unique values. Insert the values of the list in a set. Set only stores a value once even if it is inserted more than once. After inserting all the values in the set by list_set=set(list1), convert this set to a list to print it. "
},
{
"code": null,
"e": 1629,
"s": 1622,
"text": "Python"
},
{
"code": "# Python program to check if two # to get unique values from list# using set # function to get unique valuesdef unique(list1): # insert the list to the set list_set = set(list1) # convert the set to the list unique_list = (list(list_set)) for x in unique_list: print x, # driver codelist1 = [10, 20, 10, 30, 40, 40]print(\"the unique values from 1st list is\")unique(list1) list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]print(\"\\nthe unique values from 2nd list is\")unique(list2)",
"e": 2134,
"s": 1629,
"text": null
},
{
"code": null,
"e": 2143,
"s": 2134,
"text": "Output: "
},
{
"code": null,
"e": 2236,
"s": 2143,
"text": "the unique values from 1st list is\n40 10 20 30 \nthe unique values from 2nd list is\n1 2 3 4 5"
},
{
"code": null,
"e": 2266,
"s": 2236,
"text": "Method 3 : Using numpy.unique"
},
{
"code": null,
"e": 2539,
"s": 2266,
"text": "Using Python’s import numpy, the unique elements in the array are also obtained. In first step convert the list to x=numpy.array(list) and then use numpy.unique(x) function to get the unique values from the list. numpy.unique() returns only the unique values in the list. "
},
{
"code": null,
"e": 2547,
"s": 2539,
"text": "Python3"
},
{
"code": "#Python program to check if two # to get unique values from list# using numpy.unique import numpy as np # function to get unique valuesdef unique(list1): x = np.array(list1) print(np.unique(x)) # driver codelist1 = [10, 20, 10, 30, 40, 40]print(\"the unique values from 1st list is\")unique(list1) list2 =[1, 2, 1, 1, 3, 4, 3, 3, 5]print(\"\\nthe unique values from 2nd list is\")unique(list2)",
"e": 2953,
"s": 2547,
"text": null
},
{
"code": null,
"e": 2962,
"s": 2953,
"text": "Output "
},
{
"code": null,
"e": 3059,
"s": 2962,
"text": "the unique values from 1st list is\n[10 20 30 40]\n\nthe unique values from 2nd list is\n[1 2 3 4 5]"
},
{
"code": null,
"e": 3098,
"s": 3059,
"text": "Method #4: Using collections.Counter()"
},
{
"code": null,
"e": 3226,
"s": 3098,
"text": "Using python import Counter() from collections print all the keys of Counter elements or we print directly by using “*” symbol."
},
{
"code": null,
"e": 3273,
"s": 3226,
"text": "Below is the implementation of above approach."
},
{
"code": null,
"e": 3281,
"s": 3273,
"text": "Python3"
},
{
"code": "# Python program to check if two# to get unique values from list# importing counter from collectionsfrom collections import Counter # Function to get unique valuesdef unique(list1): # Print directly by using * symbol print(*Counter(list1)) # driver codelist1 = [10, 20, 10, 30, 40, 40]print(\"the unique values from 1st list is\")unique(list1) list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]print(\"\\nthe unique values from 2nd list is\")unique(list2) # This code is contributed by vikkycirus",
"e": 3776,
"s": 3281,
"text": null
},
{
"code": null,
"e": 3784,
"s": 3776,
"text": "Output:"
},
{
"code": null,
"e": 3877,
"s": 3784,
"text": "the unique values from 1st list is\n10 20 30 40\n\nthe unique values from 2nd list is\n1 2 3 4 5"
},
{
"code": null,
"e": 3888,
"s": 3877,
"text": "vikkycirus"
},
{
"code": null,
"e": 3897,
"s": 3888,
"text": "gabaa406"
},
{
"code": null,
"e": 3909,
"s": 3897,
"text": "kk773572498"
},
{
"code": null,
"e": 3922,
"s": 3909,
"text": "simmytarika5"
},
{
"code": null,
"e": 3943,
"s": 3922,
"text": "Python list-programs"
},
{
"code": null,
"e": 3955,
"s": 3943,
"text": "python-list"
},
{
"code": null,
"e": 3962,
"s": 3955,
"text": "Python"
},
{
"code": null,
"e": 3974,
"s": 3962,
"text": "python-list"
},
{
"code": null,
"e": 4072,
"s": 3974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4114,
"s": 4072,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4136,
"s": 4114,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4162,
"s": 4136,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4194,
"s": 4162,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4223,
"s": 4194,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4250,
"s": 4223,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4286,
"s": 4250,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4307,
"s": 4286,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4338,
"s": 4307,
"text": "Python | os.path.join() method"
}
] |
Count ways to obtain given sum by repeated throws of a dice | 23 Jun, 2021
Given an integer N, the task is to find the number of ways to get the sum N by repeatedly throwing a dice.
Examples:
Input: N = 3Output: 4Explanation:The four possible ways to obtain N are:
1 + 1 + 1
1 + 2
2 + 1
3
Input: N = 2Output: 2Explanation:The two possible ways to obtain N are:
1 + 1
2
Recursive Approach: The idea is to iterate for every possible value of dice to get the required sum N. Below are the steps:
Let findWays() be the required answer for sum N.The only numbers obtained from the throw of dice are [1, 6], each having equal probability in a single throw of dice.Therefore, for every state, recur for the previous (N – i) states (where 1 ≤ i ≤ 6). Therefore, the recursive relation is as follows:
Let findWays() be the required answer for sum N.
The only numbers obtained from the throw of dice are [1, 6], each having equal probability in a single throw of dice.
Therefore, for every state, recur for the previous (N – i) states (where 1 ≤ i ≤ 6). Therefore, the recursive relation is as follows:
findWays(N) = findWays(N – 1) + findWays(N – 2) + findWays(N – 3) + findWays(N – 4) + findWays(N – 5) + findWays(N – 6)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the number of ways// to get the sum N with throw of diceint findWays(int N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codeint main(){ int N = 4; // Function call cout << findWays(N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the number of ways// to get the sum N with throw of dicestatic int findWays(int N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for(int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codepublic static void main(String[] args){ int N = 4; // Function call System.out.print(findWays(N));}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to find the number of ways# to get the sum N with throw of dicedef findWays(N): # Base case if (N == 0): return 1 # Stores the count of total # number of ways to get sum N cnt = 0 # Recur for all 6 states for i in range(1, 7): if (N - i >= 0): cnt = cnt + findWays(N - i) # Return answer return cnt # Driver Codeif __name__ == '__main__': N = 4 # Function call print(findWays(N)) # This code is contributed by mohit kumar 29
// C# program for// the above approachusing System;class GFG{ // Function to find the number of ways// to get the sum N with throw of dicestatic int findWays(int N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for(int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codepublic static void Main(){ int N = 4; // Function call Console.Write(findWays(N));}} // This code is contributed by sanjoy_62
<script> // JavaScript program for the above approach // Function to find the number of ways// to get the sum N with throw of dicefunction findWays(N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N var cnt = 0; // Recur for all 6 states for (var i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codevar N = 4; // Function calldocument.write( findWays(N)); </script>
8
Time Complexity: O(6N)Auxiliary Space: O(1)
Dynamic Programming Approach: The above recursive approach needs to be optimized by dealing with the following overlapping subproblems:
Overlapping Subproblems: Partial recursion tree for N = 8:
Optimal Substructure: As for every state, recurrence occurs for 6 states, so the recursive definition of dp(N) is the following:
dp[N] = dp[N-1] + dp[N-2] + dp[N-3] + dp[N-4] + dp[N-5] + dp[N-6]
Follow the steps below to solve the problem:
Initialize an auxiliary array dp[] of size N + 1 with initial value -1, where dp[i] stores the count of ways of having sum i.
The base case while solving this problem is if N is equal to 0 in any state, the result to such a state is 1.
If for any state dp[i] is not equal to -1, then this value as this substructure is already beed calculated.
Top-Down Approach: Below is the implementation of the Top-Down approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the total// number of ways to have sum Nint findWays(int N, int dp[]){ // Base Case if (N == 0) { return 1; } // Return already stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codeint main(){ // Given sum N int N = 4; // Initialize the dp array int dp[N + 1]; memset(dp, -1, sizeof(dp)); // Function Call cout << findWays(N, dp); return 0;}
// Java Program for// the above approachimport java.util.*;class GFG{ // Function to calculate the total// number of ways to have sum Nstatic int findWays(int N, int dp[]){ // Base Case if (N == 0) { return 1; } // Return already // stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codepublic static void main(String[] args){ // Given sum N int N = 4; // Initialize the dp array int []dp = new int[N + 1]; for (int i = 0; i < dp.length; i++) dp[i] = -1; // Function Call System.out.print(findWays(N, dp));}} // This code is contributed by 29AjayKumar
# Python3 Program for the# above approach # Function to calculate# the total number of ways# to have sum Ndef findWays(N, dp): # Base Case if (N == 0): return 1 # Return already # stored result if (dp[N] != -1): return dp[N] cnt = 0 # Recur for all 6 states for i in range (1, 7): if (N - i >= 0): cnt = (cnt + findWays(N - i, dp)) # Return the result dp[N] = cnt return dp[N] # Driver Codeif __name__ == "__main__": # Given sum N N = 4 # Initialize the dp array dp = [-1] * (N + 1) # Function Call print(findWays(N, dp)) # This code is contributed by Chitranayal
// C# Program for// the above approachusing System;class GFG{ // Function to calculate the total// number of ways to have sum Nstatic int findWays(int N, int []dp){ // Base Case if (N == 0) { return 1; } // Return already stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codepublic static void Main(String[] args){ // Given sum N int N = 4; // Initialize the dp array int []dp = new int[N + 1]; for (int i = 0; i < dp.Length; i++) dp[i] = -1; // Function Call Console.Write(findWays(N, dp));}} // This code is contributed by Rajput-Ji
<script>// Javascript Program for// the above approach // Function to calculate the total// number of ways to have sum Nfunction findWays(N,dp){ // Base Case if (N == 0) { return 1; } // Return already // stored result if (dp[N] != -1) { return dp[N]; } let cnt = 0; // Recur for all 6 states for (let i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codelet N = 4; // Initialize the dp arraylet dp = new Array(N + 1); for (let i = 0; i < dp.length; i++) dp[i] = -1; // Function Calldocument.write(findWays(N, dp)); // This code is contributed by unknown2108</script>
8
Time Complexity: O(N)Auxiliary Space: O(N)
Bottom-Up Approach: Below is the implementation of the Bottom-up Dynamic Programming approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the total// number of ways to have sum Nvoid findWays(int N){ // Initialize dp array int dp[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for (int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for (int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways cout << dp[N];} // Driver Codeint main(){ // Given sum N int N = 4; // Function call findWays(N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to calculate the total// number of ways to have sum Nstatic void findWays(int N){ // Initialize dp array int []dp = new int[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways System.out.print(dp[N]);} // Driver Codepublic static void main(String[] args){ // Given sum N int N = 4; // Function call findWays(N);}} // This code is contributed by Amit Katiyar
# Python3 program for# the above approach # Function to calculate the total# number of ways to have sum Ndef findWays(N): # Initialize dp array dp = [0] * (N + 1); dp[0] = 1; # Iterate over all the # possible intermediate # values to reach N for i in range(1, N + 1): dp[i] = 0; # Calculate the sum for # all 6 faces for j in range(1, 7): if (i - j >= 0): dp[i] = dp[i] + dp[i - j]; # Print total number of ways print(dp[N]); # Driver Codeif __name__ == '__main__': # Given sum N N = 4; # Function call findWays(N); # This code is contributed by 29AjayKumar
// C# program for// the above approachusing System;class GFG{ // Function to calculate the total// number of ways to have sum Nstatic void findWays(int N){ // Initialize dp array int []dp = new int[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways Console.Write(dp[N]);} // Driver Codepublic static void Main(String[] args){ // Given sum N int N = 4; // Function call findWays(N);}} // This code is contributed by 29AjayKumar
<script> // JavaScript program for the above approach // Function to calculate the total// number of ways to have sum Nfunction findWays(N){ // Initialize dp array let dp = new Array(N + 1); dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(let i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(let j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways document.write(dp[N]);} // Driver Code // Given sum Nlet N = 4; // Function callfindWays(N); // This code is contributed by patel2127 </script>
8
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
sanjoy_62
Rajput-Ji
amit143katiyar
ukasp
rrrtnx
unknown2108
patel2127
Analysis of Algorithms (Recurrences)
Memoization
Dynamic Programming
Mathematical
Recursion
Dynamic Programming
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Find if there is a path between two vertices in an undirected graph
Matrix Chain Multiplication | DP-8
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 161,
"s": 54,
"text": "Given an integer N, the task is to find the number of ways to get the sum N by repeatedly throwing a dice."
},
{
"code": null,
"e": 171,
"s": 161,
"text": "Examples:"
},
{
"code": null,
"e": 244,
"s": 171,
"text": "Input: N = 3Output: 4Explanation:The four possible ways to obtain N are:"
},
{
"code": null,
"e": 254,
"s": 244,
"text": "1 + 1 + 1"
},
{
"code": null,
"e": 260,
"s": 254,
"text": "1 + 2"
},
{
"code": null,
"e": 266,
"s": 260,
"text": "2 + 1"
},
{
"code": null,
"e": 268,
"s": 266,
"text": "3"
},
{
"code": null,
"e": 340,
"s": 268,
"text": "Input: N = 2Output: 2Explanation:The two possible ways to obtain N are:"
},
{
"code": null,
"e": 346,
"s": 340,
"text": "1 + 1"
},
{
"code": null,
"e": 348,
"s": 346,
"text": "2"
},
{
"code": null,
"e": 472,
"s": 348,
"text": "Recursive Approach: The idea is to iterate for every possible value of dice to get the required sum N. Below are the steps:"
},
{
"code": null,
"e": 771,
"s": 472,
"text": "Let findWays() be the required answer for sum N.The only numbers obtained from the throw of dice are [1, 6], each having equal probability in a single throw of dice.Therefore, for every state, recur for the previous (N – i) states (where 1 ≤ i ≤ 6). Therefore, the recursive relation is as follows:"
},
{
"code": null,
"e": 820,
"s": 771,
"text": "Let findWays() be the required answer for sum N."
},
{
"code": null,
"e": 938,
"s": 820,
"text": "The only numbers obtained from the throw of dice are [1, 6], each having equal probability in a single throw of dice."
},
{
"code": null,
"e": 1072,
"s": 938,
"text": "Therefore, for every state, recur for the previous (N – i) states (where 1 ≤ i ≤ 6). Therefore, the recursive relation is as follows:"
},
{
"code": null,
"e": 1192,
"s": 1072,
"text": "findWays(N) = findWays(N – 1) + findWays(N – 2) + findWays(N – 3) + findWays(N – 4) + findWays(N – 5) + findWays(N – 6)"
},
{
"code": null,
"e": 1243,
"s": 1192,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1247,
"s": 1243,
"text": "C++"
},
{
"code": null,
"e": 1252,
"s": 1247,
"text": "Java"
},
{
"code": null,
"e": 1260,
"s": 1252,
"text": "Python3"
},
{
"code": null,
"e": 1263,
"s": 1260,
"text": "C#"
},
{
"code": null,
"e": 1274,
"s": 1263,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the number of ways// to get the sum N with throw of diceint findWays(int N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codeint main(){ int N = 4; // Function call cout << findWays(N); return 0;}",
"e": 1891,
"s": 1274,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the number of ways// to get the sum N with throw of dicestatic int findWays(int N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for(int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codepublic static void main(String[] args){ int N = 4; // Function call System.out.print(findWays(N));}} // This code is contributed by 29AjayKumar",
"e": 2584,
"s": 1891,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the number of ways# to get the sum N with throw of dicedef findWays(N): # Base case if (N == 0): return 1 # Stores the count of total # number of ways to get sum N cnt = 0 # Recur for all 6 states for i in range(1, 7): if (N - i >= 0): cnt = cnt + findWays(N - i) # Return answer return cnt # Driver Codeif __name__ == '__main__': N = 4 # Function call print(findWays(N)) # This code is contributed by mohit kumar 29",
"e": 3140,
"s": 2584,
"text": null
},
{
"code": "// C# program for// the above approachusing System;class GFG{ // Function to find the number of ways// to get the sum N with throw of dicestatic int findWays(int N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N int cnt = 0; // Recur for all 6 states for(int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codepublic static void Main(){ int N = 4; // Function call Console.Write(findWays(N));}} // This code is contributed by sanjoy_62",
"e": 3732,
"s": 3140,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the number of ways// to get the sum N with throw of dicefunction findWays(N){ // Base Case if (N == 0) { return 1; } // Stores the count of total // number of ways to get sum N var cnt = 0; // Recur for all 6 states for (var i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i); } } // Return answer return cnt;} // Driver Codevar N = 4; // Function calldocument.write( findWays(N)); </script>",
"e": 4304,
"s": 3732,
"text": null
},
{
"code": null,
"e": 4306,
"s": 4304,
"text": "8"
},
{
"code": null,
"e": 4350,
"s": 4306,
"text": "Time Complexity: O(6N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4486,
"s": 4350,
"text": "Dynamic Programming Approach: The above recursive approach needs to be optimized by dealing with the following overlapping subproblems:"
},
{
"code": null,
"e": 4545,
"s": 4486,
"text": "Overlapping Subproblems: Partial recursion tree for N = 8:"
},
{
"code": null,
"e": 4674,
"s": 4545,
"text": "Optimal Substructure: As for every state, recurrence occurs for 6 states, so the recursive definition of dp(N) is the following:"
},
{
"code": null,
"e": 4740,
"s": 4674,
"text": "dp[N] = dp[N-1] + dp[N-2] + dp[N-3] + dp[N-4] + dp[N-5] + dp[N-6]"
},
{
"code": null,
"e": 4785,
"s": 4740,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 4911,
"s": 4785,
"text": "Initialize an auxiliary array dp[] of size N + 1 with initial value -1, where dp[i] stores the count of ways of having sum i."
},
{
"code": null,
"e": 5021,
"s": 4911,
"text": "The base case while solving this problem is if N is equal to 0 in any state, the result to such a state is 1."
},
{
"code": null,
"e": 5129,
"s": 5021,
"text": "If for any state dp[i] is not equal to -1, then this value as this substructure is already beed calculated."
},
{
"code": null,
"e": 5202,
"s": 5129,
"text": "Top-Down Approach: Below is the implementation of the Top-Down approach:"
},
{
"code": null,
"e": 5206,
"s": 5202,
"text": "C++"
},
{
"code": null,
"e": 5211,
"s": 5206,
"text": "Java"
},
{
"code": null,
"e": 5219,
"s": 5211,
"text": "Python3"
},
{
"code": null,
"e": 5222,
"s": 5219,
"text": "C#"
},
{
"code": null,
"e": 5233,
"s": 5222,
"text": "Javascript"
},
{
"code": "// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the total// number of ways to have sum Nint findWays(int N, int dp[]){ // Base Case if (N == 0) { return 1; } // Return already stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codeint main(){ // Given sum N int N = 4; // Initialize the dp array int dp[N + 1]; memset(dp, -1, sizeof(dp)); // Function Call cout << findWays(N, dp); return 0;}",
"e": 5986,
"s": 5233,
"text": null
},
{
"code": "// Java Program for// the above approachimport java.util.*;class GFG{ // Function to calculate the total// number of ways to have sum Nstatic int findWays(int N, int dp[]){ // Base Case if (N == 0) { return 1; } // Return already // stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codepublic static void main(String[] args){ // Given sum N int N = 4; // Initialize the dp array int []dp = new int[N + 1]; for (int i = 0; i < dp.length; i++) dp[i] = -1; // Function Call System.out.print(findWays(N, dp));}} // This code is contributed by 29AjayKumar",
"e": 6860,
"s": 5986,
"text": null
},
{
"code": "# Python3 Program for the# above approach # Function to calculate# the total number of ways# to have sum Ndef findWays(N, dp): # Base Case if (N == 0): return 1 # Return already # stored result if (dp[N] != -1): return dp[N] cnt = 0 # Recur for all 6 states for i in range (1, 7): if (N - i >= 0): cnt = (cnt + findWays(N - i, dp)) # Return the result dp[N] = cnt return dp[N] # Driver Codeif __name__ == \"__main__\": # Given sum N N = 4 # Initialize the dp array dp = [-1] * (N + 1) # Function Call print(findWays(N, dp)) # This code is contributed by Chitranayal",
"e": 7536,
"s": 6860,
"text": null
},
{
"code": "// C# Program for// the above approachusing System;class GFG{ // Function to calculate the total// number of ways to have sum Nstatic int findWays(int N, int []dp){ // Base Case if (N == 0) { return 1; } // Return already stored result if (dp[N] != -1) { return dp[N]; } int cnt = 0; // Recur for all 6 states for (int i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codepublic static void Main(String[] args){ // Given sum N int N = 4; // Initialize the dp array int []dp = new int[N + 1]; for (int i = 0; i < dp.Length; i++) dp[i] = -1; // Function Call Console.Write(findWays(N, dp));}} // This code is contributed by Rajput-Ji",
"e": 8301,
"s": 7536,
"text": null
},
{
"code": "<script>// Javascript Program for// the above approach // Function to calculate the total// number of ways to have sum Nfunction findWays(N,dp){ // Base Case if (N == 0) { return 1; } // Return already // stored result if (dp[N] != -1) { return dp[N]; } let cnt = 0; // Recur for all 6 states for (let i = 1; i <= 6; i++) { if (N - i >= 0) { cnt = cnt + findWays(N - i, dp); } } // Return the result return dp[N] = cnt;} // Driver Codelet N = 4; // Initialize the dp arraylet dp = new Array(N + 1); for (let i = 0; i < dp.length; i++) dp[i] = -1; // Function Calldocument.write(findWays(N, dp)); // This code is contributed by unknown2108</script>",
"e": 9073,
"s": 8301,
"text": null
},
{
"code": null,
"e": 9075,
"s": 9073,
"text": "8"
},
{
"code": null,
"e": 9118,
"s": 9075,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9213,
"s": 9118,
"text": "Bottom-Up Approach: Below is the implementation of the Bottom-up Dynamic Programming approach:"
},
{
"code": null,
"e": 9217,
"s": 9213,
"text": "C++"
},
{
"code": null,
"e": 9222,
"s": 9217,
"text": "Java"
},
{
"code": null,
"e": 9230,
"s": 9222,
"text": "Python3"
},
{
"code": null,
"e": 9233,
"s": 9230,
"text": "C#"
},
{
"code": null,
"e": 9244,
"s": 9233,
"text": "Javascript"
},
{
"code": "// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the total// number of ways to have sum Nvoid findWays(int N){ // Initialize dp array int dp[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for (int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for (int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways cout << dp[N];} // Driver Codeint main(){ // Given sum N int N = 4; // Function call findWays(N); return 0;}",
"e": 9959,
"s": 9244,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to calculate the total// number of ways to have sum Nstatic void findWays(int N){ // Initialize dp array int []dp = new int[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways System.out.print(dp[N]);} // Driver Codepublic static void main(String[] args){ // Given sum N int N = 4; // Function call findWays(N);}} // This code is contributed by Amit Katiyar",
"e": 10784,
"s": 9959,
"text": null
},
{
"code": "# Python3 program for# the above approach # Function to calculate the total# number of ways to have sum Ndef findWays(N): # Initialize dp array dp = [0] * (N + 1); dp[0] = 1; # Iterate over all the # possible intermediate # values to reach N for i in range(1, N + 1): dp[i] = 0; # Calculate the sum for # all 6 faces for j in range(1, 7): if (i - j >= 0): dp[i] = dp[i] + dp[i - j]; # Print total number of ways print(dp[N]); # Driver Codeif __name__ == '__main__': # Given sum N N = 4; # Function call findWays(N); # This code is contributed by 29AjayKumar",
"e": 11445,
"s": 10784,
"text": null
},
{
"code": "// C# program for// the above approachusing System;class GFG{ // Function to calculate the total// number of ways to have sum Nstatic void findWays(int N){ // Initialize dp array int []dp = new int[N + 1]; dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(int i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(int j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways Console.Write(dp[N]);} // Driver Codepublic static void Main(String[] args){ // Given sum N int N = 4; // Function call findWays(N);}} // This code is contributed by 29AjayKumar",
"e": 12164,
"s": 11445,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to calculate the total// number of ways to have sum Nfunction findWays(N){ // Initialize dp array let dp = new Array(N + 1); dp[0] = 1; // Iterate over all the possible // intermediate values to reach N for(let i = 1; i <= N; i++) { dp[i] = 0; // Calculate the sum for // all 6 faces for(let j = 1; j <= 6; j++) { if (i - j >= 0) { dp[i] = dp[i] + dp[i - j]; } } } // Print the total number of ways document.write(dp[N]);} // Driver Code // Given sum Nlet N = 4; // Function callfindWays(N); // This code is contributed by patel2127 </script>",
"e": 12908,
"s": 12164,
"text": null
},
{
"code": null,
"e": 12910,
"s": 12908,
"text": "8"
},
{
"code": null,
"e": 12953,
"s": 12910,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 12968,
"s": 12953,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 12980,
"s": 12968,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12990,
"s": 12980,
"text": "sanjoy_62"
},
{
"code": null,
"e": 13000,
"s": 12990,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13015,
"s": 13000,
"text": "amit143katiyar"
},
{
"code": null,
"e": 13021,
"s": 13015,
"text": "ukasp"
},
{
"code": null,
"e": 13028,
"s": 13021,
"text": "rrrtnx"
},
{
"code": null,
"e": 13040,
"s": 13028,
"text": "unknown2108"
},
{
"code": null,
"e": 13050,
"s": 13040,
"text": "patel2127"
},
{
"code": null,
"e": 13087,
"s": 13050,
"text": "Analysis of Algorithms (Recurrences)"
},
{
"code": null,
"e": 13099,
"s": 13087,
"text": "Memoization"
},
{
"code": null,
"e": 13119,
"s": 13099,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 13132,
"s": 13119,
"text": "Mathematical"
},
{
"code": null,
"e": 13142,
"s": 13132,
"text": "Recursion"
},
{
"code": null,
"e": 13162,
"s": 13142,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 13175,
"s": 13162,
"text": "Mathematical"
},
{
"code": null,
"e": 13185,
"s": 13175,
"text": "Recursion"
},
{
"code": null,
"e": 13283,
"s": 13185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13321,
"s": 13283,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 13354,
"s": 13321,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 13373,
"s": 13354,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 13441,
"s": 13373,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 13476,
"s": 13441,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 13519,
"s": 13476,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 13534,
"s": 13519,
"text": "C++ Data Types"
},
{
"code": null,
"e": 13558,
"s": 13534,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 13577,
"s": 13558,
"text": "Coin Change | DP-7"
}
] |
Compiler Class in Java | 09 Feb, 2022
Compiler Class provides support and related services to Java code to Native Code. Native code is a form of code that can be said to run in a virtual machine (for example, [JVM]Java Virtual Machine).
Declaration:
public final class Compiler extends Object
The java.lang.Compiler.command() tests the argument type and performs some documented operations.
Syntax:
public static boolean command(Object argument)
Parameters:
argument: needs to be compiler-specific.
Return: It returns the compiler-specific value.
Exception: It throws NullPointerException.
The java.lang.Compiler.compileClass() compiles the specified class.
Syntax:
public static boolean compileClass(Class c)
Parameters:
c: class to be compiled.
Return: It returns true if the compilation succeeded. Else, false.
Exception: It throws NullPointerException.
The java.lang.Compiler.enable() cause compiler to start operation.
Syntax :
public static void enable()
Return: It returns nothing.
The java.lang.Compiler.disable() stops compiler to perform operations.
Syntax :
public static void disable()
Return: It returns nothing.
The java.lang.Compiler.compileClasses() compiles the classes having the name as string – “str”.
Syntax:
public static boolean compileClasses(String string)
Parameters:
str: name of the class to be compiled.
Return: It returns true if the classes are compiled successfully.
Exception: It throws NullPointerException.
Java
// Java Program illustrating the use// of Compiler class Methods. import java.lang.*; public class NewClass { public static void main(String[] args) { CompilerClass geek = new CompilerClass(); // Use of enable() : Compiler.enable(); // class CompilerDemo Class c = geek.getClass(); System.out.println(c); // Use of command() : Object g = Compiler.command("javac CompilerClass"); System.out.println("Value : " + g); // Use of compileClass : // Since it is not a subclass so there is no // compiler for it boolean check = Compiler.compileClass(c); System.out.println( "\nIs compilation successful ? : " + check); String str = "CompilerClass"; boolean check1 = Compiler.compileClasses(str); System.out.println( "\nIs compilation successful using str ? : " + check1); // Use of disable() : Compiler.disable(); } private static class CompilerClass { public CompilerClass() {} }}
Output:
class NewClass$CompilerClass
Value : null
Is compilation successful ? : false
Is compilation successful using str ? : false
Note: The Compiler Class in Java inherits others methods from the Object class in Java.
This article is contributed by Mohit Gupta_OMG. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article at [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.
nishkarshgandhi
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 254,
"s": 54,
"text": "Compiler Class provides support and related services to Java code to Native Code. Native code is a form of code that can be said to run in a virtual machine (for example, [JVM]Java Virtual Machine). "
},
{
"code": null,
"e": 267,
"s": 254,
"text": "Declaration:"
},
{
"code": null,
"e": 310,
"s": 267,
"text": "public final class Compiler extends Object"
},
{
"code": null,
"e": 409,
"s": 310,
"text": "The java.lang.Compiler.command() tests the argument type and performs some documented operations. "
},
{
"code": null,
"e": 418,
"s": 409,
"text": "Syntax: "
},
{
"code": null,
"e": 465,
"s": 418,
"text": "public static boolean command(Object argument)"
},
{
"code": null,
"e": 477,
"s": 465,
"text": "Parameters:"
},
{
"code": null,
"e": 518,
"s": 477,
"text": "argument: needs to be compiler-specific."
},
{
"code": null,
"e": 566,
"s": 518,
"text": "Return: It returns the compiler-specific value."
},
{
"code": null,
"e": 609,
"s": 566,
"text": "Exception: It throws NullPointerException."
},
{
"code": null,
"e": 678,
"s": 609,
"text": "The java.lang.Compiler.compileClass() compiles the specified class. "
},
{
"code": null,
"e": 687,
"s": 678,
"text": "Syntax: "
},
{
"code": null,
"e": 731,
"s": 687,
"text": "public static boolean compileClass(Class c)"
},
{
"code": null,
"e": 744,
"s": 731,
"text": "Parameters: "
},
{
"code": null,
"e": 769,
"s": 744,
"text": "c: class to be compiled."
},
{
"code": null,
"e": 836,
"s": 769,
"text": "Return: It returns true if the compilation succeeded. Else, false."
},
{
"code": null,
"e": 880,
"s": 836,
"text": "Exception: It throws NullPointerException."
},
{
"code": null,
"e": 948,
"s": 880,
"text": "The java.lang.Compiler.enable() cause compiler to start operation. "
},
{
"code": null,
"e": 958,
"s": 948,
"text": "Syntax : "
},
{
"code": null,
"e": 986,
"s": 958,
"text": "public static void enable()"
},
{
"code": null,
"e": 1014,
"s": 986,
"text": "Return: It returns nothing."
},
{
"code": null,
"e": 1086,
"s": 1014,
"text": "The java.lang.Compiler.disable() stops compiler to perform operations. "
},
{
"code": null,
"e": 1096,
"s": 1086,
"text": "Syntax : "
},
{
"code": null,
"e": 1125,
"s": 1096,
"text": "public static void disable()"
},
{
"code": null,
"e": 1153,
"s": 1125,
"text": "Return: It returns nothing."
},
{
"code": null,
"e": 1249,
"s": 1153,
"text": "The java.lang.Compiler.compileClasses() compiles the classes having the name as string – “str”."
},
{
"code": null,
"e": 1258,
"s": 1249,
"text": "Syntax: "
},
{
"code": null,
"e": 1310,
"s": 1258,
"text": "public static boolean compileClasses(String string)"
},
{
"code": null,
"e": 1323,
"s": 1310,
"text": "Parameters: "
},
{
"code": null,
"e": 1362,
"s": 1323,
"text": "str: name of the class to be compiled."
},
{
"code": null,
"e": 1428,
"s": 1362,
"text": "Return: It returns true if the classes are compiled successfully."
},
{
"code": null,
"e": 1471,
"s": 1428,
"text": "Exception: It throws NullPointerException."
},
{
"code": null,
"e": 1476,
"s": 1471,
"text": "Java"
},
{
"code": "// Java Program illustrating the use// of Compiler class Methods. import java.lang.*; public class NewClass { public static void main(String[] args) { CompilerClass geek = new CompilerClass(); // Use of enable() : Compiler.enable(); // class CompilerDemo Class c = geek.getClass(); System.out.println(c); // Use of command() : Object g = Compiler.command(\"javac CompilerClass\"); System.out.println(\"Value : \" + g); // Use of compileClass : // Since it is not a subclass so there is no // compiler for it boolean check = Compiler.compileClass(c); System.out.println( \"\\nIs compilation successful ? : \" + check); String str = \"CompilerClass\"; boolean check1 = Compiler.compileClasses(str); System.out.println( \"\\nIs compilation successful using str ? : \" + check1); // Use of disable() : Compiler.disable(); } private static class CompilerClass { public CompilerClass() {} }}",
"e": 2546,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2554,
"s": 2546,
"text": "Output:"
},
{
"code": null,
"e": 2680,
"s": 2554,
"text": "class NewClass$CompilerClass\nValue : null\n\nIs compilation successful ? : false\n\nIs compilation successful using str ? : false"
},
{
"code": null,
"e": 2768,
"s": 2680,
"text": "Note: The Compiler Class in Java inherits others methods from the Object class in Java."
},
{
"code": null,
"e": 3192,
"s": 2768,
"text": "This article is contributed by Mohit Gupta_OMG. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article at [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": 3208,
"s": 3192,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 3226,
"s": 3208,
"text": "Java-lang package"
},
{
"code": null,
"e": 3231,
"s": 3226,
"text": "Java"
},
{
"code": null,
"e": 3236,
"s": 3231,
"text": "Java"
},
{
"code": null,
"e": 3334,
"s": 3236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3349,
"s": 3334,
"text": "Stream In Java"
},
{
"code": null,
"e": 3370,
"s": 3349,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3391,
"s": 3370,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3410,
"s": 3391,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3427,
"s": 3410,
"text": "Generics in Java"
},
{
"code": null,
"e": 3457,
"s": 3427,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3483,
"s": 3457,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3499,
"s": 3483,
"text": "Strings in Java"
},
{
"code": null,
"e": 3536,
"s": 3499,
"text": "Differences between JDK, JRE and JVM"
}
] |
Path toString() method in Java with Examples | 16 Jul, 2019
The Java Path interface was added to Java NIO in Java 7. toString() method of java.nio.file.Path used to return the string representation of this path. If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path. The returned path by this method uses the default name-separator to separate names in the path.
Syntax:
String toString()
Parameters: This method accepts nothing.
Return value: This method returns the string representation of this path.
Below programs illustrate toString() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.toAbsolute() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get("C:\\Program Files\\" + "Java\\jre1.8.0_211"); // print path System.out.println("Path: " + path.toString()); }}
Path: C:\Program Files\Java\jre1.8.0_211
Program 2:
// Java program to demonstrate// java.nio.file.Path.toString() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get("C:\\Users\\" + "asingh.one\\Documents"); // print path System.out.println("Path: " + path.toString()); }}
Path: C:\Users\asingh.one\Documents
References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toString()
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jul, 2019"
},
{
"code": null,
"e": 460,
"s": 28,
"text": "The Java Path interface was added to Java NIO in Java 7. toString() method of java.nio.file.Path used to return the string representation of this path. If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path. The returned path by this method uses the default name-separator to separate names in the path."
},
{
"code": null,
"e": 468,
"s": 460,
"text": "Syntax:"
},
{
"code": null,
"e": 487,
"s": 468,
"text": "String toString()\n"
},
{
"code": null,
"e": 528,
"s": 487,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 602,
"s": 528,
"text": "Return value: This method returns the string representation of this path."
},
{
"code": null,
"e": 657,
"s": 602,
"text": "Below programs illustrate toString() method:Program 1:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.toAbsolute() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get(\"C:\\\\Program Files\\\\\" + \"Java\\\\jre1.8.0_211\"); // print path System.out.println(\"Path: \" + path.toString()); }}",
"e": 1156,
"s": 657,
"text": null
},
{
"code": null,
"e": 1198,
"s": 1156,
"text": "Path: C:\\Program Files\\Java\\jre1.8.0_211\n"
},
{
"code": null,
"e": 1209,
"s": 1198,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// java.nio.file.Path.toString() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths; public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get(\"C:\\\\Users\\\\\" + \"asingh.one\\\\Documents\"); // print path System.out.println(\"Path: \" + path.toString()); }}",
"e": 1703,
"s": 1209,
"text": null
},
{
"code": null,
"e": 1740,
"s": 1703,
"text": "Path: C:\\Users\\asingh.one\\Documents\n"
},
{
"code": null,
"e": 1830,
"s": 1740,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toString()"
},
{
"code": null,
"e": 1845,
"s": 1830,
"text": "Java-Functions"
},
{
"code": null,
"e": 1855,
"s": 1845,
"text": "Java-Path"
},
{
"code": null,
"e": 1877,
"s": 1855,
"text": "java.nio.file package"
},
{
"code": null,
"e": 1882,
"s": 1877,
"text": "Java"
},
{
"code": null,
"e": 1887,
"s": 1882,
"text": "Java"
},
{
"code": null,
"e": 1985,
"s": 1887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2000,
"s": 1985,
"text": "Stream In Java"
},
{
"code": null,
"e": 2021,
"s": 2000,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2042,
"s": 2021,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2061,
"s": 2042,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2078,
"s": 2061,
"text": "Generics in Java"
},
{
"code": null,
"e": 2108,
"s": 2078,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2134,
"s": 2108,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2150,
"s": 2134,
"text": "Strings in Java"
},
{
"code": null,
"e": 2187,
"s": 2150,
"text": "Differences between JDK, JRE and JVM"
}
] |
ReactJS Form Validation using Formik and Yup | 20 Sep, 2021
As covered in the previous article, we can validate forms using controlled components. But it may be time-consuming and the length of the code may increase if we need forms at many places on our website. Here comes Formik and Yup to the rescue! Formik is designed to manage forms with complex validation with ease. Formik supports synchronous and asynchronous form-level and field-level validation. Furthermore, it comes with baked-in support for schema-based form-level validation through Yup. We would also use bootstrap so that we won’t waste our time on HTML and CSS.
Below is the step-by-step implementation on how to so Form Validation using Formik and Yup.
Step 1: Creating React Application And Installing Module:
npx create-react-app react-form
Step 2: After creating your project folder i.e.react-form , move to it using the following command:
cd react-form
Step 3: Then add bootstrap (this is optional if you want you can create your own styling).
yarn add bootstrap
Step 4: We can proceed to add Formik and Yup.
yarn add formik yup
Project Structure: It will look like the following.
project structure
Note: We will write down the entire code in the App.js file. Here, App is our default component where we have written our code.
Step 5: <Formik> is a component that helps you with building forms. InitialValues is a prop that initializes all fields in your form. Generally, the initialization is an empty string but in some fields you may require an initial value.
Javascript
<Formik initialValues={{ email: "", password: "" }}>
Step 6: We are adding a code block in which we are passing props provided by Formik and we are printing the props object on the console. Then we use the <Form> Component provided by Bootstrap in which we again pass 2 components namely <label> and <Field> Component. Lastly, we use the Bootstrap <Button> Component for submitting the form. Basic boiler code of form component which should be wrapped inside formik.
Javascript
import React from "react";import { Formik, Form, Field } from "formik"; import "bootstrap/dist/css/bootstrap.css"; class App extends React.Component { render() { return ( <div className="container"> <div className="row"> <div className="col-lg-12"> <Formik initialValues={{ email: "", password: "" }}> {(props) => ( <div> {console.log(props)} <div className="row mb-5"> <div className="col-lg-12 text-center"> <h1 className="mt-5">Login Form</h1> </div> </div> <Form> <div className="form-group"> <label htmlFor="email">Email</label> <Field type="email" name="email" placeholder="Enter email" autoComplete="off" /> </div> <div className="form-group"> <label htmlFor="password" className="mt-3"> Password </label> <Field type="password" name="password" placeholder="Enter password" /> </div> <button type="submit" className="btn btn-primary btn-block mt-4" > Submit </button> </Form> </div> )} </Formik> </div> </div> </div> ); }} export default App;
Step 7: As discussed, we added a function that takes an argument (let’s say props) and we have wrapped our form inside the formik component and then we have printed the props argument so that we can see various props provided by formik. In the console, an object is displayed. If we look closely we can see that initial values also gets displayed in this object.
Step 8: Another prop for Formik is onSubmit which takes values as a parameter and it is mostly used for post api calls to collect the data out of the form and then we can store the data in the server. But in our case, we would keep it simple and just print the values in the console and alert a message.
Javascript
<Formik initialValues={{ email: "", password: "" }} onSubmit={(values) => { console.log(values) alert("Form is validated and in this block api call should be made..."); } }>
Step 9: Also, here we can have validationSchema prop which takes the Yup object (in this case LoginSchema) as a parameter with customized validations like if we want our Field to be :
String : Yup.string()Format as email (validation message) : Yup.email(“Invalid email address format”)Minimum characters : Yup.min(length , “Validation Message”)Maximum characters : Yup.max(length , “Validation Message”)
String : Yup.string()
Format as email (validation message) : Yup.email(“Invalid email address format”)
Minimum characters : Yup.min(length , “Validation Message”)
Maximum characters : Yup.max(length , “Validation Message”)
Javascript
const LoginSchema = Yup.object().shape({ email: Yup.string() // Format Validation .email("Invalid email address format") // Required Field Validation .required("Email is required"), password: Yup.string() //Minimum Character Validation .min(3, "Password must be 3 characters at minimum") .required("Password is required")});
Step 10: Formik Component after including 3 props namely initialValues, ValidationSchema (to bind Formik and Yup), onSubmit looks like this :
Javascript
<Formik initialValues={{ email: "", password: "" }} validationSchema={LoginSchema} onSubmit={(values) => { console.log(values) alert("Form is validated! Submitting the form...");}}>
The 4 important states of props object are touched, errors , isSubmitting, values which are more than enough to create highly customized forms .
touched takes boolean values as input and it sets to true if a field is clicked.errors is used to display error messages set by the Yup object.isSubmitting is set to true after we click on submit form.values consist of all field values at that point in time.
touched takes boolean values as input and it sets to true if a field is clicked.
errors is used to display error messages set by the Yup object.
isSubmitting is set to true after we click on submit form.
values consist of all field values at that point in time.
Step 11: Now comes the ErrorMessage Component which we generally use below the Field Component to display the validation generated by Yup. We can add bootstrap class invalid-feedback for styling.
Javascript
<label htmlFor="email">Email</label> <Field type="email" name="email" placeholder="Enter email" autocomplete="off" className={`mt-2 form-control ${touched.email && errors.email ? "is-invalid" : ""}`} // If there is validation error then // is-invalid bootstrap class is added/> <ErrorMessage component="div" name="email" className="invalid-feedback"/>
Step 12: We haven’t used isSubmitting prop in the function just yet. We can do one interesting thing using it. We can acknowledge the user who has been logged in and display his username and password using the values parameter on the screen by using conditional rendering and ternary operator.
Javascript
isSubmitting ? (<h1>Login Page</h1>) : (<h1>Confirmation of Login</h1>)// (condition) ? (if true this component gets displayed) : (else this component gets displayed)
Now we will see the complete code of the above steps.
App.js
import React from "react";import { Formik, Form, Field, ErrorMessage } from "formik";import * as Yup from "yup";import "bootstrap/dist/css/bootstrap.css"; const LoginSchema = Yup.object().shape({ email: Yup.string() .email("Invalid email address format") .required("Email is required"), password: Yup.string() .min(3, "Password must be 3 characters at minimum") .required("Password is required"),}); class App extends React.Component { render() { return ( <div className="container"> <div className="row"> <div className="col-lg-12"> <Formik initialValues={{ email: "", password: "" }} validationSchema={LoginSchema} onSubmit={(values) => { console.log(values); alert("Form is validated! Submitting the form..."); }} > {({ touched, errors, isSubmitting, values }) => !isSubmitting ? ( <div> <div className="row mb-5"> <div className="col-lg-12 text-center"> <h1 className="mt-5">Login Form</h1> </div> </div> <Form> <div className="form-group"> <label htmlFor="email">Email</label> <Field type="email" name="email" placeholder="Enter email" autocomplete="off" className={`mt-2 form-control ${touched.email && errors.email ? "is-invalid" : ""}`} /> <ErrorMessage component="div" name="email" className="invalid-feedback" /> </div> <div className="form-group"> <label htmlFor="password" className="mt-3"> Password </label> <Field type="password" name="password" placeholder="Enter password" className={`mt-2 form-control ${ touched.password && errors.password ? "is-invalid" : "" }`} /> <ErrorMessage component="div" name="password" className="invalid-feedback" /> </div> <button type="submit" className="btn btn-primary btn-block mt-4" > Submit </button> </Form> </div> ) : ( <div> <h1 className="p-3 mt-5">Form Submitted</h1> <div className="alert alert-success mt-3"> Thank for your connecting with us. Here's what we got from you ! </div> <ul className="list-group"> <li className="list-group-item">Email: {values.email}</li> <li className="list-group-item"> Password: {values.password} </li> </ul> </div> ) } </Formik> </div> </div> </div> ); }} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Blogathon-2021
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Sep, 2021"
},
{
"code": null,
"e": 626,
"s": 54,
"text": "As covered in the previous article, we can validate forms using controlled components. But it may be time-consuming and the length of the code may increase if we need forms at many places on our website. Here comes Formik and Yup to the rescue! Formik is designed to manage forms with complex validation with ease. Formik supports synchronous and asynchronous form-level and field-level validation. Furthermore, it comes with baked-in support for schema-based form-level validation through Yup. We would also use bootstrap so that we won’t waste our time on HTML and CSS."
},
{
"code": null,
"e": 718,
"s": 626,
"text": "Below is the step-by-step implementation on how to so Form Validation using Formik and Yup."
},
{
"code": null,
"e": 776,
"s": 718,
"text": "Step 1: Creating React Application And Installing Module:"
},
{
"code": null,
"e": 808,
"s": 776,
"text": "npx create-react-app react-form"
},
{
"code": null,
"e": 910,
"s": 810,
"text": "Step 2: After creating your project folder i.e.react-form , move to it using the following command:"
},
{
"code": null,
"e": 924,
"s": 910,
"text": "cd react-form"
},
{
"code": null,
"e": 1015,
"s": 924,
"text": "Step 3: Then add bootstrap (this is optional if you want you can create your own styling)."
},
{
"code": null,
"e": 1034,
"s": 1015,
"text": "yarn add bootstrap"
},
{
"code": null,
"e": 1080,
"s": 1034,
"text": "Step 4: We can proceed to add Formik and Yup."
},
{
"code": null,
"e": 1100,
"s": 1080,
"text": "yarn add formik yup"
},
{
"code": null,
"e": 1152,
"s": 1100,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1170,
"s": 1152,
"text": "project structure"
},
{
"code": null,
"e": 1299,
"s": 1170,
"text": "Note: We will write down the entire code in the App.js file. Here, App is our default component where we have written our code. "
},
{
"code": null,
"e": 1535,
"s": 1299,
"text": "Step 5: <Formik> is a component that helps you with building forms. InitialValues is a prop that initializes all fields in your form. Generally, the initialization is an empty string but in some fields you may require an initial value."
},
{
"code": null,
"e": 1546,
"s": 1535,
"text": "Javascript"
},
{
"code": "<Formik initialValues={{ email: \"\", password: \"\" }}>",
"e": 1623,
"s": 1546,
"text": null
},
{
"code": null,
"e": 2038,
"s": 1623,
"text": "Step 6: We are adding a code block in which we are passing props provided by Formik and we are printing the props object on the console. Then we use the <Form> Component provided by Bootstrap in which we again pass 2 components namely <label> and <Field> Component. Lastly, we use the Bootstrap <Button> Component for submitting the form. Basic boiler code of form component which should be wrapped inside formik."
},
{
"code": null,
"e": 2049,
"s": 2038,
"text": "Javascript"
},
{
"code": "import React from \"react\";import { Formik, Form, Field } from \"formik\"; import \"bootstrap/dist/css/bootstrap.css\"; class App extends React.Component { render() { return ( <div className=\"container\"> <div className=\"row\"> <div className=\"col-lg-12\"> <Formik initialValues={{ email: \"\", password: \"\" }}> {(props) => ( <div> {console.log(props)} <div className=\"row mb-5\"> <div className=\"col-lg-12 text-center\"> <h1 className=\"mt-5\">Login Form</h1> </div> </div> <Form> <div className=\"form-group\"> <label htmlFor=\"email\">Email</label> <Field type=\"email\" name=\"email\" placeholder=\"Enter email\" autoComplete=\"off\" /> </div> <div className=\"form-group\"> <label htmlFor=\"password\" className=\"mt-3\"> Password </label> <Field type=\"password\" name=\"password\" placeholder=\"Enter password\" /> </div> <button type=\"submit\" className=\"btn btn-primary btn-block mt-4\" > Submit </button> </Form> </div> )} </Formik> </div> </div> </div> ); }} export default App;",
"e": 3805,
"s": 2049,
"text": null
},
{
"code": null,
"e": 4168,
"s": 3805,
"text": "Step 7: As discussed, we added a function that takes an argument (let’s say props) and we have wrapped our form inside the formik component and then we have printed the props argument so that we can see various props provided by formik. In the console, an object is displayed. If we look closely we can see that initial values also gets displayed in this object."
},
{
"code": null,
"e": 4473,
"s": 4168,
"text": "Step 8: Another prop for Formik is onSubmit which takes values as a parameter and it is mostly used for post api calls to collect the data out of the form and then we can store the data in the server. But in our case, we would keep it simple and just print the values in the console and alert a message. "
},
{
"code": null,
"e": 4484,
"s": 4473,
"text": "Javascript"
},
{
"code": "<Formik initialValues={{ email: \"\", password: \"\" }} onSubmit={(values) => { console.log(values) alert(\"Form is validated and in this block api call should be made...\"); } }>",
"e": 4690,
"s": 4484,
"text": null
},
{
"code": null,
"e": 4874,
"s": 4690,
"text": "Step 9: Also, here we can have validationSchema prop which takes the Yup object (in this case LoginSchema) as a parameter with customized validations like if we want our Field to be :"
},
{
"code": null,
"e": 5094,
"s": 4874,
"text": "String : Yup.string()Format as email (validation message) : Yup.email(“Invalid email address format”)Minimum characters : Yup.min(length , “Validation Message”)Maximum characters : Yup.max(length , “Validation Message”)"
},
{
"code": null,
"e": 5116,
"s": 5094,
"text": "String : Yup.string()"
},
{
"code": null,
"e": 5197,
"s": 5116,
"text": "Format as email (validation message) : Yup.email(“Invalid email address format”)"
},
{
"code": null,
"e": 5257,
"s": 5197,
"text": "Minimum characters : Yup.min(length , “Validation Message”)"
},
{
"code": null,
"e": 5317,
"s": 5257,
"text": "Maximum characters : Yup.max(length , “Validation Message”)"
},
{
"code": null,
"e": 5328,
"s": 5317,
"text": "Javascript"
},
{
"code": "const LoginSchema = Yup.object().shape({ email: Yup.string() // Format Validation .email(\"Invalid email address format\") // Required Field Validation .required(\"Email is required\"), password: Yup.string() //Minimum Character Validation .min(3, \"Password must be 3 characters at minimum\") .required(\"Password is required\")});",
"e": 5682,
"s": 5328,
"text": null
},
{
"code": null,
"e": 5825,
"s": 5682,
"text": "Step 10: Formik Component after including 3 props namely initialValues, ValidationSchema (to bind Formik and Yup), onSubmit looks like this : "
},
{
"code": null,
"e": 5836,
"s": 5825,
"text": "Javascript"
},
{
"code": "<Formik initialValues={{ email: \"\", password: \"\" }} validationSchema={LoginSchema} onSubmit={(values) => { console.log(values) alert(\"Form is validated! Submitting the form...\");}}>",
"e": 6033,
"s": 5836,
"text": null
},
{
"code": null,
"e": 6178,
"s": 6033,
"text": "The 4 important states of props object are touched, errors , isSubmitting, values which are more than enough to create highly customized forms ."
},
{
"code": null,
"e": 6437,
"s": 6178,
"text": "touched takes boolean values as input and it sets to true if a field is clicked.errors is used to display error messages set by the Yup object.isSubmitting is set to true after we click on submit form.values consist of all field values at that point in time."
},
{
"code": null,
"e": 6518,
"s": 6437,
"text": "touched takes boolean values as input and it sets to true if a field is clicked."
},
{
"code": null,
"e": 6582,
"s": 6518,
"text": "errors is used to display error messages set by the Yup object."
},
{
"code": null,
"e": 6641,
"s": 6582,
"text": "isSubmitting is set to true after we click on submit form."
},
{
"code": null,
"e": 6699,
"s": 6641,
"text": "values consist of all field values at that point in time."
},
{
"code": null,
"e": 6895,
"s": 6699,
"text": "Step 11: Now comes the ErrorMessage Component which we generally use below the Field Component to display the validation generated by Yup. We can add bootstrap class invalid-feedback for styling."
},
{
"code": null,
"e": 6906,
"s": 6895,
"text": "Javascript"
},
{
"code": "<label htmlFor=\"email\">Email</label> <Field type=\"email\" name=\"email\" placeholder=\"Enter email\" autocomplete=\"off\" className={`mt-2 form-control ${touched.email && errors.email ? \"is-invalid\" : \"\"}`} // If there is validation error then // is-invalid bootstrap class is added/> <ErrorMessage component=\"div\" name=\"email\" className=\"invalid-feedback\"/>",
"e": 7280,
"s": 6906,
"text": null
},
{
"code": null,
"e": 7574,
"s": 7280,
"text": "Step 12: We haven’t used isSubmitting prop in the function just yet. We can do one interesting thing using it. We can acknowledge the user who has been logged in and display his username and password using the values parameter on the screen by using conditional rendering and ternary operator."
},
{
"code": null,
"e": 7585,
"s": 7574,
"text": "Javascript"
},
{
"code": "isSubmitting ? (<h1>Login Page</h1>) : (<h1>Confirmation of Login</h1>)// (condition) ? (if true this component gets displayed) : (else this component gets displayed)",
"e": 7768,
"s": 7585,
"text": null
},
{
"code": null,
"e": 7822,
"s": 7768,
"text": "Now we will see the complete code of the above steps."
},
{
"code": null,
"e": 7829,
"s": 7822,
"text": "App.js"
},
{
"code": "import React from \"react\";import { Formik, Form, Field, ErrorMessage } from \"formik\";import * as Yup from \"yup\";import \"bootstrap/dist/css/bootstrap.css\"; const LoginSchema = Yup.object().shape({ email: Yup.string() .email(\"Invalid email address format\") .required(\"Email is required\"), password: Yup.string() .min(3, \"Password must be 3 characters at minimum\") .required(\"Password is required\"),}); class App extends React.Component { render() { return ( <div className=\"container\"> <div className=\"row\"> <div className=\"col-lg-12\"> <Formik initialValues={{ email: \"\", password: \"\" }} validationSchema={LoginSchema} onSubmit={(values) => { console.log(values); alert(\"Form is validated! Submitting the form...\"); }} > {({ touched, errors, isSubmitting, values }) => !isSubmitting ? ( <div> <div className=\"row mb-5\"> <div className=\"col-lg-12 text-center\"> <h1 className=\"mt-5\">Login Form</h1> </div> </div> <Form> <div className=\"form-group\"> <label htmlFor=\"email\">Email</label> <Field type=\"email\" name=\"email\" placeholder=\"Enter email\" autocomplete=\"off\" className={`mt-2 form-control ${touched.email && errors.email ? \"is-invalid\" : \"\"}`} /> <ErrorMessage component=\"div\" name=\"email\" className=\"invalid-feedback\" /> </div> <div className=\"form-group\"> <label htmlFor=\"password\" className=\"mt-3\"> Password </label> <Field type=\"password\" name=\"password\" placeholder=\"Enter password\" className={`mt-2 form-control ${ touched.password && errors.password ? \"is-invalid\" : \"\" }`} /> <ErrorMessage component=\"div\" name=\"password\" className=\"invalid-feedback\" /> </div> <button type=\"submit\" className=\"btn btn-primary btn-block mt-4\" > Submit </button> </Form> </div> ) : ( <div> <h1 className=\"p-3 mt-5\">Form Submitted</h1> <div className=\"alert alert-success mt-3\"> Thank for your connecting with us. Here's what we got from you ! </div> <ul className=\"list-group\"> <li className=\"list-group-item\">Email: {values.email}</li> <li className=\"list-group-item\"> Password: {values.password} </li> </ul> </div> ) } </Formik> </div> </div> </div> ); }} export default App;",
"e": 11620,
"s": 7829,
"text": null
},
{
"code": null,
"e": 11733,
"s": 11620,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 11743,
"s": 11733,
"text": "npm start"
},
{
"code": null,
"e": 11843,
"s": 11743,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output: "
},
{
"code": null,
"e": 11858,
"s": 11843,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 11874,
"s": 11858,
"text": "React-Questions"
},
{
"code": null,
"e": 11884,
"s": 11874,
"text": "Blogathon"
},
{
"code": null,
"e": 11892,
"s": 11884,
"text": "ReactJS"
},
{
"code": null,
"e": 11909,
"s": 11892,
"text": "Web Technologies"
},
{
"code": null,
"e": 12007,
"s": 11909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12048,
"s": 12007,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 12086,
"s": 12048,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 12130,
"s": 12086,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 12190,
"s": 12130,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 12257,
"s": 12190,
"text": "How to toggle password visibility in forms using Bootstrap-icons ?"
},
{
"code": null,
"e": 12300,
"s": 12257,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 12338,
"s": 12300,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 12383,
"s": 12338,
"text": "How to redirect to another page in ReactJS ?"
}
] |
Python Number pow() Method | Python number method pow() returns x to the power of y. If the third argument (z) is given, it returns x to the power of y modulus z, i.e. pow(x, y) % z.
Following is the syntax for pow() method −
import math
math.pow( x, y[, z] )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − number which is to be powered.
x − number which is to be powered.
y − number which is to be powered with x
y − number which is to be powered with x
z − (Optional) number which is to be used for modulus operation
z − (Optional) number which is to be used for modulus operation
This method returns value of xy.
The following example shows the usage of pow() method.
#!/usr/bin/python
import math # This will import math module
print "math.pow(100, 2) : ", math.pow(100, 2)
print "math.pow(100, -2) : ", math.pow(100, -2)
print "math.pow(2, 4) : ", math.pow(2, 4)
print "math.pow(3, 0) : ", math.pow(3, 0)
When we run above program, it produces following result −
math.pow(100, 2) : 10000.0
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0 | [
{
"code": null,
"e": 2533,
"s": 2378,
"text": "Python number method pow() returns x to the power of y. If the third argument (z) is given, it returns x to the power of y modulus z, i.e. pow(x, y) % z."
},
{
"code": null,
"e": 2576,
"s": 2533,
"text": "Following is the syntax for pow() method −"
},
{
"code": null,
"e": 2611,
"s": 2576,
"text": "import math\n\nmath.pow( x, y[, z] )"
},
{
"code": null,
"e": 2758,
"s": 2611,
"text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object."
},
{
"code": null,
"e": 2793,
"s": 2758,
"text": "x − number which is to be powered."
},
{
"code": null,
"e": 2828,
"s": 2793,
"text": "x − number which is to be powered."
},
{
"code": null,
"e": 2869,
"s": 2828,
"text": "y − number which is to be powered with x"
},
{
"code": null,
"e": 2910,
"s": 2869,
"text": "y − number which is to be powered with x"
},
{
"code": null,
"e": 2974,
"s": 2910,
"text": "z − (Optional) number which is to be used for modulus operation"
},
{
"code": null,
"e": 3038,
"s": 2974,
"text": "z − (Optional) number which is to be used for modulus operation"
},
{
"code": null,
"e": 3071,
"s": 3038,
"text": "This method returns value of xy."
},
{
"code": null,
"e": 3126,
"s": 3071,
"text": "The following example shows the usage of pow() method."
},
{
"code": null,
"e": 3368,
"s": 3126,
"text": "#!/usr/bin/python\nimport math # This will import math module\n\nprint \"math.pow(100, 2) : \", math.pow(100, 2)\nprint \"math.pow(100, -2) : \", math.pow(100, -2)\nprint \"math.pow(2, 4) : \", math.pow(2, 4)\nprint \"math.pow(3, 0) : \", math.pow(3, 0)"
},
{
"code": null,
"e": 3426,
"s": 3368,
"text": "When we run above program, it produces following result −"
}
] |
How to create a character vector from data frame values in R? | To create a character vector in R we can enclose the vector values in double quotation marks but if we want to use a data frame values to create a character vector then as.character function can be used. For example, if we have a data frame df then all the values in the df can form a character vector using as.character(df[]).
Live Demo
x1<−letters[1:10]
x2<−letters[11:20]
df1<−data.frame(x1,x2)
df1
x1 x2
1 a k
2 b l
3 c m
4 d n
5 e o
6 f p
7 g q
8 h r
9 i s
10 j t
as.character(df1[])
[1] "c(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\")"
[2] "c(\"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\")"
is.vector(as.character(df1[]))
[1] TRUE
Live Demo
set.seed(3232)
y1<−sample(LETTERS[1:5],20,replace=TRUE)
y2<−sample(LETTERS[6:15],20,replace=TRUE)
y3<−sample(LETTERS[16:26],20,replace=TRUE)
df2<−data.frame(y1,y2,y3)
df2
y1 y2 y3
1 E O U
2 B N U
3 C L P
4 A N Q
5 A I W
6 E M Y
7 E N P
8 B I Z
9 A G Z
10 B J W
11 D L R
12 D G R
13 B M U
14 D K W
15 B F S
16 A O Y
17 D K Z
18 A N Y
19 A O U
20 D K W
as.character(df2[])
[1] "c(\"E\", \"B\", \"C\", \"A\", \"A\", \"E\", \"E\", \"B\", \"A\", \"B\", \"D\", \"D\", \"B\", \"D\", \"B\", \"A\", \"D\", \"A\", \"A\", \"D\")"
[2] "c(\"O\", \"N\", \"L\", \"N\", \"I\", \"M\", \"N\", \"I\", \"G\", \"J\", \"L\", \"G\", \"M\", \"K\", \"F\", \"O\", \"K\", \"N\", \"O\", \"K\")"
[3] "c(\"U\", \"U\", \"P\", \"Q\", \"W\", \"Y\", \"P\", \"Z\", \"Z\", \"W\", \"R\", \"R\", \"U\", \"W\", \"S\", \"Y\", \"Z\", \"Y\", \"U\", \"W\")"
is.vector(as.character(df2[]))
[1] TRUE
Live Demo
z1<−sample(c("Purity","Impurity","Crystal"),20,replace=TRUE)
z2<−sample(c("Chain Reaction","Odorless","Reactive"),20,replace=TRUE)
df3<−data.frame(z1,z2)
df3
z1 z2
1 Impurity Reactive
2 Crystal Reactive
3 Impurity Chain Reaction
4 Purity Chain Reaction
5 Impurity Chain Reaction
6 Crystal Reactive
7 Crystal Chain Reaction
8 Impurity Reactive
9 Purity Odorless
10 Impurity Chain Reaction
11 Purity Odorless
12 Purity Chain Reaction
13 Impurity Odorless
14 Impurity Chain Reaction
15 Impurity Odorless
16 Purity Odorless
17 Impurity Chain Reaction
18 Crystal Reactive
19 Impurity Chain Reaction
20 Crystal Reactive
as.character(df3[])
[1] "c(\"Impurity\", \"Crystal\", \"Impurity\", \"Purity\", \"Impurity\", \"Crystal\", \"Crystal\", \"Impurity\", \"Purity\", \"Impurity\", \"Purity\", \"Purity\", \"Impurity\", \"Impurity\", \"Impurity\", \"Purity\", \"Impurity\", \"Crystal\", \"Impurity\", \"Crystal\")"
[2] "c(\"Reactive\", \"Reactive\", \"Chain Reaction\", \"Chain Reaction\", \"Chain Reaction\", \"Reactive\", \"Chain Reaction\", \"Reactive\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Odorless\", \"Chain Reaction\", \"Reactive\", \"Chain Reaction\", \"Reactive\")"
is.vector(as.character(df3[]))
[1] TRUE | [
{
"code": null,
"e": 1515,
"s": 1187,
"text": "To create a character vector in R we can enclose the vector values in double quotation marks but if we want to use a data frame values to create a character vector then as.character function can be used. For example, if we have a data frame df then all the values in the df can form a character vector using as.character(df[])."
},
{
"code": null,
"e": 1526,
"s": 1515,
"text": " Live Demo"
},
{
"code": null,
"e": 1590,
"s": 1526,
"text": "x1<−letters[1:10]\nx2<−letters[11:20]\ndf1<−data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1873,
"s": 1590,
"text": "x1 x2\n1 a k\n2 b l\n3 c m\n4 d n\n5 e o\n6 f p\n7 g q\n8 h r\n9 i s\n10 j t\nas.character(df1[])\n[1] \"c(\\\"a\\\", \\\"b\\\", \\\"c\\\", \\\"d\\\", \\\"e\\\", \\\"f\\\", \\\"g\\\", \\\"h\\\", \\\"i\\\", \\\"j\\\")\"\n[2] \"c(\\\"k\\\", \\\"l\\\", \\\"m\\\", \\\"n\\\", \\\"o\\\", \\\"p\\\", \\\"q\\\", \\\"r\\\", \\\"s\\\", \\\"t\\\")\"\nis.vector(as.character(df1[]))\n[1] TRUE"
},
{
"code": null,
"e": 1884,
"s": 1873,
"text": " Live Demo"
},
{
"code": null,
"e": 2055,
"s": 1884,
"text": "set.seed(3232)\ny1<−sample(LETTERS[1:5],20,replace=TRUE)\ny2<−sample(LETTERS[6:15],20,replace=TRUE)\ny3<−sample(LETTERS[16:26],20,replace=TRUE)\ndf2<−data.frame(y1,y2,y3)\ndf2"
},
{
"code": null,
"e": 2739,
"s": 2055,
"text": "y1 y2 y3\n1 E O U\n2 B N U\n3 C L P\n4 A N Q\n5 A I W\n6 E M Y\n7 E N P\n8 B I Z\n9 A G Z\n10 B J W\n11 D L R\n12 D G R\n13 B M U\n14 D K W\n15 B F S\n16 A O Y\n17 D K Z\n18 A N Y\n19 A O U\n20 D K W\nas.character(df2[])\n[1] \"c(\\\"E\\\", \\\"B\\\", \\\"C\\\", \\\"A\\\", \\\"A\\\", \\\"E\\\", \\\"E\\\", \\\"B\\\", \\\"A\\\", \\\"B\\\", \\\"D\\\", \\\"D\\\", \\\"B\\\", \\\"D\\\", \\\"B\\\", \\\"A\\\", \\\"D\\\", \\\"A\\\", \\\"A\\\", \\\"D\\\")\"\n[2] \"c(\\\"O\\\", \\\"N\\\", \\\"L\\\", \\\"N\\\", \\\"I\\\", \\\"M\\\", \\\"N\\\", \\\"I\\\", \\\"G\\\", \\\"J\\\", \\\"L\\\", \\\"G\\\", \\\"M\\\", \\\"K\\\", \\\"F\\\", \\\"O\\\", \\\"K\\\", \\\"N\\\", \\\"O\\\", \\\"K\\\")\"\n[3] \"c(\\\"U\\\", \\\"U\\\", \\\"P\\\", \\\"Q\\\", \\\"W\\\", \\\"Y\\\", \\\"P\\\", \\\"Z\\\", \\\"Z\\\", \\\"W\\\", \\\"R\\\", \\\"R\\\", \\\"U\\\", \\\"W\\\", \\\"S\\\", \\\"Y\\\", \\\"Z\\\", \\\"Y\\\", \\\"U\\\", \\\"W\\\")\"\nis.vector(as.character(df2[]))\n[1] TRUE"
},
{
"code": null,
"e": 2750,
"s": 2739,
"text": " Live Demo"
},
{
"code": null,
"e": 2908,
"s": 2750,
"text": "z1<−sample(c(\"Purity\",\"Impurity\",\"Crystal\"),20,replace=TRUE)\nz2<−sample(c(\"Chain Reaction\",\"Odorless\",\"Reactive\"),20,replace=TRUE)\ndf3<−data.frame(z1,z2)\ndf3"
},
{
"code": null,
"e": 4039,
"s": 2908,
"text": "z1 z2\n1 Impurity Reactive\n2 Crystal Reactive\n3 Impurity Chain Reaction\n4 Purity Chain Reaction\n5 Impurity Chain Reaction\n6 Crystal Reactive\n7 Crystal Chain Reaction\n8 Impurity Reactive\n9 Purity Odorless\n10 Impurity Chain Reaction\n11 Purity Odorless\n12 Purity Chain Reaction\n13 Impurity Odorless\n14 Impurity Chain Reaction\n15 Impurity Odorless\n16 Purity Odorless\n17 Impurity Chain Reaction\n18 Crystal Reactive\n19 Impurity Chain Reaction\n20 Crystal Reactive\nas.character(df3[])\n[1] \"c(\\\"Impurity\\\", \\\"Crystal\\\", \\\"Impurity\\\", \\\"Purity\\\", \\\"Impurity\\\", \\\"Crystal\\\", \\\"Crystal\\\", \\\"Impurity\\\", \\\"Purity\\\", \\\"Impurity\\\", \\\"Purity\\\", \\\"Purity\\\", \\\"Impurity\\\", \\\"Impurity\\\", \\\"Impurity\\\", \\\"Purity\\\", \\\"Impurity\\\", \\\"Crystal\\\", \\\"Impurity\\\", \\\"Crystal\\\")\"\n[2] \"c(\\\"Reactive\\\", \\\"Reactive\\\", \\\"Chain Reaction\\\", \\\"Chain Reaction\\\", \\\"Chain Reaction\\\", \\\"Reactive\\\", \\\"Chain Reaction\\\", \\\"Reactive\\\", \\\"Odorless\\\", \\\"Chain Reaction\\\", \\\"Odorless\\\", \\\"Chain Reaction\\\", \\\"Odorless\\\", \\\"Chain Reaction\\\", \\\"Odorless\\\", \\\"Odorless\\\", \\\"Chain Reaction\\\", \\\"Reactive\\\", \\\"Chain Reaction\\\", \\\"Reactive\\\")\"\nis.vector(as.character(df3[]))\n[1] TRUE"
}
] |
fillellipse() function in C | 05 Dec, 2019
The header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse.Syntax :
void fillellipse(int x, int y, int x_radius,
int y_radius);
where,
(x, y) is center of the ellipse.
(x_radius, y_radius) are x and y
radius of ellipse.
Examples :
Input : x = 200, y = 200,
x_radius = 50, y_radius = 90
Output :
Input : x = 300, y = 250,
x_radius = 100, y_radius = 70
Output :
Below is the implementation of fillellipse() function :
// C Implementation for fillellipse()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // fillellipse function fillellipse(200, 200, 50, 90); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}
Output :
Akanksha_Rai
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 229,
"s": 52,
"text": "The header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse.Syntax :"
},
{
"code": null,
"e": 414,
"s": 229,
"text": "void fillellipse(int x, int y, int x_radius,\n int y_radius);\n\nwhere,\n(x, y) is center of the ellipse.\n(x_radius, y_radius) are x and y \nradius of ellipse.\n"
},
{
"code": null,
"e": 425,
"s": 414,
"text": "Examples :"
},
{
"code": null,
"e": 574,
"s": 425,
"text": "Input : x = 200, y = 200,\n x_radius = 50, y_radius = 90\nOutput : \n\nInput : x = 300, y = 250,\n x_radius = 100, y_radius = 70\nOutput : \n"
},
{
"code": null,
"e": 630,
"s": 574,
"text": "Below is the implementation of fillellipse() function :"
},
{
"code": "// C Implementation for fillellipse()#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // fillellipse function fillellipse(200, 200, 50, 90); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}",
"e": 1280,
"s": 630,
"text": null
},
{
"code": null,
"e": 1289,
"s": 1280,
"text": "Output :"
},
{
"code": null,
"e": 1304,
"s": 1291,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1315,
"s": 1304,
"text": "c-graphics"
},
{
"code": null,
"e": 1333,
"s": 1315,
"text": "computer-graphics"
},
{
"code": null,
"e": 1344,
"s": 1333,
"text": "C Language"
}
] |
Program for Worst Fit algorithm in Memory Management | 28 Jun, 2022
Prerequisite : Partition allocation methodsWorst Fit allocates a process to the partition which is largest sufficient among the freely available partitions available in the main memory. If a large process comes at a later stage, then memory will not have space to accommodate it.
Example:
Input : blockSize[] = {100, 500, 200, 300, 600};
processSize[] = {212, 417, 112, 426};
Output:
Process No. Process Size Block no.
1 212 5
2 417 2
3 112 5
4 426 Not Allocated
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Implementation:
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the
maximum block size that can be assigned to
current process i.e., find max(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
it to the current process.
5- If not then leave that process and keep checking
the further processes.
Below is implementation of above steps.
C++
Java
Python3
C#
Javascript
// C++ implementation of worst - Fit algorithm#include<bits/stdc++.h>using namespace std; // Function to allocate memory to blocks as per worst fit// algorithmvoid worstFit(int blockSize[], int m, int processSize[], int n){ // Stores block id of the block allocated to a // process int allocation[n]; // Initially no block is assigned to any process memset(allocation, -1, sizeof(allocation)); // pick each process and find suitable blocks // according to its size ad assign to it for (int i=0; i<n; i++) { // Find the best fit block for current process int wstIdx = -1; for (int j=0; j<m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for current process if (wstIdx != -1) { // allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } cout << "\nProcess No.\tProcess Size\tBlock no.\n"; for (int i = 0; i < n; i++) { cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t"; if (allocation[i] != -1) cout << allocation[i] + 1; else cout << "Not Allocated"; cout << endl; }} // Driver codeint main(){ int blockSize[] = {100, 500, 200, 300, 600}; int processSize[] = {212, 417, 112, 426}; int m = sizeof(blockSize)/sizeof(blockSize[0]); int n = sizeof(processSize)/sizeof(processSize[0]); worstFit(blockSize, m, processSize, n); return 0 ;}
// Java implementation of worst - Fit algorithm public class GFG{ // Method to allocate memory to blocks as per worst fit // algorithm static void worstFit(int blockSize[], int m, int processSize[], int n) { // Stores block id of the block allocated to a // process int allocation[] = new int[n]; // Initially no block is assigned to any process for (int i = 0; i < allocation.length; i++) allocation[i] = -1; // pick each process and find suitable blocks // according to its size ad assign to it for (int i=0; i<n; i++) { // Find the best fit block for current process int wstIdx = -1; for (int j=0; j<m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for current process if (wstIdx != -1) { // allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } System.out.println("\nProcess No.\tProcess Size\tBlock no."); for (int i = 0; i < n; i++) { System.out.print(" " + (i+1) + "\t\t" + processSize[i] + "\t\t"); if (allocation[i] != -1) System.out.print(allocation[i] + 1); else System.out.print("Not Allocated"); System.out.println(); } } // Driver Method public static void main(String[] args) { int blockSize[] = {100, 500, 200, 300, 600}; int processSize[] = {212, 417, 112, 426}; int m = blockSize.length; int n = processSize.length; worstFit(blockSize, m, processSize, n); }}
# Python3 implementation of worst - Fit algorithm # Function to allocate memory to blocks as# per worst fit algorithmdef worstFit(blockSize, m, processSize, n): # Stores block id of the block # allocated to a process # Initially no block is assigned # to any process allocation = [-1] * n # pick each process and find suitable blocks # according to its size ad assign to it for i in range(n): # Find the best fit block for # current process wstIdx = -1 for j in range(m): if blockSize[j] >= processSize[i]: if wstIdx == -1: wstIdx = j elif blockSize[wstIdx] < blockSize[j]: wstIdx = j # If we could find a block for # current process if wstIdx != -1: # allocate block j to p[i] process allocation[i] = wstIdx # Reduce available memory in this block. blockSize[wstIdx] -= processSize[i] print("Process No. Process Size Block no.") for i in range(n): print(i + 1, " ", processSize[i], end = " ") if allocation[i] != -1: print(allocation[i] + 1) else: print("Not Allocated") # Driver codeif __name__ == '__main__': blockSize = [100, 500, 200, 300, 600] processSize = [212, 417, 112, 426] m = len(blockSize) n = len(processSize) worstFit(blockSize, m, processSize, n) # This code is contributed by PranchalK
// C# implementation of worst - Fit algorithmusing System; class GFG{ // Method to allocate memory to blocks // as per worst fit algorithm static void worstFit(int []blockSize, int m, int []processSize, int n) { // Stores block id of the block allocated to a // process int []allocation = new int[n]; // Initially no block is assigned to any process for (int i = 0; i < allocation.Length; i++) allocation[i] = -1; // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Find the best fit block for current process int wstIdx = -1; for (int j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for current process if (wstIdx != -1) { // allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } Console.WriteLine("\nProcess No.\tProcess Size\tBlock no."); for (int i = 0; i < n; i++) { Console.Write(" " + (i+1) + "\t\t\t" + processSize[i] + "\t\t\t"); if (allocation[i] != -1) Console.Write(allocation[i] + 1); else Console.Write("Not Allocated"); Console.WriteLine(); } } // Driver code public static void Main(String[] args) { int []blockSize = {100, 500, 200, 300, 600}; int []processSize = {212, 417, 112, 426}; int m = blockSize.Length; int n = processSize.Length; worstFit(blockSize, m, processSize, n); }} // This code has been contributed by 29AjayKumar
<script> // Javascript implementation of// worst - Fit algorithm // Method to allocate memory to// blocks as per worst fit// algorithmfunction worstFit(blockSize, m, processSize, n){ // Stores block id of the block allocated // to a process let allocation = new Array(n); // Initially no block is assigned // to any process for(let i = 0; i < allocation.length; i++) allocation[i] = -1; // Pick each process and find suitable blocks // according to its size ad assign to it for(let i = 0; i < n; i++) { // Find the best fit block // for current process let wstIdx = -1; for(let j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for // current process if (wstIdx != -1) { // Allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } document.write("<br>Process No. " + " Process Size " + " Block no.<br>"); for(let i = 0; i < n; i++) { document.write(" " + (i + 1) + " " + " " + processSize[i] + " "); if (allocation[i] != -1) document.write(allocation[i] + 1); else document.write("Not Allocated"); document.write("<br>"); }} // Driver codelet blockSize = [ 100, 500, 200, 300, 600 ];let processSize = [ 212, 417, 112, 426 ];let m = blockSize.length;let n = processSize.length; worstFit(blockSize, m, processSize, n); // This code is contributed by rag2127 </script>
Output:
Process No. Process Size Block no.
1 212 5
2 417 2
3 112 5
4 426 Not Allocated
Worst Fit algorithm in Memory Management | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersWorst Fit algorithm in Memory Management | 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:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fQY2FVhDu9k" 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 Sahil Chhabra (akku). 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.
devansh bhatia 1
PranchalKatiyar
29AjayKumar
rag2127
surinderdawra388
clirimfurriku
memory-management
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 332,
"s": 52,
"text": "Prerequisite : Partition allocation methodsWorst Fit allocates a process to the partition which is largest sufficient among the freely available partitions available in the main memory. If a large process comes at a later stage, then memory will not have space to accommodate it."
},
{
"code": null,
"e": 342,
"s": 332,
"text": "Example: "
},
{
"code": null,
"e": 600,
"s": 342,
"text": "Input : blockSize[] = {100, 500, 200, 300, 600};\n processSize[] = {212, 417, 112, 426};\nOutput:\nProcess No. Process Size Block no.\n 1 212 5\n 2 417 2\n 3 112 5\n 4 426 Not Allocated"
},
{
"code": null,
"e": 613,
"s": 604,
"text": "Chapters"
},
{
"code": null,
"e": 640,
"s": 613,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 690,
"s": 640,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 713,
"s": 690,
"text": "captions off, selected"
},
{
"code": null,
"e": 721,
"s": 713,
"text": "English"
},
{
"code": null,
"e": 745,
"s": 721,
"text": "This is a modal window."
},
{
"code": null,
"e": 814,
"s": 745,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 836,
"s": 814,
"text": "End of dialog window."
},
{
"code": null,
"e": 1275,
"s": 836,
"text": "Implementation:\n1- Input memory blocks and processes with sizes.\n2- Initialize all memory blocks as free.\n3- Start by picking each process and find the\n maximum block size that can be assigned to\n current process i.e., find max(bockSize[1], \n blockSize[2],.....blockSize[n]) > \n processSize[current], if found then assign \n it to the current process.\n5- If not then leave that process and keep checking\n the further processes."
},
{
"code": null,
"e": 1316,
"s": 1275,
"text": "Below is implementation of above steps. "
},
{
"code": null,
"e": 1320,
"s": 1316,
"text": "C++"
},
{
"code": null,
"e": 1325,
"s": 1320,
"text": "Java"
},
{
"code": null,
"e": 1333,
"s": 1325,
"text": "Python3"
},
{
"code": null,
"e": 1336,
"s": 1333,
"text": "C#"
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": "Javascript"
},
{
"code": "// C++ implementation of worst - Fit algorithm#include<bits/stdc++.h>using namespace std; // Function to allocate memory to blocks as per worst fit// algorithmvoid worstFit(int blockSize[], int m, int processSize[], int n){ // Stores block id of the block allocated to a // process int allocation[n]; // Initially no block is assigned to any process memset(allocation, -1, sizeof(allocation)); // pick each process and find suitable blocks // according to its size ad assign to it for (int i=0; i<n; i++) { // Find the best fit block for current process int wstIdx = -1; for (int j=0; j<m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for current process if (wstIdx != -1) { // allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } cout << \"\\nProcess No.\\tProcess Size\\tBlock no.\\n\"; for (int i = 0; i < n; i++) { cout << \" \" << i+1 << \"\\t\\t\" << processSize[i] << \"\\t\\t\"; if (allocation[i] != -1) cout << allocation[i] + 1; else cout << \"Not Allocated\"; cout << endl; }} // Driver codeint main(){ int blockSize[] = {100, 500, 200, 300, 600}; int processSize[] = {212, 417, 112, 426}; int m = sizeof(blockSize)/sizeof(blockSize[0]); int n = sizeof(processSize)/sizeof(processSize[0]); worstFit(blockSize, m, processSize, n); return 0 ;}",
"e": 3161,
"s": 1347,
"text": null
},
{
"code": "// Java implementation of worst - Fit algorithm public class GFG{ // Method to allocate memory to blocks as per worst fit // algorithm static void worstFit(int blockSize[], int m, int processSize[], int n) { // Stores block id of the block allocated to a // process int allocation[] = new int[n]; // Initially no block is assigned to any process for (int i = 0; i < allocation.length; i++) allocation[i] = -1; // pick each process and find suitable blocks // according to its size ad assign to it for (int i=0; i<n; i++) { // Find the best fit block for current process int wstIdx = -1; for (int j=0; j<m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for current process if (wstIdx != -1) { // allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } System.out.println(\"\\nProcess No.\\tProcess Size\\tBlock no.\"); for (int i = 0; i < n; i++) { System.out.print(\" \" + (i+1) + \"\\t\\t\" + processSize[i] + \"\\t\\t\"); if (allocation[i] != -1) System.out.print(allocation[i] + 1); else System.out.print(\"Not Allocated\"); System.out.println(); } } // Driver Method public static void main(String[] args) { int blockSize[] = {100, 500, 200, 300, 600}; int processSize[] = {212, 417, 112, 426}; int m = blockSize.length; int n = processSize.length; worstFit(blockSize, m, processSize, n); }}",
"e": 5277,
"s": 3161,
"text": null
},
{
"code": "# Python3 implementation of worst - Fit algorithm # Function to allocate memory to blocks as# per worst fit algorithmdef worstFit(blockSize, m, processSize, n): # Stores block id of the block # allocated to a process # Initially no block is assigned # to any process allocation = [-1] * n # pick each process and find suitable blocks # according to its size ad assign to it for i in range(n): # Find the best fit block for # current process wstIdx = -1 for j in range(m): if blockSize[j] >= processSize[i]: if wstIdx == -1: wstIdx = j elif blockSize[wstIdx] < blockSize[j]: wstIdx = j # If we could find a block for # current process if wstIdx != -1: # allocate block j to p[i] process allocation[i] = wstIdx # Reduce available memory in this block. blockSize[wstIdx] -= processSize[i] print(\"Process No. Process Size Block no.\") for i in range(n): print(i + 1, \" \", processSize[i], end = \" \") if allocation[i] != -1: print(allocation[i] + 1) else: print(\"Not Allocated\") # Driver codeif __name__ == '__main__': blockSize = [100, 500, 200, 300, 600] processSize = [212, 417, 112, 426] m = len(blockSize) n = len(processSize) worstFit(blockSize, m, processSize, n) # This code is contributed by PranchalK",
"e": 6807,
"s": 5277,
"text": null
},
{
"code": "// C# implementation of worst - Fit algorithmusing System; class GFG{ // Method to allocate memory to blocks // as per worst fit algorithm static void worstFit(int []blockSize, int m, int []processSize, int n) { // Stores block id of the block allocated to a // process int []allocation = new int[n]; // Initially no block is assigned to any process for (int i = 0; i < allocation.Length; i++) allocation[i] = -1; // pick each process and find suitable blocks // according to its size ad assign to it for (int i = 0; i < n; i++) { // Find the best fit block for current process int wstIdx = -1; for (int j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for current process if (wstIdx != -1) { // allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } Console.WriteLine(\"\\nProcess No.\\tProcess Size\\tBlock no.\"); for (int i = 0; i < n; i++) { Console.Write(\" \" + (i+1) + \"\\t\\t\\t\" + processSize[i] + \"\\t\\t\\t\"); if (allocation[i] != -1) Console.Write(allocation[i] + 1); else Console.Write(\"Not Allocated\"); Console.WriteLine(); } } // Driver code public static void Main(String[] args) { int []blockSize = {100, 500, 200, 300, 600}; int []processSize = {212, 417, 112, 426}; int m = blockSize.Length; int n = processSize.Length; worstFit(blockSize, m, processSize, n); }} // This code has been contributed by 29AjayKumar",
"e": 8934,
"s": 6807,
"text": null
},
{
"code": "<script> // Javascript implementation of// worst - Fit algorithm // Method to allocate memory to// blocks as per worst fit// algorithmfunction worstFit(blockSize, m, processSize, n){ // Stores block id of the block allocated // to a process let allocation = new Array(n); // Initially no block is assigned // to any process for(let i = 0; i < allocation.length; i++) allocation[i] = -1; // Pick each process and find suitable blocks // according to its size ad assign to it for(let i = 0; i < n; i++) { // Find the best fit block // for current process let wstIdx = -1; for(let j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { if (wstIdx == -1) wstIdx = j; else if (blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } // If we could find a block for // current process if (wstIdx != -1) { // Allocate block j to p[i] process allocation[i] = wstIdx; // Reduce available memory in this block. blockSize[wstIdx] -= processSize[i]; } } document.write(\"<br>Process No. \" + \" Process Size \" + \" Block no.<br>\"); for(let i = 0; i < n; i++) { document.write(\" \" + (i + 1) + \" \" + \" \" + processSize[i] + \" \"); if (allocation[i] != -1) document.write(allocation[i] + 1); else document.write(\"Not Allocated\"); document.write(\"<br>\"); }} // Driver codelet blockSize = [ 100, 500, 200, 300, 600 ];let processSize = [ 212, 417, 112, 426 ];let m = blockSize.length;let n = processSize.length; worstFit(blockSize, m, processSize, n); // This code is contributed by rag2127 </script>",
"e": 10974,
"s": 8934,
"text": null
},
{
"code": null,
"e": 10983,
"s": 10974,
"text": "Output: "
},
{
"code": null,
"e": 11136,
"s": 10983,
"text": "Process No. Process Size Block no.\n 1 212 5\n 2 417 2\n 3 112 5\n 4 426 Not Allocated"
},
{
"code": null,
"e": 12036,
"s": 11138,
"text": "Worst Fit algorithm in Memory Management | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersWorst Fit algorithm in Memory Management | 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:05•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fQY2FVhDu9k\" 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": 12465,
"s": 12036,
"text": "This article is contributed by Sahil Chhabra (akku). 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": 12482,
"s": 12465,
"text": "devansh bhatia 1"
},
{
"code": null,
"e": 12498,
"s": 12482,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 12510,
"s": 12498,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12518,
"s": 12510,
"text": "rag2127"
},
{
"code": null,
"e": 12535,
"s": 12518,
"text": "surinderdawra388"
},
{
"code": null,
"e": 12549,
"s": 12535,
"text": "clirimfurriku"
},
{
"code": null,
"e": 12567,
"s": 12549,
"text": "memory-management"
},
{
"code": null,
"e": 12574,
"s": 12567,
"text": "Greedy"
},
{
"code": null,
"e": 12581,
"s": 12574,
"text": "Greedy"
}
] |
Datetime.replace() Function in Python | 28 Jul, 2021
Datetime.replace() function is used to replace the contents of the DateTime object with the given parameters.
Syntax: Datetime_object.replace(year,month,day,hour,minute,second,microsecond,tzinfo)
Parameters:
year: New year value in range-[1,9999],
month: New month value in range-[1,12],
day: New day value in range-[1,31],
hour: New hour value in range-[24],
minute: New minute value in range-[60],
second: New second value in range-[60],
microsecond: New microsecond value in range-[1000000],
tzinfo: New time zone info.
Returns: It returns the modified datetime object
Note:
In the replace() we can only pass the parameter the DateTime object is already having, replacing a parameter that is not present in the DateTime object will raise an Error
It does not replace the original DateTime object but returns a modified DateTime object
Example 1: Replace the current date’s year with the year 2000.
Python3
# importing the datetime moduleimport datetime # Getting current date using today()# function of the datetime classtodays_date = datetime.date.today()print("Original Date:", todays_date) # Replacing the todays_date year with# 2000 using replace() functionmodified_date = todays_date.replace(year=2000)print("Modified Date:", modified_date)
Output:
Original Date: 2021-07-27
Modified Date: 2000-07-27
Example 2: Replace a parameter that is not present in the datetime object.
Python3
# importing the datetime moduleimport datetime # Getting current date using today()# function of the datetime classtodays_date = datetime.date.today()print("Original Date:", todays_date,) # Trying to replace the todays_date hour# with 3 using replace() functionmodified_date = todays_date.replace(hour=3)print("Modified Date:", modified_date)
Output:
Traceback (most recent call last):
File “/home/6e1aaed34d749f5b15af6dc27ce73a2d.py”, line 9, in <module>
modified_date = todays_date.replace(hour=3)
TypeError: ‘hour’ is an invalid keyword argument for this function
So we observe that we get an error as the hour is not present in the datetime object. Now we will create a datetime object with hour property and try to change it to 03 and we will also change the date to 10.
Python3
# importing the datetime moduleimport datetime # Getting current date and time using now()# function of the datetime classtodays_date = datetime.datetime.now()print("Today's date and time:", todays_date) # Replacing todays_date hour with 3 and day# with 10 using replace() function using hour# and day parametermodified_date = todays_date.replace(day = 10, hour=3)print("Modified date and time:", modified_date)
Output:
Today's date and time: 2021-07-28 09:08:47.563144
Modified date and time: 2021-07-10 03:08:47.563144
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "Datetime.replace() function is used to replace the contents of the DateTime object with the given parameters."
},
{
"code": null,
"e": 224,
"s": 138,
"text": "Syntax: Datetime_object.replace(year,month,day,hour,minute,second,microsecond,tzinfo)"
},
{
"code": null,
"e": 236,
"s": 224,
"text": "Parameters:"
},
{
"code": null,
"e": 276,
"s": 236,
"text": "year: New year value in range-[1,9999],"
},
{
"code": null,
"e": 316,
"s": 276,
"text": "month: New month value in range-[1,12],"
},
{
"code": null,
"e": 352,
"s": 316,
"text": "day: New day value in range-[1,31],"
},
{
"code": null,
"e": 388,
"s": 352,
"text": "hour: New hour value in range-[24],"
},
{
"code": null,
"e": 428,
"s": 388,
"text": "minute: New minute value in range-[60],"
},
{
"code": null,
"e": 468,
"s": 428,
"text": "second: New second value in range-[60],"
},
{
"code": null,
"e": 523,
"s": 468,
"text": "microsecond: New microsecond value in range-[1000000],"
},
{
"code": null,
"e": 551,
"s": 523,
"text": "tzinfo: New time zone info."
},
{
"code": null,
"e": 600,
"s": 551,
"text": "Returns: It returns the modified datetime object"
},
{
"code": null,
"e": 606,
"s": 600,
"text": "Note:"
},
{
"code": null,
"e": 778,
"s": 606,
"text": "In the replace() we can only pass the parameter the DateTime object is already having, replacing a parameter that is not present in the DateTime object will raise an Error"
},
{
"code": null,
"e": 866,
"s": 778,
"text": "It does not replace the original DateTime object but returns a modified DateTime object"
},
{
"code": null,
"e": 929,
"s": 866,
"text": "Example 1: Replace the current date’s year with the year 2000."
},
{
"code": null,
"e": 937,
"s": 929,
"text": "Python3"
},
{
"code": "# importing the datetime moduleimport datetime # Getting current date using today()# function of the datetime classtodays_date = datetime.date.today()print(\"Original Date:\", todays_date) # Replacing the todays_date year with# 2000 using replace() functionmodified_date = todays_date.replace(year=2000)print(\"Modified Date:\", modified_date)",
"e": 1279,
"s": 937,
"text": null
},
{
"code": null,
"e": 1287,
"s": 1279,
"text": "Output:"
},
{
"code": null,
"e": 1339,
"s": 1287,
"text": "Original Date: 2021-07-27\nModified Date: 2000-07-27"
},
{
"code": null,
"e": 1414,
"s": 1339,
"text": "Example 2: Replace a parameter that is not present in the datetime object."
},
{
"code": null,
"e": 1422,
"s": 1414,
"text": "Python3"
},
{
"code": "# importing the datetime moduleimport datetime # Getting current date using today()# function of the datetime classtodays_date = datetime.date.today()print(\"Original Date:\", todays_date,) # Trying to replace the todays_date hour# with 3 using replace() functionmodified_date = todays_date.replace(hour=3)print(\"Modified Date:\", modified_date)",
"e": 1767,
"s": 1422,
"text": null
},
{
"code": null,
"e": 1775,
"s": 1767,
"text": "Output:"
},
{
"code": null,
"e": 1810,
"s": 1775,
"text": "Traceback (most recent call last):"
},
{
"code": null,
"e": 1881,
"s": 1810,
"text": " File “/home/6e1aaed34d749f5b15af6dc27ce73a2d.py”, line 9, in <module>"
},
{
"code": null,
"e": 1928,
"s": 1881,
"text": " modified_date = todays_date.replace(hour=3)"
},
{
"code": null,
"e": 1995,
"s": 1928,
"text": "TypeError: ‘hour’ is an invalid keyword argument for this function"
},
{
"code": null,
"e": 2204,
"s": 1995,
"text": "So we observe that we get an error as the hour is not present in the datetime object. Now we will create a datetime object with hour property and try to change it to 03 and we will also change the date to 10."
},
{
"code": null,
"e": 2212,
"s": 2204,
"text": "Python3"
},
{
"code": "# importing the datetime moduleimport datetime # Getting current date and time using now()# function of the datetime classtodays_date = datetime.datetime.now()print(\"Today's date and time:\", todays_date) # Replacing todays_date hour with 3 and day# with 10 using replace() function using hour# and day parametermodified_date = todays_date.replace(day = 10, hour=3)print(\"Modified date and time:\", modified_date)",
"e": 2626,
"s": 2212,
"text": null
},
{
"code": null,
"e": 2634,
"s": 2626,
"text": "Output:"
},
{
"code": null,
"e": 2735,
"s": 2634,
"text": "Today's date and time: 2021-07-28 09:08:47.563144\nModified date and time: 2021-07-10 03:08:47.563144"
},
{
"code": null,
"e": 2742,
"s": 2735,
"text": "Picked"
},
{
"code": null,
"e": 2758,
"s": 2742,
"text": "Python-datetime"
},
{
"code": null,
"e": 2765,
"s": 2758,
"text": "Python"
},
{
"code": null,
"e": 2863,
"s": 2765,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2895,
"s": 2863,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2922,
"s": 2895,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2943,
"s": 2922,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2966,
"s": 2943,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3022,
"s": 2966,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3053,
"s": 3022,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3095,
"s": 3053,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3137,
"s": 3095,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3176,
"s": 3137,
"text": "Python | Get unique values from a list"
}
] |
Check if a string is palindrome in C using pointers | 25 May, 2022
Given a string. The task is to check if the string is a palindrome or not using pointers. You are not allowed to use any built-in string functions. A string is said to be a palindrome if the reverse of the string is same as the original string. For example, “madam” is palindrome because when the string is reversed same string is achieved, but “Madam” is not a palindrome.
Input: str = "Madam"
Output: String is not a Palindrome.
Input: str = "madam"
Output: String is Palindrome.
Input: str = "radar"
Output: String is Palindrome.
Algorithm:
Take two pointers say, ptr and rev.Initialize ptr to the base address of the string and move it forward to point to the last character of the string.Now, initialize rev to the base address of the string and start moving rev in forward direction and ptr in backward direction simultaneously until middle of the string is reached.If at any point the character pointed by ptr and rev does not match, then break from the loop.Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is palindrome otherwise not.
Take two pointers say, ptr and rev.
Initialize ptr to the base address of the string and move it forward to point to the last character of the string.
Now, initialize rev to the base address of the string and start moving rev in forward direction and ptr in backward direction simultaneously until middle of the string is reached.
If at any point the character pointed by ptr and rev does not match, then break from the loop.
Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is palindrome otherwise not.
Below is the implementation of the above approach:
C
// C program to check if a string is palindrome// using pointers #include <stdio.h> // Function to check if the string is palindrome// using pointersvoid isPalindrome(char* string){ char *ptr, *rev; ptr = string; while (*ptr != '\0') { ++ptr; } --ptr; for (rev = string; ptr >= rev;) { if (*ptr == *rev) { --ptr; rev++; } else break; } if (rev > ptr) printf("String is Palindrome"); else printf("String is not a Palindrome");} // Driver codeint main(){ char str[1000] = "madam"; isPalindrome(str); return 0;}
String is Palindrome
Time Complexity: O(N), where N represents the length of the given string.Auxiliary Space: O(1), no extra space is required, so it is a constant.
samim2000
C-Pointer Basics
C-Pointers
palindrome
C Programs
School Programming
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 426,
"s": 52,
"text": "Given a string. The task is to check if the string is a palindrome or not using pointers. You are not allowed to use any built-in string functions. A string is said to be a palindrome if the reverse of the string is same as the original string. For example, “madam” is palindrome because when the string is reversed same string is achieved, but “Madam” is not a palindrome."
},
{
"code": null,
"e": 587,
"s": 426,
"text": "Input: str = \"Madam\"\nOutput: String is not a Palindrome.\n\nInput: str = \"madam\"\nOutput: String is Palindrome.\n\nInput: str = \"radar\"\nOutput: String is Palindrome."
},
{
"code": null,
"e": 598,
"s": 587,
"text": "Algorithm:"
},
{
"code": null,
"e": 1129,
"s": 598,
"text": "Take two pointers say, ptr and rev.Initialize ptr to the base address of the string and move it forward to point to the last character of the string.Now, initialize rev to the base address of the string and start moving rev in forward direction and ptr in backward direction simultaneously until middle of the string is reached.If at any point the character pointed by ptr and rev does not match, then break from the loop.Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is palindrome otherwise not."
},
{
"code": null,
"e": 1165,
"s": 1129,
"text": "Take two pointers say, ptr and rev."
},
{
"code": null,
"e": 1280,
"s": 1165,
"text": "Initialize ptr to the base address of the string and move it forward to point to the last character of the string."
},
{
"code": null,
"e": 1460,
"s": 1280,
"text": "Now, initialize rev to the base address of the string and start moving rev in forward direction and ptr in backward direction simultaneously until middle of the string is reached."
},
{
"code": null,
"e": 1555,
"s": 1460,
"text": "If at any point the character pointed by ptr and rev does not match, then break from the loop."
},
{
"code": null,
"e": 1664,
"s": 1555,
"text": "Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is palindrome otherwise not."
},
{
"code": null,
"e": 1716,
"s": 1664,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1718,
"s": 1716,
"text": "C"
},
{
"code": "// C program to check if a string is palindrome// using pointers #include <stdio.h> // Function to check if the string is palindrome// using pointersvoid isPalindrome(char* string){ char *ptr, *rev; ptr = string; while (*ptr != '\\0') { ++ptr; } --ptr; for (rev = string; ptr >= rev;) { if (*ptr == *rev) { --ptr; rev++; } else break; } if (rev > ptr) printf(\"String is Palindrome\"); else printf(\"String is not a Palindrome\");} // Driver codeint main(){ char str[1000] = \"madam\"; isPalindrome(str); return 0;}",
"e": 2344,
"s": 1718,
"text": null
},
{
"code": null,
"e": 2365,
"s": 2344,
"text": "String is Palindrome"
},
{
"code": null,
"e": 2510,
"s": 2365,
"text": "Time Complexity: O(N), where N represents the length of the given string.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 2520,
"s": 2510,
"text": "samim2000"
},
{
"code": null,
"e": 2537,
"s": 2520,
"text": "C-Pointer Basics"
},
{
"code": null,
"e": 2548,
"s": 2537,
"text": "C-Pointers"
},
{
"code": null,
"e": 2559,
"s": 2548,
"text": "palindrome"
},
{
"code": null,
"e": 2570,
"s": 2559,
"text": "C Programs"
},
{
"code": null,
"e": 2589,
"s": 2570,
"text": "School Programming"
},
{
"code": null,
"e": 2597,
"s": 2589,
"text": "Strings"
},
{
"code": null,
"e": 2605,
"s": 2597,
"text": "Strings"
},
{
"code": null,
"e": 2616,
"s": 2605,
"text": "palindrome"
},
{
"code": null,
"e": 2714,
"s": 2616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2749,
"s": 2714,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2790,
"s": 2749,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 2849,
"s": 2790,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 2883,
"s": 2849,
"text": "C++ Program to check Prime Number"
},
{
"code": null,
"e": 2914,
"s": 2883,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 2932,
"s": 2914,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2957,
"s": 2932,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 2973,
"s": 2957,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 2996,
"s": 2973,
"text": "Introduction To PYTHON"
}
] |
Java.util.Objects class in Java | 13 Nov, 2017
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
Using Objects class methods, one can smartly handle NullPointerException and can also show customized NullPointerException message(if an Exception occur).
String toString(Object o) : This method returns the result of calling toString() method for a non-null argument and “null” for a null argument.Syntax :
public static String toString(Object o)
Parameters :
o - an object
Returns :
the result of calling toString() method for a non-null argument and
"null" for a null argument
String toString(Object o, String nullDefault) : This method is overloaded version of above method. It returns the result of calling toString() method on the first argument if the first argument is not null and returns the second argument otherwise.Syntax :
public static String toString(Object o, String nullDefault)
Parameters :
o - an object
nullDefault - string to return if the first argument is null
Returns :
the result of calling toString() method on the first argument if it is not null and
the second argument otherwise.
// Java program to demonstrate Objects.toString(Object o) // and Objects.toString(Object o, String nullDefault) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "Pair {key = " + Objects.toString(key) + ", value = " + Objects.toString(value, "no value") + "}"; /* without Objects.toString(Object o) and Objects.toString(Object o, String nullDefault) method return "Pair {key = " + (key == null ? "null" : key.toString()) + ", value = " + (value == null ? "no value" : value.toString()) + "}"; */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); System.out.println(p1); System.out.println(p2); }}Output:Pair {key = GFG, value = geeksforgeeks.org}
Pair {key = Code, value = no value}
boolean equals(Object a,Object b) : This method true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax :
public static boolean equals(Object a,Object b)
Parameters :
a - an object
b - an object to be compared with a for equality
Returns :
true if the arguments are equal to each other and false otherwise
// Java program to demonstrate equals(Object a, Object b) method import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.key, key) && Objects.equals(p.value, value); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p3 = new Pair<String, String>("GFG", "www.geeksforgeeks.org"); System.out.println(p1.equals(p2)); System.out.println(p2.equals(p3)); }}Output:true
false
boolean deepEquals(Object a,Object b) :This method returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.Syntax :
public static boolean deepEquals(Object a,Object b)
Parameters :
a - an object
b - an object to be compared with a for equality
Returns :
true if the arguments are deeply equals to each other and false otherwise
T requireNonNull(T obj) : This method checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated in below example:Syntax :
public static T requireNonNull(T obj)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
Returns :
obj if not null
Throws:
NullPointerException - if obj is null
T requireNonNull(T obj,String message) : This method is overloaded version of above method with customized message printing if obj is null as demonstrated in below example:Syntax :
public static T requireNonNull(T obj,String message)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
message - detail message to be used in the event that a NullPointerException is thrown
Returns :
obj if not null
Throws:
NullPointerException - if obj is null
// Java program to demonstrate Objects.requireNonNull(Object o) // and Objects.requireNonNull(Object o, String message) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = Objects.requireNonNull(key); } public void setValue(V value) { this.value = Objects.requireNonNull(value, "no value"); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); p1.setKey("Geeks"); // below statement will throw NPE with customized message p1.setValue(null); }}Output:Exception in thread "main" java.lang.NullPointerException: no value
at java.util.Objects.requireNonNull(Objects.java:228)
at Pair.setValue(GFG.java:22)
at GFG.main(GFG.java:36)
int hashCode(Object o) : This method returns the hash code of a non-null argument and 0 for a null argument.Syntax :
public static int hashCode(Object o)
Parameters :
o - an object
Returns :
the hash code of a non-null argument and 0 for a null argument
// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hashCode(key) ^ Objects.hashCode(value)); /* without Objects.hashCode(Object o) method return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:450903651
2105869
0
int hash(Object... values) : This method generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]).This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x, y, and z, one could write:@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
Note: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object).Syntax :
public static int hash(Object... values)
Parameters :
values - the values to be hashed
Returns :
a hash value of the sequence of input values
// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hash(key,value)); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:453150372
65282900
961
int compare(T a,T b,Comparator c) : As usual, this method returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned.Note that if one of the arguments is null, a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.Syntax :
public static int compare(T a,T b,Comparator c)
Type Parameters:
T - the type of the objects being compared
Parameters :
a - an object
b - an object to be compared with a
c - the Comparator to compare the first two arguments
Returns :
0 if the arguments are identical and c.compare(a, b) otherwise.
String toString(Object o) : This method returns the result of calling toString() method for a non-null argument and “null” for a null argument.Syntax :
public static String toString(Object o)
Parameters :
o - an object
Returns :
the result of calling toString() method for a non-null argument and
"null" for a null argument
Syntax :
public static String toString(Object o)
Parameters :
o - an object
Returns :
the result of calling toString() method for a non-null argument and
"null" for a null argument
String toString(Object o, String nullDefault) : This method is overloaded version of above method. It returns the result of calling toString() method on the first argument if the first argument is not null and returns the second argument otherwise.Syntax :
public static String toString(Object o, String nullDefault)
Parameters :
o - an object
nullDefault - string to return if the first argument is null
Returns :
the result of calling toString() method on the first argument if it is not null and
the second argument otherwise.
// Java program to demonstrate Objects.toString(Object o) // and Objects.toString(Object o, String nullDefault) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "Pair {key = " + Objects.toString(key) + ", value = " + Objects.toString(value, "no value") + "}"; /* without Objects.toString(Object o) and Objects.toString(Object o, String nullDefault) method return "Pair {key = " + (key == null ? "null" : key.toString()) + ", value = " + (value == null ? "no value" : value.toString()) + "}"; */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); System.out.println(p1); System.out.println(p2); }}Output:Pair {key = GFG, value = geeksforgeeks.org}
Pair {key = Code, value = no value}
Syntax :
public static String toString(Object o, String nullDefault)
Parameters :
o - an object
nullDefault - string to return if the first argument is null
Returns :
the result of calling toString() method on the first argument if it is not null and
the second argument otherwise.
// Java program to demonstrate Objects.toString(Object o) // and Objects.toString(Object o, String nullDefault) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return "Pair {key = " + Objects.toString(key) + ", value = " + Objects.toString(value, "no value") + "}"; /* without Objects.toString(Object o) and Objects.toString(Object o, String nullDefault) method return "Pair {key = " + (key == null ? "null" : key.toString()) + ", value = " + (value == null ? "no value" : value.toString()) + "}"; */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); System.out.println(p1); System.out.println(p2); }}
Output:
Pair {key = GFG, value = geeksforgeeks.org}
Pair {key = Code, value = no value}
boolean equals(Object a,Object b) : This method true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax :
public static boolean equals(Object a,Object b)
Parameters :
a - an object
b - an object to be compared with a for equality
Returns :
true if the arguments are equal to each other and false otherwise
// Java program to demonstrate equals(Object a, Object b) method import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.key, key) && Objects.equals(p.value, value); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p3 = new Pair<String, String>("GFG", "www.geeksforgeeks.org"); System.out.println(p1.equals(p2)); System.out.println(p2.equals(p3)); }}Output:true
false
Syntax :
public static boolean equals(Object a,Object b)
Parameters :
a - an object
b - an object to be compared with a for equality
Returns :
true if the arguments are equal to each other and false otherwise
// Java program to demonstrate equals(Object a, Object b) method import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.key, key) && Objects.equals(p.value, value); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p3 = new Pair<String, String>("GFG", "www.geeksforgeeks.org"); System.out.println(p1.equals(p2)); System.out.println(p2.equals(p3)); }}
Output:
true
false
boolean deepEquals(Object a,Object b) :This method returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.Syntax :
public static boolean deepEquals(Object a,Object b)
Parameters :
a - an object
b - an object to be compared with a for equality
Returns :
true if the arguments are deeply equals to each other and false otherwise
Syntax :
public static boolean deepEquals(Object a,Object b)
Parameters :
a - an object
b - an object to be compared with a for equality
Returns :
true if the arguments are deeply equals to each other and false otherwise
T requireNonNull(T obj) : This method checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated in below example:Syntax :
public static T requireNonNull(T obj)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
Returns :
obj if not null
Throws:
NullPointerException - if obj is null
Syntax :
public static T requireNonNull(T obj)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
Returns :
obj if not null
Throws:
NullPointerException - if obj is null
T requireNonNull(T obj,String message) : This method is overloaded version of above method with customized message printing if obj is null as demonstrated in below example:Syntax :
public static T requireNonNull(T obj,String message)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
message - detail message to be used in the event that a NullPointerException is thrown
Returns :
obj if not null
Throws:
NullPointerException - if obj is null
// Java program to demonstrate Objects.requireNonNull(Object o) // and Objects.requireNonNull(Object o, String message) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = Objects.requireNonNull(key); } public void setValue(V value) { this.value = Objects.requireNonNull(value, "no value"); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); p1.setKey("Geeks"); // below statement will throw NPE with customized message p1.setValue(null); }}Output:Exception in thread "main" java.lang.NullPointerException: no value
at java.util.Objects.requireNonNull(Objects.java:228)
at Pair.setValue(GFG.java:22)
at GFG.main(GFG.java:36)
Syntax :
public static T requireNonNull(T obj,String message)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
message - detail message to be used in the event that a NullPointerException is thrown
Returns :
obj if not null
Throws:
NullPointerException - if obj is null
// Java program to demonstrate Objects.requireNonNull(Object o) // and Objects.requireNonNull(Object o, String message) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = Objects.requireNonNull(key); } public void setValue(V value) { this.value = Objects.requireNonNull(value, "no value"); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); p1.setKey("Geeks"); // below statement will throw NPE with customized message p1.setValue(null); }}
Output:
Exception in thread "main" java.lang.NullPointerException: no value
at java.util.Objects.requireNonNull(Objects.java:228)
at Pair.setValue(GFG.java:22)
at GFG.main(GFG.java:36)
int hashCode(Object o) : This method returns the hash code of a non-null argument and 0 for a null argument.Syntax :
public static int hashCode(Object o)
Parameters :
o - an object
Returns :
the hash code of a non-null argument and 0 for a null argument
// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hashCode(key) ^ Objects.hashCode(value)); /* without Objects.hashCode(Object o) method return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:450903651
2105869
0
Syntax :
public static int hashCode(Object o)
Parameters :
o - an object
Returns :
the hash code of a non-null argument and 0 for a null argument
// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hashCode(key) ^ Objects.hashCode(value)); /* without Objects.hashCode(Object o) method return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}
Output:
450903651
2105869
0
int hash(Object... values) : This method generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]).This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x, y, and z, one could write:@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
Note: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object).Syntax :
public static int hash(Object... values)
Parameters :
values - the values to be hashed
Returns :
a hash value of the sequence of input values
// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hash(key,value)); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:453150372
65282900
961
@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
Note: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object).
Syntax :
public static int hash(Object... values)
Parameters :
values - the values to be hashed
Returns :
a hash value of the sequence of input values
// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hash(key,value)); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>("GFG", "geeksforgeeks.org"); Pair<String, String> p2 = new Pair<String, String>("Code", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}
Output:
453150372
65282900
961
int compare(T a,T b,Comparator c) : As usual, this method returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned.Note that if one of the arguments is null, a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.Syntax :
public static int compare(T a,T b,Comparator c)
Type Parameters:
T - the type of the objects being compared
Parameters :
a - an object
b - an object to be compared with a
c - the Comparator to compare the first two arguments
Returns :
0 if the arguments are identical and c.compare(a, b) otherwise.
Note that if one of the arguments is null, a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.
Syntax :
public static int compare(T a,T b,Comparator c)
Type Parameters:
T - the type of the objects being compared
Parameters :
a - an object
b - an object to be compared with a
c - the Comparator to compare the first two arguments
Returns :
0 if the arguments are identical and c.compare(a, b) otherwise.
Note : In Java 8, Objects class has 3 more methods. Two of them(isNull(Object o) and nonNull(Object o)) are used for checking null reference. The third one is one more overloaded version of requireNonNull method. Refer here.
Java - util package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Nov, 2017"
},
{
"code": null,
"e": 304,
"s": 54,
"text": "Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects."
},
{
"code": null,
"e": 459,
"s": 304,
"text": "Using Objects class methods, one can smartly handle NullPointerException and can also show customized NullPointerException message(if an Exception occur)."
},
{
"code": null,
"e": 10160,
"s": 459,
"text": "String toString(Object o) : This method returns the result of calling toString() method for a non-null argument and “null” for a null argument.Syntax : \npublic static String toString(Object o)\nParameters : \no - an object\nReturns :\nthe result of calling toString() method for a non-null argument and \n\"null\" for a null argument\nString toString(Object o, String nullDefault) : This method is overloaded version of above method. It returns the result of calling toString() method on the first argument if the first argument is not null and returns the second argument otherwise.Syntax : \npublic static String toString(Object o, String nullDefault)\nParameters : \no - an object\nnullDefault - string to return if the first argument is null\nReturns :\nthe result of calling toString() method on the first argument if it is not null and\nthe second argument otherwise.\n// Java program to demonstrate Objects.toString(Object o) // and Objects.toString(Object o, String nullDefault) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return \"Pair {key = \" + Objects.toString(key) + \", value = \" + Objects.toString(value, \"no value\") + \"}\"; /* without Objects.toString(Object o) and Objects.toString(Object o, String nullDefault) method return \"Pair {key = \" + (key == null ? \"null\" : key.toString()) + \", value = \" + (value == null ? \"no value\" : value.toString()) + \"}\"; */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); System.out.println(p1); System.out.println(p2); }}Output:Pair {key = GFG, value = geeksforgeeks.org}\nPair {key = Code, value = no value}\nboolean equals(Object a,Object b) : This method true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax : \npublic static boolean equals(Object a,Object b)\nParameters : \na - an object\nb - an object to be compared with a for equality\nReturns :\ntrue if the arguments are equal to each other and false otherwise\n// Java program to demonstrate equals(Object a, Object b) method import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.key, key) && Objects.equals(p.value, value); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p3 = new Pair<String, String>(\"GFG\", \"www.geeksforgeeks.org\"); System.out.println(p1.equals(p2)); System.out.println(p2.equals(p3)); }}Output:true\nfalse\nboolean deepEquals(Object a,Object b) :This method returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.Syntax : \npublic static boolean deepEquals(Object a,Object b)\nParameters : \na - an object\nb - an object to be compared with a for equality\nReturns :\ntrue if the arguments are deeply equals to each other and false otherwise\nT requireNonNull(T obj) : This method checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated in below example:Syntax : \npublic static T requireNonNull(T obj)\nType Parameters:\nT - the type of the reference\nParameters : \nobj - the object reference to check for nullity\nReturns :\nobj if not null\nThrows:\nNullPointerException - if obj is null\nT requireNonNull(T obj,String message) : This method is overloaded version of above method with customized message printing if obj is null as demonstrated in below example:Syntax : \npublic static T requireNonNull(T obj,String message)\nType Parameters:\nT - the type of the reference\nParameters : \nobj - the object reference to check for nullity\nmessage - detail message to be used in the event that a NullPointerException is thrown\nReturns :\nobj if not null\nThrows:\nNullPointerException - if obj is null\n// Java program to demonstrate Objects.requireNonNull(Object o) // and Objects.requireNonNull(Object o, String message) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = Objects.requireNonNull(key); } public void setValue(V value) { this.value = Objects.requireNonNull(value, \"no value\"); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); p1.setKey(\"Geeks\"); // below statement will throw NPE with customized message p1.setValue(null); }}Output:Exception in thread \"main\" java.lang.NullPointerException: no value\n at java.util.Objects.requireNonNull(Objects.java:228)\n at Pair.setValue(GFG.java:22)\n at GFG.main(GFG.java:36)\nint hashCode(Object o) : This method returns the hash code of a non-null argument and 0 for a null argument.Syntax : \npublic static int hashCode(Object o)\nParameters : \no - an object\nReturns :\nthe hash code of a non-null argument and 0 for a null argument\n// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hashCode(key) ^ Objects.hashCode(value)); /* without Objects.hashCode(Object o) method return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:450903651\n2105869\n0\nint hash(Object... values) : This method generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]).This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x, y, and z, one could write:@Override \npublic int hashCode() {\n return Objects.hash(x, y, z);\n}\nNote: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object).Syntax : \npublic static int hash(Object... values)\nParameters : \nvalues - the values to be hashed\nReturns :\na hash value of the sequence of input values\n// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hash(key,value)); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:453150372\n65282900\n961\nint compare(T a,T b,Comparator c) : As usual, this method returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned.Note that if one of the arguments is null, a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.Syntax : \npublic static int compare(T a,T b,Comparator c)\nType Parameters:\nT - the type of the objects being compared\nParameters : \na - an object\nb - an object to be compared with a\nc - the Comparator to compare the first two arguments\nReturns :\n0 if the arguments are identical and c.compare(a, b) otherwise.\n"
},
{
"code": null,
"e": 10488,
"s": 10160,
"text": "String toString(Object o) : This method returns the result of calling toString() method for a non-null argument and “null” for a null argument.Syntax : \npublic static String toString(Object o)\nParameters : \no - an object\nReturns :\nthe result of calling toString() method for a non-null argument and \n\"null\" for a null argument\n"
},
{
"code": null,
"e": 10673,
"s": 10488,
"text": "Syntax : \npublic static String toString(Object o)\nParameters : \no - an object\nReturns :\nthe result of calling toString() method for a non-null argument and \n\"null\" for a null argument\n"
},
{
"code": null,
"e": 12373,
"s": 10673,
"text": "String toString(Object o, String nullDefault) : This method is overloaded version of above method. It returns the result of calling toString() method on the first argument if the first argument is not null and returns the second argument otherwise.Syntax : \npublic static String toString(Object o, String nullDefault)\nParameters : \no - an object\nnullDefault - string to return if the first argument is null\nReturns :\nthe result of calling toString() method on the first argument if it is not null and\nthe second argument otherwise.\n// Java program to demonstrate Objects.toString(Object o) // and Objects.toString(Object o, String nullDefault) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return \"Pair {key = \" + Objects.toString(key) + \", value = \" + Objects.toString(value, \"no value\") + \"}\"; /* without Objects.toString(Object o) and Objects.toString(Object o, String nullDefault) method return \"Pair {key = \" + (key == null ? \"null\" : key.toString()) + \", value = \" + (value == null ? \"no value\" : value.toString()) + \"}\"; */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); System.out.println(p1); System.out.println(p2); }}Output:Pair {key = GFG, value = geeksforgeeks.org}\nPair {key = Code, value = no value}\n"
},
{
"code": null,
"e": 12658,
"s": 12373,
"text": "Syntax : \npublic static String toString(Object o, String nullDefault)\nParameters : \no - an object\nnullDefault - string to return if the first argument is null\nReturns :\nthe result of calling toString() method on the first argument if it is not null and\nthe second argument otherwise.\n"
},
{
"code": "// Java program to demonstrate Objects.toString(Object o) // and Objects.toString(Object o, String nullDefault) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public String toString() { return \"Pair {key = \" + Objects.toString(key) + \", value = \" + Objects.toString(value, \"no value\") + \"}\"; /* without Objects.toString(Object o) and Objects.toString(Object o, String nullDefault) method return \"Pair {key = \" + (key == null ? \"null\" : key.toString()) + \", value = \" + (value == null ? \"no value\" : value.toString()) + \"}\"; */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); System.out.println(p1); System.out.println(p2); }}",
"e": 13739,
"s": 12658,
"text": null
},
{
"code": null,
"e": 13747,
"s": 13739,
"text": "Output:"
},
{
"code": null,
"e": 13828,
"s": 13747,
"text": "Pair {key = GFG, value = geeksforgeeks.org}\nPair {key = Code, value = no value}\n"
},
{
"code": null,
"e": 15371,
"s": 13828,
"text": "boolean equals(Object a,Object b) : This method true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.Syntax : \npublic static boolean equals(Object a,Object b)\nParameters : \na - an object\nb - an object to be compared with a for equality\nReturns :\ntrue if the arguments are equal to each other and false otherwise\n// Java program to demonstrate equals(Object a, Object b) method import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.key, key) && Objects.equals(p.value, value); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p3 = new Pair<String, String>(\"GFG\", \"www.geeksforgeeks.org\"); System.out.println(p1.equals(p2)); System.out.println(p2.equals(p3)); }}Output:true\nfalse\n"
},
{
"code": null,
"e": 15583,
"s": 15371,
"text": "Syntax : \npublic static boolean equals(Object a,Object b)\nParameters : \na - an object\nb - an object to be compared with a for equality\nReturns :\ntrue if the arguments are equal to each other and false otherwise\n"
},
{
"code": "// Java program to demonstrate equals(Object a, Object b) method import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.key, key) && Objects.equals(p.value, value); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p3 = new Pair<String, String>(\"GFG\", \"www.geeksforgeeks.org\"); System.out.println(p1.equals(p2)); System.out.println(p2.equals(p3)); }}",
"e": 16582,
"s": 15583,
"text": null
},
{
"code": null,
"e": 16590,
"s": 16582,
"text": "Output:"
},
{
"code": null,
"e": 16602,
"s": 16590,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 17172,
"s": 16602,
"text": "boolean deepEquals(Object a,Object b) :This method returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.Syntax : \npublic static boolean deepEquals(Object a,Object b)\nParameters : \na - an object\nb - an object to be compared with a for equality\nReturns :\ntrue if the arguments are deeply equals to each other and false otherwise\n"
},
{
"code": null,
"e": 17396,
"s": 17172,
"text": "Syntax : \npublic static boolean deepEquals(Object a,Object b)\nParameters : \na - an object\nb - an object to be compared with a for equality\nReturns :\ntrue if the arguments are deeply equals to each other and false otherwise\n"
},
{
"code": null,
"e": 17848,
"s": 17396,
"text": "T requireNonNull(T obj) : This method checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated in below example:Syntax : \npublic static T requireNonNull(T obj)\nType Parameters:\nT - the type of the reference\nParameters : \nobj - the object reference to check for nullity\nReturns :\nobj if not null\nThrows:\nNullPointerException - if obj is null\n"
},
{
"code": null,
"e": 18079,
"s": 17848,
"text": "Syntax : \npublic static T requireNonNull(T obj)\nType Parameters:\nT - the type of the reference\nParameters : \nobj - the object reference to check for nullity\nReturns :\nobj if not null\nThrows:\nNullPointerException - if obj is null\n"
},
{
"code": null,
"e": 19600,
"s": 18079,
"text": "T requireNonNull(T obj,String message) : This method is overloaded version of above method with customized message printing if obj is null as demonstrated in below example:Syntax : \npublic static T requireNonNull(T obj,String message)\nType Parameters:\nT - the type of the reference\nParameters : \nobj - the object reference to check for nullity\nmessage - detail message to be used in the event that a NullPointerException is thrown\nReturns :\nobj if not null\nThrows:\nNullPointerException - if obj is null\n// Java program to demonstrate Objects.requireNonNull(Object o) // and Objects.requireNonNull(Object o, String message) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = Objects.requireNonNull(key); } public void setValue(V value) { this.value = Objects.requireNonNull(value, \"no value\"); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); p1.setKey(\"Geeks\"); // below statement will throw NPE with customized message p1.setValue(null); }}Output:Exception in thread \"main\" java.lang.NullPointerException: no value\n at java.util.Objects.requireNonNull(Objects.java:228)\n at Pair.setValue(GFG.java:22)\n at GFG.main(GFG.java:36)\n"
},
{
"code": null,
"e": 19933,
"s": 19600,
"text": "Syntax : \npublic static T requireNonNull(T obj,String message)\nType Parameters:\nT - the type of the reference\nParameters : \nobj - the object reference to check for nullity\nmessage - detail message to be used in the event that a NullPointerException is thrown\nReturns :\nobj if not null\nThrows:\nNullPointerException - if obj is null\n"
},
{
"code": "// Java program to demonstrate Objects.requireNonNull(Object o) // and Objects.requireNonNull(Object o, String message) methods import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = Objects.requireNonNull(key); } public void setValue(V value) { this.value = Objects.requireNonNull(value, \"no value\"); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); p1.setKey(\"Geeks\"); // below statement will throw NPE with customized message p1.setValue(null); }}",
"e": 20754,
"s": 19933,
"text": null
},
{
"code": null,
"e": 20762,
"s": 20754,
"text": "Output:"
},
{
"code": null,
"e": 20952,
"s": 20762,
"text": "Exception in thread \"main\" java.lang.NullPointerException: no value\n at java.util.Objects.requireNonNull(Objects.java:228)\n at Pair.setValue(GFG.java:22)\n at GFG.main(GFG.java:36)\n"
},
{
"code": null,
"e": 22222,
"s": 20952,
"text": "int hashCode(Object o) : This method returns the hash code of a non-null argument and 0 for a null argument.Syntax : \npublic static int hashCode(Object o)\nParameters : \no - an object\nReturns :\nthe hash code of a non-null argument and 0 for a null argument\n// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hashCode(key) ^ Objects.hashCode(value)); /* without Objects.hashCode(Object o) method return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:450903651\n2105869\n0\n"
},
{
"code": null,
"e": 22371,
"s": 22222,
"text": "Syntax : \npublic static int hashCode(Object o)\nParameters : \no - an object\nReturns :\nthe hash code of a non-null argument and 0 for a null argument\n"
},
{
"code": "// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hashCode(key) ^ Objects.hashCode(value)); /* without Objects.hashCode(Object o) method return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); */ }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}",
"e": 23358,
"s": 22371,
"text": null
},
{
"code": null,
"e": 23366,
"s": 23358,
"text": "Output:"
},
{
"code": null,
"e": 23387,
"s": 23366,
"text": "450903651\n2105869\n0\n"
},
{
"code": null,
"e": 25034,
"s": 23387,
"text": "int hash(Object... values) : This method generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]).This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x, y, and z, one could write:@Override \npublic int hashCode() {\n return Objects.hash(x, y, z);\n}\nNote: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object).Syntax : \npublic static int hash(Object... values)\nParameters : \nvalues - the values to be hashed\nReturns :\na hash value of the sequence of input values\n// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hash(key,value)); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}Output:453150372\n65282900\n961\n"
},
{
"code": null,
"e": 25107,
"s": 25034,
"text": "@Override \npublic int hashCode() {\n return Objects.hash(x, y, z);\n}\n"
},
{
"code": null,
"e": 25287,
"s": 25107,
"text": "Note: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object)."
},
{
"code": null,
"e": 25441,
"s": 25287,
"text": "Syntax : \npublic static int hash(Object... values)\nParameters : \nvalues - the values to be hashed\nReturns :\na hash value of the sequence of input values\n"
},
{
"code": "// Java program to demonstrate Objects.hashCode(Object o) object import java.util.Objects; class Pair<K, V> { public K key; public V value; public Pair(K key, V value) { this.key = key; this.value = value; } @Override public int hashCode() { return (Objects.hash(key,value)); }} class GFG{ public static void main(String[] args) { Pair<String, String> p1 = new Pair<String, String>(\"GFG\", \"geeksforgeeks.org\"); Pair<String, String> p2 = new Pair<String, String>(\"Code\", null); Pair<String, String> p3 = new Pair<String, String>(null, null); System.out.println(p1.hashCode()); System.out.println(p2.hashCode()); System.out.println(p3.hashCode()); }}",
"e": 26240,
"s": 25441,
"text": null
},
{
"code": null,
"e": 26248,
"s": 26240,
"text": "Output:"
},
{
"code": null,
"e": 26272,
"s": 26248,
"text": "453150372\n65282900\n961\n"
},
{
"code": null,
"e": 26950,
"s": 26272,
"text": "int compare(T a,T b,Comparator c) : As usual, this method returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned.Note that if one of the arguments is null, a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.Syntax : \npublic static int compare(T a,T b,Comparator c)\nType Parameters:\nT - the type of the objects being compared\nParameters : \na - an object\nb - an object to be compared with a\nc - the Comparator to compare the first two arguments\nReturns :\n0 if the arguments are identical and c.compare(a, b) otherwise.\n"
},
{
"code": null,
"e": 27132,
"s": 26950,
"text": "Note that if one of the arguments is null, a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values."
},
{
"code": null,
"e": 27444,
"s": 27132,
"text": "Syntax : \npublic static int compare(T a,T b,Comparator c)\nType Parameters:\nT - the type of the objects being compared\nParameters : \na - an object\nb - an object to be compared with a\nc - the Comparator to compare the first two arguments\nReturns :\n0 if the arguments are identical and c.compare(a, b) otherwise.\n"
},
{
"code": null,
"e": 27669,
"s": 27444,
"text": "Note : In Java 8, Objects class has 3 more methods. Two of them(isNull(Object o) and nonNull(Object o)) are used for checking null reference. The third one is one more overloaded version of requireNonNull method. Refer here."
},
{
"code": null,
"e": 27689,
"s": 27669,
"text": "Java - util package"
},
{
"code": null,
"e": 27694,
"s": 27689,
"text": "Java"
},
{
"code": null,
"e": 27699,
"s": 27694,
"text": "Java"
},
{
"code": null,
"e": 27797,
"s": 27699,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27812,
"s": 27797,
"text": "Arrays in Java"
},
{
"code": null,
"e": 27856,
"s": 27812,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 27892,
"s": 27856,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 27917,
"s": 27892,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27968,
"s": 27917,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27990,
"s": 27968,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28021,
"s": 27990,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28040,
"s": 28021,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28070,
"s": 28040,
"text": "HashMap in Java with Examples"
}
] |
SelectionSort - GeeksforGeeks | 28 Jun, 2021
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array ... More on Selection Sort
Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above.
In best case,
Quick sort: O (nlogn)
Merge sort: O (nlogn)
Insertion sort: O (n)
Selection sort: O (n^2)
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Tejas Networks Interview Experience for R&D Engineer
TCS NQT Coding Sheet
A Freshers Guide To Programming
Different Ways to Initialize an Set in C++ | [
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 29828,
"s": 29577,
"text": "The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array ... More on Selection Sort "
},
{
"code": null,
"e": 29923,
"s": 29828,
"text": "Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above."
},
{
"code": null,
"e": 30032,
"s": 29923,
"text": "In best case, \n\nQuick sort: O (nlogn) \nMerge sort: O (nlogn)\nInsertion sort: O (n)\nSelection sort: O (n^2) "
},
{
"code": null,
"e": 30132,
"s": 30034,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 30206,
"s": 30132,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 30259,
"s": 30206,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 30308,
"s": 30259,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30333,
"s": 30308,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30346,
"s": 30333,
"text": "Java Threads"
},
{
"code": null,
"e": 30398,
"s": 30346,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 30451,
"s": 30398,
"text": "Tejas Networks Interview Experience for R&D Engineer"
},
{
"code": null,
"e": 30472,
"s": 30451,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 30504,
"s": 30472,
"text": "A Freshers Guide To Programming"
}
] |
Spring JDBC - JdbcTemplate Class | The org.springframework.jdbc.core.JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving the application code to provide SQL and extract results. This class executes SQL queries or updates, initiating iteration over ResultSets and catching JDBC exceptions and translating them to the generic, more informative exception hierarchy defined in the org.springframework.dao package.
Following is the declaration for org.springframework.jdbc.core.JdbcTemplate class −
public class JdbcTemplate
extends JdbcAccessor
implements JdbcOperations
Step 1 − Create a JdbcTemplate object using a configured datasource.
Step 1 − Create a JdbcTemplate object using a configured datasource.
Step 2 − Use JdbcTemplate object methods to make database operations.
Step 2 − Use JdbcTemplate object methods to make database operations.
Following example will demonstrate how to read a query using JdbcTemplate class. We'll read the available records in Student Table.
String selectQuery = "select * from Student";
List <Student> students = jdbcTemplateObject.query(selectQuery, new StudentMapper());
Where,
selectQuery − Select query to read students.
selectQuery − Select query to read students.
jdbcTemplateObject − StudentJDBCTemplate object to read student object from the database.
jdbcTemplateObject − StudentJDBCTemplate object to read student object from the database.
StudentMapper − StudentMapper is a RowMapper object to map each fetched record to the student object.
StudentMapper − StudentMapper is a RowMapper object to map each fetched record to the student object.
To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will select a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of the Data Access Object interface file StudentDAO.java.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Following is the content of the StudentMapper.java file.
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Listing Multiple Records--------" );
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.println(", Age : " + record.getAge());
}
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id="dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "admin"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id="studentJDBCTemplate"
class = "com.tutorialspoint.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message.
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 11
ID : 2, Name : Nuha, Age : 2
ID : 3, Name : Ayan, Age : 15
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2889,
"s": 2396,
"text": "The org.springframework.jdbc.core.JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving the application code to provide SQL and extract results. This class executes SQL queries or updates, initiating iteration over ResultSets and catching JDBC exceptions and translating them to the generic, more informative exception hierarchy defined in the org.springframework.dao package."
},
{
"code": null,
"e": 2973,
"s": 2889,
"text": "Following is the declaration for org.springframework.jdbc.core.JdbcTemplate class −"
},
{
"code": null,
"e": 3056,
"s": 2973,
"text": "public class JdbcTemplate\n extends JdbcAccessor\n implements JdbcOperations\n"
},
{
"code": null,
"e": 3125,
"s": 3056,
"text": "Step 1 − Create a JdbcTemplate object using a configured datasource."
},
{
"code": null,
"e": 3194,
"s": 3125,
"text": "Step 1 − Create a JdbcTemplate object using a configured datasource."
},
{
"code": null,
"e": 3264,
"s": 3194,
"text": "Step 2 − Use JdbcTemplate object methods to make database operations."
},
{
"code": null,
"e": 3334,
"s": 3264,
"text": "Step 2 − Use JdbcTemplate object methods to make database operations."
},
{
"code": null,
"e": 3466,
"s": 3334,
"text": "Following example will demonstrate how to read a query using JdbcTemplate class. We'll read the available records in Student Table."
},
{
"code": null,
"e": 3598,
"s": 3466,
"text": "String selectQuery = \"select * from Student\";\nList <Student> students = jdbcTemplateObject.query(selectQuery, new StudentMapper());"
},
{
"code": null,
"e": 3605,
"s": 3598,
"text": "Where,"
},
{
"code": null,
"e": 3650,
"s": 3605,
"text": "selectQuery − Select query to read students."
},
{
"code": null,
"e": 3695,
"s": 3650,
"text": "selectQuery − Select query to read students."
},
{
"code": null,
"e": 3785,
"s": 3695,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to read student object from the database."
},
{
"code": null,
"e": 3875,
"s": 3785,
"text": "jdbcTemplateObject − StudentJDBCTemplate object to read student object from the database."
},
{
"code": null,
"e": 3977,
"s": 3875,
"text": "StudentMapper − StudentMapper is a RowMapper object to map each fetched record to the student object."
},
{
"code": null,
"e": 4079,
"s": 3977,
"text": "StudentMapper − StudentMapper is a RowMapper object to map each fetched record to the student object."
},
{
"code": null,
"e": 4322,
"s": 4079,
"text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will select a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application."
},
{
"code": null,
"e": 4405,
"s": 4322,
"text": "Following is the content of the Data Access Object interface file StudentDAO.java."
},
{
"code": null,
"e": 4833,
"s": 4405,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to list down\n * all the records from the Student table.\n */\n public List<Student> listStudents(); \n}"
},
{
"code": null,
"e": 4884,
"s": 4833,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 5356,
"s": 4884,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 5413,
"s": 5356,
"text": "Following is the content of the StudentMapper.java file."
},
{
"code": null,
"e": 5871,
"s": 5413,
"text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n return student;\n }\n}"
},
{
"code": null,
"e": 5981,
"s": 5871,
"text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO."
},
{
"code": null,
"e": 6609,
"s": 5981,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\n\npublic class StudentJDBCTemplate implements StudentDAO {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n \n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n }\n public List<Student> listStudents() {\n String SQL = \"select * from Student\";\n List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());\n return students;\n }\n}"
},
{
"code": null,
"e": 6660,
"s": 6609,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 7528,
"s": 6660,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport com.tutorialspoint.StudentJDBCTemplate;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n \n System.out.println(\"------Listing Multiple Records--------\" );\n List<Student> students = studentJDBCTemplate.listStudents();\n \n for (Student record : students) {\n System.out.print(\"ID : \" + record.getId() );\n System.out.print(\", Name : \" + record.getName() );\n System.out.println(\", Age : \" + record.getAge());\n }\n }\n}"
},
{
"code": null,
"e": 7575,
"s": 7528,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 8518,
"s": 7575,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id=\"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.cj.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id=\"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean>\n</beans>"
},
{
"code": null,
"e": 8696,
"s": 8518,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 8825,
"s": 8696,
"text": "------Listing Multiple Records--------\nID : 1, Name : Zara, Age : 11\nID : 2, Name : Nuha, Age : 2\nID : 3, Name : Ayan, Age : 15\n"
},
{
"code": null,
"e": 8832,
"s": 8825,
"text": " Print"
},
{
"code": null,
"e": 8843,
"s": 8832,
"text": " Add Notes"
}
] |
How to Merge all CSV Files into a single dataframe – Python Pandas? | To merge all CSV files, use the GLOB module. The os.path.join() method is used inside the concat() to merge the CSV files together.
At first, import the required libraries. We have set pd as an alias for the pandas library −
import pandas as pd
import glob
import os
Now, let’s say we have the following 3 CSV Files −
Sales1.csv
Sales2.csv
Sales3.csv
At first, set the path for joining multiple files. We have all the CSV files to be merged on the Desktop −
files = os.path.join("C:\\Users\\amit_\\Desktop\\", "sales*.csv")
Next, use glob to return the list of merged files −
files = glob.glob(files)
Following is the code −
import pandas as pd
import glob
import os
# setting the path for joining multiple files
files = os.path.join("C:\\Users\\amit_\\Desktop\\", "sales*.csv")
# list of merged files returned
files = glob.glob(files)
print("Resultant CSV after joining all CSV files at a particular location...");
# joining files with concat and read_csv
df = pd.concat(map(pd.read_csv, files), ignore_index=True)
print(df)
This will produce the following −
Resultant CSV after joining all CSV files at a particular location...
Car Place UnitsSold
0 Audi Bangalore 80
1 Porsche Mumbai 110
2 RollsRoyce Pune 100
3 BMW Delhi 95
4 Mercedes Hyderabad 80
5 Lamborghini Chandigarh 80
6 Volvo Rajasthan 150
7 Hyundai Manipur 120
8 Toyota HP 70 | [
{
"code": null,
"e": 1194,
"s": 1062,
"text": "To merge all CSV files, use the GLOB module. The os.path.join() method is used inside the concat() to merge the CSV files together."
},
{
"code": null,
"e": 1287,
"s": 1194,
"text": "At first, import the required libraries. We have set pd as an alias for the pandas library −"
},
{
"code": null,
"e": 1329,
"s": 1287,
"text": "import pandas as pd\nimport glob\nimport os"
},
{
"code": null,
"e": 1380,
"s": 1329,
"text": "Now, let’s say we have the following 3 CSV Files −"
},
{
"code": null,
"e": 1391,
"s": 1380,
"text": "Sales1.csv"
},
{
"code": null,
"e": 1402,
"s": 1391,
"text": "Sales2.csv"
},
{
"code": null,
"e": 1413,
"s": 1402,
"text": "Sales3.csv"
},
{
"code": null,
"e": 1520,
"s": 1413,
"text": "At first, set the path for joining multiple files. We have all the CSV files to be merged on the Desktop −"
},
{
"code": null,
"e": 1587,
"s": 1520,
"text": "files = os.path.join(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\\", \"sales*.csv\")\n"
},
{
"code": null,
"e": 1639,
"s": 1587,
"text": "Next, use glob to return the list of merged files −"
},
{
"code": null,
"e": 1664,
"s": 1639,
"text": "files = glob.glob(files)"
},
{
"code": null,
"e": 1688,
"s": 1664,
"text": "Following is the code −"
},
{
"code": null,
"e": 2093,
"s": 1688,
"text": "import pandas as pd\nimport glob\nimport os\n\n# setting the path for joining multiple files\nfiles = os.path.join(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\\", \"sales*.csv\")\n\n# list of merged files returned\nfiles = glob.glob(files)\n\nprint(\"Resultant CSV after joining all CSV files at a particular location...\");\n\n# joining files with concat and read_csv\ndf = pd.concat(map(pd.read_csv, files), ignore_index=True)\nprint(df)"
},
{
"code": null,
"e": 2127,
"s": 2093,
"text": "This will produce the following −"
},
{
"code": null,
"e": 2577,
"s": 2127,
"text": "Resultant CSV after joining all CSV files at a particular location...\n Car Place UnitsSold\n0 Audi Bangalore 80\n1 Porsche Mumbai 110\n2 RollsRoyce Pune 100\n3 BMW Delhi 95\n4 Mercedes Hyderabad 80\n5 Lamborghini Chandigarh 80\n6 Volvo Rajasthan 150\n7 Hyundai Manipur 120\n8 Toyota HP 70"
}
] |
How to use protractor to check whether text is present in an element or not ? - GeeksforGeeks | 22 Oct, 2021
Protractor is an end-to-end test framework developed for AngularJS applications, however, it also works for non-Angular JS applications. It runs tests against the application interacting with it as a real user would, running in a real browser. In this article, we are going to use Protractor to check how we can wait for the text to be present in an element?
Prerequisite: Installation and Setup of Protractor
Approach: We are going to create a basic test program in which we are going to check whether the text is present in an element or not? All the Protractor tests will have a file that will contain the configuration and this will be the initial file that will initiate the test.
Below is the step-by-step implementation of the above approach.
Step 1: We have to first create a conf.js file consists of the configuration to be used with Protractor.
conf.js
exports.config = { // Define the capabilities to be passed // to the webdriver instance capabilities: { browserName: "chrome", }, // Define the framework to be use framework: "jasmine", // Define the Spec patterns. This is relative // to the current working directory when // protractor is called specs: ["test.js"], SELENIUM_PROMISE_MANAGER: false, // Define the options to be used with Jasmine jasmineNodeOpts: { defaultTimeoutInterval: 30000, }, // Define the baseUrl for the file baseUrl: "file://" + __dirname + "/", onPrepare: function () { browser.resetUrl = "file://"; },};
Step 2: We will create the HTML file called test.html which will contain the element to be tested.
test.html
<!DOCTYPE html><html><head> <title> fade-in effect on page load using JavaScript </title> <script type="text/javascript"> var opacity = 0; var intervalID = 0; window.onload = fadeIn; function fadeIn() { setInterval(show, 200); } function show() { var body = document.getElementById("fade-in"); opacity = Number(window.getComputedStyle(body) .getPropertyValue("opacity")); if (opacity < 1) { opacity = opacity + 0.1; body.style.opacity = opacity } else { clearInterval(intervalID); } } </script></head><body> <!-- The element to be tested --> <div id="fade-in" style="opacity: 0;"> GFG </div></body></html>
Step 3: We will create the test.js file. In this file, we are going to access the above HTML file and then going wait for the element to have a particular text in it. The browser is a global created by Protractor, which is used for browser-level commands such as navigation with browser.get() method. The description and it syntax is from the Jasmine framework where describe is a description of your test while it defines the steps for the test.
test.js
describe('Protractor Demo App', function () { it('should have a title', async function () { var EC = protractor.ExpectedConditions; // Disable waiting for Angular render update browser.waitForAngularEnabled(false) // Get the HTML file that has to be tested browser.get('test.html'); // Get the fade in element let fadeIn = element(by.id('fade-in')); // Waits for the element with id 'myInput' to contain the input 'foo'. browser.wait(EC.textToBePresentInElementValue(fadeIn, 'GFG'), 5000); expect(fadeIn.getText()).toEqual('GFG'); });});
Step 4: Finally, we will run the configuration file using the command given below. This will run the configuration file and the test will be run as shown in the output below.
protractor conf.js
Output:
AngularJS-Questions
JavaScript-Questions
AngularJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js | [
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 25468,
"s": 25109,
"text": "Protractor is an end-to-end test framework developed for AngularJS applications, however, it also works for non-Angular JS applications. It runs tests against the application interacting with it as a real user would, running in a real browser. In this article, we are going to use Protractor to check how we can wait for the text to be present in an element?"
},
{
"code": null,
"e": 25519,
"s": 25468,
"text": "Prerequisite: Installation and Setup of Protractor"
},
{
"code": null,
"e": 25795,
"s": 25519,
"text": "Approach: We are going to create a basic test program in which we are going to check whether the text is present in an element or not? All the Protractor tests will have a file that will contain the configuration and this will be the initial file that will initiate the test."
},
{
"code": null,
"e": 25859,
"s": 25795,
"text": "Below is the step-by-step implementation of the above approach."
},
{
"code": null,
"e": 25964,
"s": 25859,
"text": "Step 1: We have to first create a conf.js file consists of the configuration to be used with Protractor."
},
{
"code": null,
"e": 25972,
"s": 25964,
"text": "conf.js"
},
{
"code": "exports.config = { // Define the capabilities to be passed // to the webdriver instance capabilities: { browserName: \"chrome\", }, // Define the framework to be use framework: \"jasmine\", // Define the Spec patterns. This is relative // to the current working directory when // protractor is called specs: [\"test.js\"], SELENIUM_PROMISE_MANAGER: false, // Define the options to be used with Jasmine jasmineNodeOpts: { defaultTimeoutInterval: 30000, }, // Define the baseUrl for the file baseUrl: \"file://\" + __dirname + \"/\", onPrepare: function () { browser.resetUrl = \"file://\"; },};",
"e": 26573,
"s": 25972,
"text": null
},
{
"code": null,
"e": 26672,
"s": 26573,
"text": "Step 2: We will create the HTML file called test.html which will contain the element to be tested."
},
{
"code": null,
"e": 26682,
"s": 26672,
"text": "test.html"
},
{
"code": "<!DOCTYPE html><html><head> <title> fade-in effect on page load using JavaScript </title> <script type=\"text/javascript\"> var opacity = 0; var intervalID = 0; window.onload = fadeIn; function fadeIn() { setInterval(show, 200); } function show() { var body = document.getElementById(\"fade-in\"); opacity = Number(window.getComputedStyle(body) .getPropertyValue(\"opacity\")); if (opacity < 1) { opacity = opacity + 0.1; body.style.opacity = opacity } else { clearInterval(intervalID); } } </script></head><body> <!-- The element to be tested --> <div id=\"fade-in\" style=\"opacity: 0;\"> GFG </div></body></html>",
"e": 27514,
"s": 26682,
"text": null
},
{
"code": null,
"e": 27961,
"s": 27514,
"text": "Step 3: We will create the test.js file. In this file, we are going to access the above HTML file and then going wait for the element to have a particular text in it. The browser is a global created by Protractor, which is used for browser-level commands such as navigation with browser.get() method. The description and it syntax is from the Jasmine framework where describe is a description of your test while it defines the steps for the test."
},
{
"code": null,
"e": 27969,
"s": 27961,
"text": "test.js"
},
{
"code": "describe('Protractor Demo App', function () { it('should have a title', async function () { var EC = protractor.ExpectedConditions; // Disable waiting for Angular render update browser.waitForAngularEnabled(false) // Get the HTML file that has to be tested browser.get('test.html'); // Get the fade in element let fadeIn = element(by.id('fade-in')); // Waits for the element with id 'myInput' to contain the input 'foo'. browser.wait(EC.textToBePresentInElementValue(fadeIn, 'GFG'), 5000); expect(fadeIn.getText()).toEqual('GFG'); });});",
"e": 28575,
"s": 27969,
"text": null
},
{
"code": null,
"e": 28750,
"s": 28575,
"text": "Step 4: Finally, we will run the configuration file using the command given below. This will run the configuration file and the test will be run as shown in the output below."
},
{
"code": null,
"e": 28769,
"s": 28750,
"text": "protractor conf.js"
},
{
"code": null,
"e": 28777,
"s": 28769,
"text": "Output:"
},
{
"code": null,
"e": 28797,
"s": 28777,
"text": "AngularJS-Questions"
},
{
"code": null,
"e": 28818,
"s": 28797,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28828,
"s": 28818,
"text": "AngularJS"
},
{
"code": null,
"e": 28839,
"s": 28828,
"text": "JavaScript"
},
{
"code": null,
"e": 28856,
"s": 28839,
"text": "Web Technologies"
},
{
"code": null,
"e": 28954,
"s": 28856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28963,
"s": 28954,
"text": "Comments"
},
{
"code": null,
"e": 28976,
"s": 28963,
"text": "Old Comments"
},
{
"code": null,
"e": 29020,
"s": 28976,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 29084,
"s": 29020,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 29137,
"s": 29084,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29161,
"s": 29137,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29196,
"s": 29161,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29241,
"s": 29196,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29310,
"s": 29241,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 29371,
"s": 29310,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29443,
"s": 29371,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Difference between sequence and identity in Hibernate | Hibernate or JPA support 4 different types of primary key generator. These generators are used to generate primary key while inserting rows in the database. Below are the primary key generator −
GenerationType.AUTO
GenerationType. IDENTITY
GenerationType.SEQUENCE
GenerationType.TABLE
GenerationType. IDENTITY − In identity , database is responsible to auto generate the primary key. Insert a row without specifying a value for the ID and after inserting the row, ask the database for the last generated ID. Oracle 11g does not support identity key generator. This feature is supported in Oracle 12c.
GenerationType. SEQUENCE − In sequence, we first ask database for the next set of the sequence then we insert row with return sequence id.
1
Basic
Database is responsible to auto generate the primary key
we first ask database for the next set of the sequence then we insert row with return sequence id.
2
Performance
It is faster than sequence key generator
It is bit slower than identity key generator
3
Database Support
Oracle 11g does not support identity key generator
Oracle 11g does support SEQUENCE key generator
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "Hibernate or JPA support 4 different types of primary key generator. These generators are used to generate primary key while inserting rows in the database. Below are the primary key generator −"
},
{
"code": null,
"e": 1280,
"s": 1260,
"text": "GenerationType.AUTO"
},
{
"code": null,
"e": 1305,
"s": 1280,
"text": "GenerationType. IDENTITY"
},
{
"code": null,
"e": 1330,
"s": 1305,
"text": "GenerationType.SEQUENCE "
},
{
"code": null,
"e": 1351,
"s": 1330,
"text": "GenerationType.TABLE"
},
{
"code": null,
"e": 1669,
"s": 1351,
"text": "GenerationType. IDENTITY − In identity , database is responsible to auto generate the primary key. Insert a row without specifying a value for the ID and after inserting the row, ask the database for the last generated ID. Oracle 11g does not support identity key generator. This feature is supported in Oracle 12c. "
},
{
"code": null,
"e": 1809,
"s": 1669,
"text": "GenerationType. SEQUENCE − In sequence, we first ask database for the next set of the sequence then we insert row with return sequence id. "
},
{
"code": null,
"e": 1811,
"s": 1809,
"text": "1"
},
{
"code": null,
"e": 1818,
"s": 1811,
"text": "Basic "
},
{
"code": null,
"e": 1876,
"s": 1818,
"text": " Database is responsible to auto generate the primary key"
},
{
"code": null,
"e": 1975,
"s": 1876,
"text": "we first ask database for the next set of the sequence then we insert row with return sequence id."
},
{
"code": null,
"e": 1977,
"s": 1975,
"text": "2"
},
{
"code": null,
"e": 1990,
"s": 1977,
"text": "Performance "
},
{
"code": null,
"e": 2032,
"s": 1990,
"text": "It is faster than sequence key generator "
},
{
"code": null,
"e": 2077,
"s": 2032,
"text": "It is bit slower than identity key generator"
},
{
"code": null,
"e": 2079,
"s": 2077,
"text": "3"
},
{
"code": null,
"e": 2097,
"s": 2079,
"text": "Database Support "
},
{
"code": null,
"e": 2148,
"s": 2097,
"text": "Oracle 11g does not support identity key generator"
},
{
"code": null,
"e": 2195,
"s": 2148,
"text": "Oracle 11g does support SEQUENCE key generator"
},
{
"code": null,
"e": 2548,
"s": 2195,
"text": "@Entity\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n Integer id;\n String name;\n public Integer getId() {\n return id;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 2903,
"s": 2548,
"text": "@Entity\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE)\n Integer id;\n String name; \n public Integer getId() {\n return id;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
}
] |
Perl gethostbyname Function | This function contacts the system's name-resolving service, returning a list of information for the host ADDR of type ADDRTYPE, as follows − ($name, $aliases, $addrtype, $length, @addrs)
The @addrs array contains a list of packed binary addresses. In a scalar context, returns the host address.
Following is the simple syntax for this function −
gethostbyname NAME
This function returns undef on error and otherwise host name in scalr context and empty list on error otherwise host record in list context.
Following is the example code showing its basic usage −
#!/usr/bin/perl
use Socket;
($name, $aliases, $addrtype,
$length, @addrs) = gethostbyname "amrood.com";
print "Host name is $name\n";
print "Aliases is $aliases\n";
When above code is executed, it produces the following result −
Host name is amrood.com
Aliases is
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2407,
"s": 2220,
"text": "This function contacts the system's name-resolving service, returning a list of information for the host ADDR of type ADDRTYPE, as follows − ($name, $aliases, $addrtype, $length, @addrs)"
},
{
"code": null,
"e": 2515,
"s": 2407,
"text": "The @addrs array contains a list of packed binary addresses. In a scalar context, returns the host address."
},
{
"code": null,
"e": 2566,
"s": 2515,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2586,
"s": 2566,
"text": "gethostbyname NAME\n"
},
{
"code": null,
"e": 2727,
"s": 2586,
"text": "This function returns undef on error and otherwise host name in scalr context and empty list on error otherwise host record in list context."
},
{
"code": null,
"e": 2783,
"s": 2727,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2965,
"s": 2783,
"text": "#!/usr/bin/perl\nuse Socket;\n\n ($name, $aliases, $addrtype, \n $length, @addrs) = gethostbyname \"amrood.com\";\n print \"Host name is $name\\n\";\n print \"Aliases is $aliases\\n\";"
},
{
"code": null,
"e": 3029,
"s": 2965,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3065,
"s": 3029,
"text": "Host name is amrood.com\nAliases is\n"
},
{
"code": null,
"e": 3100,
"s": 3065,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3114,
"s": 3100,
"text": " Devi Killada"
},
{
"code": null,
"e": 3149,
"s": 3114,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3169,
"s": 3149,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3202,
"s": 3169,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3218,
"s": 3202,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3251,
"s": 3218,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3268,
"s": 3251,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3301,
"s": 3268,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3324,
"s": 3301,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3359,
"s": 3324,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3382,
"s": 3359,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3389,
"s": 3382,
"text": " Print"
},
{
"code": null,
"e": 3400,
"s": 3389,
"text": " Add Notes"
}
] |
Scikit Learn - Linear Regression | It is one of the best statistical models that studies the relationship between a dependent variable (Y) with a given set of independent variables (X). The relationship can be established with the help of fitting a best line.
sklearn.linear_model.LinearRegression is the module used to implement linear regression.
Following table consists the parameters used by Linear Regression module −
fit_intercept − Boolean, optional, default True
Used to calculate the intercept for the model. No intercept will be used in the calculation if this set to false.
normalize − Boolean, optional, default False
If this parameter is set to True, the regressor X will be normalized before regression. The normalization will be done by subtracting the mean and dividing it by L2 norm. If fit_intercept = False, this parameter will be ignored.
copy_X − Boolean, optional, default True
By default, it is true which means X will be copied. But if it is set to false, X may be overwritten.
n_jobs − int or None, optional(default = None)
It represents the number of jobs to use for the computation.
Following table consists the attributes used by Linear Regression module −
coef_ − array, shape(n_features,) or (n_targets, n_features)
It is used to estimate the coefficients for the linear regression problem. It would be a 2D array of shape (n_targets, n_features) if multiple targets are passed during fit. Ex. (y 2D). On the other hand, it would be a 1D array of length (n_features) if only one target is passed during fit.
Intercept_ − array
This is an independent term in this linear model.
First, import the required packages −
import numpy as np
from sklearn.linear_model import LinearRegression
Now, provide the values for independent variable X −
X = np.array([[1,1],[1,2],[2,2],[2,3]])
Next, the value of dependent variable y can be calculated as follows −
y = np.dot(X, np.array([1,2])) + 3
Now, create a linear regression object as follows −
regr = LinearRegression(
fit_intercept = True, normalize = True, copy_X = True, n_jobs = 2
)
.fit(X,y)
Use predict() method to predict using this linear model as follows −
regr.predict(np.array([[3,5]]))
array([16.])
To get the coefficient of determination of the prediction we can use Score() method as follows −
regr.score(X,y)
1.0
We can estimate the coefficients by using attribute named ‘coef’ as follows −
regr.coef_
array([1., 2.])
We can calculate the intercept i.e. the expected mean value of Y when all X = 0 by using attribute named ‘intercept’ as follows −
In [24]: regr.intercept_
Output
3.0000000000000018
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1,1],[1,2],[2,2],[2,3]])
y = np.dot(X, np.array([1,2])) + 3
regr = LinearRegression(
fit_intercept = True, normalize = True, copy_X = True, n_jobs = 2
).fit(X,y)
regr.predict(np.array([[3,5]]))
regr.score(X,y)
regr.coef_
regr.intercept_
11 Lectures
2 hours
PARTHA MAJUMDAR
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2446,
"s": 2221,
"text": "It is one of the best statistical models that studies the relationship between a dependent variable (Y) with a given set of independent variables (X). The relationship can be established with the help of fitting a best line."
},
{
"code": null,
"e": 2535,
"s": 2446,
"text": "sklearn.linear_model.LinearRegression is the module used to implement linear regression."
},
{
"code": null,
"e": 2610,
"s": 2535,
"text": "Following table consists the parameters used by Linear Regression module −"
},
{
"code": null,
"e": 2658,
"s": 2610,
"text": "fit_intercept − Boolean, optional, default True"
},
{
"code": null,
"e": 2772,
"s": 2658,
"text": "Used to calculate the intercept for the model. No intercept will be used in the calculation if this set to false."
},
{
"code": null,
"e": 2817,
"s": 2772,
"text": "normalize − Boolean, optional, default False"
},
{
"code": null,
"e": 3046,
"s": 2817,
"text": "If this parameter is set to True, the regressor X will be normalized before regression. The normalization will be done by subtracting the mean and dividing it by L2 norm. If fit_intercept = False, this parameter will be ignored."
},
{
"code": null,
"e": 3087,
"s": 3046,
"text": "copy_X − Boolean, optional, default True"
},
{
"code": null,
"e": 3189,
"s": 3087,
"text": "By default, it is true which means X will be copied. But if it is set to false, X may be overwritten."
},
{
"code": null,
"e": 3236,
"s": 3189,
"text": "n_jobs − int or None, optional(default = None)"
},
{
"code": null,
"e": 3297,
"s": 3236,
"text": "It represents the number of jobs to use for the computation."
},
{
"code": null,
"e": 3372,
"s": 3297,
"text": "Following table consists the attributes used by Linear Regression module −"
},
{
"code": null,
"e": 3433,
"s": 3372,
"text": "coef_ − array, shape(n_features,) or (n_targets, n_features)"
},
{
"code": null,
"e": 3725,
"s": 3433,
"text": "It is used to estimate the coefficients for the linear regression problem. It would be a 2D array of shape (n_targets, n_features) if multiple targets are passed during fit. Ex. (y 2D). On the other hand, it would be a 1D array of length (n_features) if only one target is passed during fit."
},
{
"code": null,
"e": 3744,
"s": 3725,
"text": "Intercept_ − array"
},
{
"code": null,
"e": 3794,
"s": 3744,
"text": "This is an independent term in this linear model."
},
{
"code": null,
"e": 3832,
"s": 3794,
"text": "First, import the required packages −"
},
{
"code": null,
"e": 3901,
"s": 3832,
"text": "import numpy as np\nfrom sklearn.linear_model import LinearRegression"
},
{
"code": null,
"e": 3954,
"s": 3901,
"text": "Now, provide the values for independent variable X −"
},
{
"code": null,
"e": 3994,
"s": 3954,
"text": "X = np.array([[1,1],[1,2],[2,2],[2,3]])"
},
{
"code": null,
"e": 4065,
"s": 3994,
"text": "Next, the value of dependent variable y can be calculated as follows −"
},
{
"code": null,
"e": 4100,
"s": 4065,
"text": "y = np.dot(X, np.array([1,2])) + 3"
},
{
"code": null,
"e": 4152,
"s": 4100,
"text": "Now, create a linear regression object as follows −"
},
{
"code": null,
"e": 4258,
"s": 4152,
"text": "regr = LinearRegression(\n fit_intercept = True, normalize = True, copy_X = True, n_jobs = 2\n)\n.fit(X,y)"
},
{
"code": null,
"e": 4327,
"s": 4258,
"text": "Use predict() method to predict using this linear model as follows −"
},
{
"code": null,
"e": 4359,
"s": 4327,
"text": "regr.predict(np.array([[3,5]]))"
},
{
"code": null,
"e": 4373,
"s": 4359,
"text": "array([16.])\n"
},
{
"code": null,
"e": 4470,
"s": 4373,
"text": "To get the coefficient of determination of the prediction we can use Score() method as follows −"
},
{
"code": null,
"e": 4487,
"s": 4470,
"text": "regr.score(X,y)\n"
},
{
"code": null,
"e": 4492,
"s": 4487,
"text": "1.0\n"
},
{
"code": null,
"e": 4570,
"s": 4492,
"text": "We can estimate the coefficients by using attribute named ‘coef’ as follows −"
},
{
"code": null,
"e": 4582,
"s": 4570,
"text": "regr.coef_\n"
},
{
"code": null,
"e": 4599,
"s": 4582,
"text": "array([1., 2.])\n"
},
{
"code": null,
"e": 4729,
"s": 4599,
"text": "We can calculate the intercept i.e. the expected mean value of Y when all X = 0 by using attribute named ‘intercept’ as follows −"
},
{
"code": null,
"e": 4781,
"s": 4729,
"text": "In [24]: regr.intercept_\nOutput\n3.0000000000000018\n"
},
{
"code": null,
"e": 5105,
"s": 4781,
"text": "import numpy as np\nfrom sklearn.linear_model import LinearRegression\nX = np.array([[1,1],[1,2],[2,2],[2,3]])\ny = np.dot(X, np.array([1,2])) + 3\nregr = LinearRegression(\n fit_intercept = True, normalize = True, copy_X = True, n_jobs = 2\n).fit(X,y)\nregr.predict(np.array([[3,5]]))\nregr.score(X,y)\nregr.coef_\nregr.intercept_"
},
{
"code": null,
"e": 5138,
"s": 5105,
"text": "\n 11 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5155,
"s": 5138,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 5162,
"s": 5155,
"text": " Print"
},
{
"code": null,
"e": 5173,
"s": 5162,
"text": " Add Notes"
}
] |
Prefix Sum of Matrix (Or 2D Array) in C++ | In this problem, we are given a 2D array of integer values mat[][]. Our task is to print the prefix sum matrix of mat.
Prefix sum matrix: every element of the matrix is the sum elements above and left of it. i.e
prefixSum[i][j] = mat[i][j] + mat[i-1][j]...mat[0][j] + mat[i][j-1] +... mat[i][0].
Let’s take an example to understand the problem
Input: arr =[
[4 6 1]
[5 7 2]
[3 8 9]
]
Output:[
[4 10 11]
[9 22 25]
[12 33 45]
]
To solve this problem, one simple solution is finding prefixSum by traversing all elements till i,j position and add them. But it is a bit complex for the system.
A more effective solution will be using the formula for finding the values of elements of prefixSum matrix.
The general formula for element at ij position is
prefixSum[i][j] = prefixSum[i-1][j] + prefixSum[i][j-1] - prefixSum[i-1][j-1] + a[i][j]
Some specail cases are
For i = j = 0, prefixSum[i][j] = a[i][j]
For i = 0 and j > 0, prefixSum[i][j] = prefixSum[i][j-1] + a[i][j]
For i > 0 and j = 0, prefixSum[i][j] = prefixSum[i-1][j] + a[i][j]
The code to show the implementation of our solution
Live Demo
#include <iostream>
using namespace std;
#define R 3
#define C 3
void printPrefixSum(int a[][C]) {
int prefixSum[R][C];
prefixSum[0][0] = a[0][0];
for (int i = 1; i < C; i++)
prefixSum[0][i] = prefixSum[0][i - 1] + a[0][i];
for (int i = 0; i < R; i++)
prefixSum[i][0] = prefixSum[i - 1][0] + a[i][0];
for (int i = 1; i < R; i++) {
for (int j = 1; j < C; j++)
prefixSum[i][j]=prefixSum[i- 1][j]+prefixSum[i][j- 1]-prefixSum[i- 1][j- 1]+a[i][j];
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++)
cout<<prefixSum[i][j]<<"\t";
cout<<endl;
}
}
int main() {
int mat[R][C] = {
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9}
};
cout<<"The prefix Sum Matrix is :\n";
printPrefixSum(mat);
return 0;
}
The prefix Sum Matrix is :
1 3 6
5 12 21
12 27 45 | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "In this problem, we are given a 2D array of integer values mat[][]. Our task is to print the prefix sum matrix of mat."
},
{
"code": null,
"e": 1274,
"s": 1181,
"text": "Prefix sum matrix: every element of the matrix is the sum elements above and left of it. i.e"
},
{
"code": null,
"e": 1358,
"s": 1274,
"text": "prefixSum[i][j] = mat[i][j] + mat[i-1][j]...mat[0][j] + mat[i][j-1] +... mat[i][0]."
},
{
"code": null,
"e": 1406,
"s": 1358,
"text": "Let’s take an example to understand the problem"
},
{
"code": null,
"e": 1530,
"s": 1406,
"text": "Input: arr =[\n [4 6 1]\n [5 7 2]\n [3 8 9]\n]\nOutput:[\n [4 10 11]\n [9 22 25]\n [12 33 45]\n]"
},
{
"code": null,
"e": 1693,
"s": 1530,
"text": "To solve this problem, one simple solution is finding prefixSum by traversing all elements till i,j position and add them. But it is a bit complex for the system."
},
{
"code": null,
"e": 1801,
"s": 1693,
"text": "A more effective solution will be using the formula for finding the values of elements of prefixSum matrix."
},
{
"code": null,
"e": 1851,
"s": 1801,
"text": "The general formula for element at ij position is"
},
{
"code": null,
"e": 1939,
"s": 1851,
"text": "prefixSum[i][j] = prefixSum[i-1][j] + prefixSum[i][j-1] - prefixSum[i-1][j-1] + a[i][j]"
},
{
"code": null,
"e": 1962,
"s": 1939,
"text": "Some specail cases are"
},
{
"code": null,
"e": 2137,
"s": 1962,
"text": "For i = j = 0, prefixSum[i][j] = a[i][j]\nFor i = 0 and j > 0, prefixSum[i][j] = prefixSum[i][j-1] + a[i][j]\nFor i > 0 and j = 0, prefixSum[i][j] = prefixSum[i-1][j] + a[i][j]"
},
{
"code": null,
"e": 2189,
"s": 2137,
"text": "The code to show the implementation of our solution"
},
{
"code": null,
"e": 2200,
"s": 2189,
"text": " Live Demo"
},
{
"code": null,
"e": 2982,
"s": 2200,
"text": "#include <iostream>\nusing namespace std;\n#define R 3\n#define C 3\nvoid printPrefixSum(int a[][C]) {\n int prefixSum[R][C];\n prefixSum[0][0] = a[0][0];\n for (int i = 1; i < C; i++)\n prefixSum[0][i] = prefixSum[0][i - 1] + a[0][i];\n for (int i = 0; i < R; i++)\n prefixSum[i][0] = prefixSum[i - 1][0] + a[i][0];\n for (int i = 1; i < R; i++) {\n for (int j = 1; j < C; j++)\n prefixSum[i][j]=prefixSum[i- 1][j]+prefixSum[i][j- 1]-prefixSum[i- 1][j- 1]+a[i][j];\n }\n for (int i = 0; i < R; i++) {\n for (int j = 0; j < C; j++)\n cout<<prefixSum[i][j]<<\"\\t\";\n cout<<endl;\n }\n}\nint main() {\n int mat[R][C] = {\n { 1, 2, 3},\n { 4, 5, 6},\n { 7, 8, 9}\n };\n cout<<\"The prefix Sum Matrix is :\\n\";\n printPrefixSum(mat);\n return 0;\n}"
},
{
"code": null,
"e": 3044,
"s": 2982,
"text": "The prefix Sum Matrix is :\n1 3 6\n5 12 21\n12 27 45"
}
] |
jQuery UI Dialog buttons Option | 19 Mar, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Dialog buttons option is used to specify the buttons that should be displayed on the dialog.
Syntax:
$( ".selector" ).dialog({
buttons: [
{
text: "Ok",
icon: "ui-icon-heart",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
CDN Link: First, add jQuery UI scripts needed for your project.
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
Example:
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href= "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").dialog({ autoOpen: false, buttons: [ { text: "Ok", click: function () { $(this).dialog("close"); } } ] }); $("#geeks").click(function () { $("#gfg").dialog("open"); }); }); </script></head> <body style="text-align: center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h3>jQuery UI Dialog buttons Option</h3> <button id="geeks">Open Dialog</button> <div id="gfg" title="GeeksforGeeks"> Welcome to GeeksforGeeks </div></body> </html>
Output:
Reference: https://api.jqueryui.com/dialog/#option-buttons
HTML-Tags
jQuery-Methods
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Mar, 2021"
},
{
"code": null,
"e": 303,
"s": 28,
"text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Dialog buttons option is used to specify the buttons that should be displayed on the dialog. "
},
{
"code": null,
"e": 311,
"s": 303,
"text": "Syntax:"
},
{
"code": null,
"e": 488,
"s": 311,
"text": "$( \".selector\" ).dialog({\n buttons: [\n {\n text: \"Ok\",\n icon: \"ui-icon-heart\",\n click: function() {\n $( this ).dialog( \"close\" );\n }\n }\n ]\n});"
},
{
"code": null,
"e": 552,
"s": 488,
"text": "CDN Link: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 765,
"s": 552,
"text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>"
},
{
"code": null,
"e": 774,
"s": 765,
"text": "Example:"
},
{
"code": null,
"e": 779,
"s": 774,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href= \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").dialog({ autoOpen: false, buttons: [ { text: \"Ok\", click: function () { $(this).dialog(\"close\"); } } ] }); $(\"#geeks\").click(function () { $(\"#gfg\").dialog(\"open\"); }); }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>jQuery UI Dialog buttons Option</h3> <button id=\"geeks\">Open Dialog</button> <div id=\"gfg\" title=\"GeeksforGeeks\"> Welcome to GeeksforGeeks </div></body> </html>",
"e": 1861,
"s": 779,
"text": null
},
{
"code": null,
"e": 1869,
"s": 1861,
"text": "Output:"
},
{
"code": null,
"e": 1928,
"s": 1869,
"text": "Reference: https://api.jqueryui.com/dialog/#option-buttons"
},
{
"code": null,
"e": 1938,
"s": 1928,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1953,
"s": 1938,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 1963,
"s": 1953,
"text": "jQuery-UI"
},
{
"code": null,
"e": 1970,
"s": 1963,
"text": "JQuery"
},
{
"code": null,
"e": 1987,
"s": 1970,
"text": "Web Technologies"
},
{
"code": null,
"e": 2085,
"s": 1987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2131,
"s": 2085,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 2160,
"s": 2131,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2223,
"s": 2160,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 2276,
"s": 2223,
"text": "How to add options to a select element using jQuery?"
},
{
"code": null,
"e": 2310,
"s": 2276,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 2372,
"s": 2310,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2405,
"s": 2372,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2466,
"s": 2405,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2516,
"s": 2466,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Discrete logarithm (Find an integer k such that a^k is congruent modulo b) | 29 Dec, 2021
Given three integers a, b and m. Find an integer k such that where a and m are relatively prime. If it is not possible for any k to satisfy this relation, print -1.Examples:
Input: 2 3 5
Output: 3
Explanation:
a = 2, b = 3, m = 5
The value which satisfies the above equation
is 3, because
=> 23 = 2 * 2 * 2 = 8
=> 23 (mod 5) = 8 (mod 5)
=> 3
which is equal to b i.e., 3.
Input: 3 7 11
Output: -1
A Naive approach is to run a loop from 0 to m to cover all possible values of k and check for which value of k, the above relation satisfies. If all the values of k exhausted, print -1. Time complexity of this approach is O(m) An efficient approach is to use baby-step, giant-step algorithm by using meet in the middle trick.
Baby-step giant-step algorithm
Given a cyclic group G of order ‘m’, a generator ‘a’ of the group, and a group element ‘b’, the problem is to find an integer ‘k’ such that So what we are going to do(according to Meet in the middle trick) is to split the problem in two parts of each and solve them individually and then find the collision.
Now according to the baby-step giant-step
algorithm, we can write 'k' as
with
and and .
Therefore, we have:
Therefore in order to solve, we precompute
for different values of 'i'.
Then fix 'b' and tries values of 'j'
In RHS of the congruence relation above. It
tests to see if congruence is satisfied for
any value of 'j', using precomputed
values of LHS.
Let’s see how to use above algorithm for our question:-First of all we have to write , where Obviously, any value of k in the interval [0, m) can be represented in this form, where and Replace the ‘k’ in above equality, we get:-
The term left and right can take only n distinct values as . Therefore we need to generate all these terms for either left or right part of equality and store them in an array or data structure like map/unordered_map in C/C++ or Hashmap in java.Suppose we have stored all values of LHS. Now iterate over all possible terms on the RHS for different values of j and check which value satisfies the LHS equality.If no value satisfies in above step for any candidate of j, print -1.
The term left and right can take only n distinct values as . Therefore we need to generate all these terms for either left or right part of equality and store them in an array or data structure like map/unordered_map in C/C++ or Hashmap in java.
Suppose we have stored all values of LHS. Now iterate over all possible terms on the RHS for different values of j and check which value satisfies the LHS equality.
If no value satisfies in above step for any candidate of j, print -1.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to calculate discrete logarithm#include<bits/stdc++.h>using namespace std; /* Iterative Function to calculate (x ^ y)%p in O(log y) */int powmod(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // Function to calculate k for given a, b, mint discreteLogarithm(int a, int b, int m) { int n = (int) sqrt (m) + 1; unordered_map<int, int> value; // Store all values of a^(n*i) of LHS for (int i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (int j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision int cur = (powmod (a, j, m) * b) % m; // If collision occurs i.e., LHS = RHS if (value[cur]) { int ans = value[cur] * n - j; // Check whether ans lies below m or not if (ans < m) return ans; } } return -1;} // Driver codeint main(){ int a = 2, b = 3, m = 5; cout << discreteLogarithm(a, b, m) << endl; a = 3, b = 7, m = 11; cout << discreteLogarithm(a, b, m);}
// Java program to calculate discrete logarithm class GFG{/* Iterative Function to calculate (x ^ y)%p inO(log y) */static int powmod(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)>0) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // Function to calculate k for given a, b, mstatic int discreteLogarithm(int a, int b, int m) { int n = (int) (Math.sqrt (m) + 1); int[] value=new int[m]; // Store all values of a^(n*i) of LHS for (int i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (int j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision int cur = (powmod (a, j, m) * b) % m; // If collision occurs i.e., LHS = RHS if (value[cur]>0) { int ans = value[cur] * n - j; // Check whether ans lies below m or not if (ans < m) return ans; } } return -1;} // Driver codepublic static void main(String[] args){ int a = 2, b = 3, m = 5; System.out.println(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; System.out.println(discreteLogarithm(a, b, m));}}// This code is contributed by mits
# Python3 program to calculate# discrete logarithmimport math; # Iterative Function to calculate# (x ^ y)%p in O(log y)def powmod(x, y, p): res = 1; # Initialize result x = x % p; # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p; # y must be even now y = y >> 1; # y = y/2 x = (x * x) % p; return res; # Function to calculate k for given a, b, mdef discreteLogarithm(a, b, m): n = int(math.sqrt(m) + 1); value = [0] * m; # Store all values of a^(n*i) of LHS for i in range(n, 0, -1): value[ powmod (a, i * n, m) ] = i; for j in range(n): # Calculate (a ^ j) * b and check # for collision cur = (powmod (a, j, m) * b) % m; # If collision occurs i.e., LHS = RHS if (value[cur]): ans = value[cur] * n - j; # Check whether ans lies below m or not if (ans < m): return ans; return -1; # Driver codea = 2;b = 3;m = 5;print(discreteLogarithm(a, b, m)); a = 3;b = 7;m = 11;print(discreteLogarithm(a, b, m)); # This code is contributed by mits
// C# program to calculate discrete logarithmusing System;class GFG{/* Iterative Function to calculate (x ^ y)%p inO(log y) */static int powmod(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)>0) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // Function to calculate k for given a, b, mstatic int discreteLogarithm(int a, int b, int m) { int n = (int) (Math.Sqrt (m) + 1); int[] value=new int[m]; // Store all values of a^(n*i) of LHS for (int i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (int j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision int cur = (powmod (a, j, m) * b) % m; // If collision occurs i.e., LHS = RHS if (value[cur]>0) { int ans = value[cur] * n - j; // Check whether ans lies below m or not if (ans < m) return ans; } } return -1;} // Driver codestatic void Main(){ int a = 2, b = 3, m = 5; Console.WriteLine(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; Console.WriteLine(discreteLogarithm(a, b, m));}}// This code is contributed by mits
<?php// PHP program to calculate// discrete logarithm // Iterative Function to calculate// (x ^ y)%p in O(log y)function powmod($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Function to calculate k for given a, b, mfunction discreteLogarithm($a, $b, $m){ $n = (int)sqrt($m) + 1; $value = array_fill(0, $m, NULL); // Store all values of a^(n*i) of LHS for ($i = $n; $i >= 1; --$i) $value[ powmod ($a, $i * $n, $m) ] = $i; for ($j = 0; $j < $n; ++$j) { // Calculate (a ^ j) * b and check // for collision $cur = (powmod ($a, $j, $m) * $b) % $m; // If collision occurs i.e., LHS = RHS if ($value[$cur]) { $ans = $value[$cur] * $n - $j; // Check whether ans lies below m or not if ($ans < $m) return $ans; } } return -1;} // Driver code$a = 2;$b = 3;$m = 5;echo discreteLogarithm($a, $b, $m), "\n"; $a = 3;$b = 7;$m = 11;echo discreteLogarithm($a, $b, $m), "\n"; // This code is contributed by ajit.?>
<script> // Javascript program to calculate // discrete logarithm /* Iterative Function to calculate (x ^ y)%p in O(log y) */ function powmod(x, y, p) { // Initialize result let res = 1; // Update x if it is more // than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if ((y & 1)>0) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res; } // Function to calculate // k for given a, b, m function discreteLogarithm(a, b, m) { let n = (parseInt(Math.sqrt(m), 10) + 1); let value = new Array(m); value.fill(0); // Store all values of a^(n*i) of LHS for (let i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (let j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision let cur = (powmod (a, j, m) * b) % m; // If collision occurs // i.e., LHS = RHS if (value[cur]>0) { let ans = value[cur] * n - j; // Check whether ans lies // below m or not if (ans < m) return ans; } } return -1; } let a = 2, b = 3, m = 5; document.write( discreteLogarithm(a, b, m) + "</br>" ); a = 3; b = 7; m = 11; document.write( discreteLogarithm(a, b, m) + "</br>" ); </script>
Output:
3
-1
Time complexity: O(sqrt(m)*log(b)) Auxiliary space: O(sqrt(m))A possible improvement is to get rid of binary exponentiation or log(b) factor in the second phase of the algorithm. This can be done by keeping a variable that multiplies by ‘a’ each time as ‘an’. Let’s see the program to understand more.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to calculate discrete logarithm#include<bits/stdc++.h>using namespace std; int discreteLogarithm(int a, int b, int m){ int n = (int) sqrt (m) + 1; // Calculate a ^ n int an = 1; for (int i = 0; i<n; ++i) an = (an * a) % m; unordered_map<int, int> value; // Store all values of a^(n*i) of LHS for (int i = 1, cur = an; i<= n; ++i) { if (! value[ cur ]) value[ cur ] = i; cur = (cur * an) % m; } for (int i = 0, cur = b; i<= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur]) { int ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1;} // Driver codeint main(){ int a = 2, b = 3, m = 5; cout << discreteLogarithm(a, b, m) << endl; a = 3, b = 7, m = 11; cout << discreteLogarithm(a, b, m);}
// Java program to calculate discrete logarithm class GFG{ static int discreteLogarithm(int a, int b, int m) { int n = (int) (Math.sqrt (m) + 1); // Calculate a ^ n int an = 1; for (int i = 0; i < n; ++i) an = (an * a) % m; int[] value=new int[m]; // Store all values of a^(n*i) of LHS for (int i = 1, cur = an; i <= n; ++i) { if (value[ cur ] == 0) value[ cur ] = i; cur = (cur * an) % m; } for (int i = 0, cur = b; i <= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur] > 0) { int ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1; } // Driver code public static void main(String[] args) { int a = 2, b = 3, m = 5; System.out.println(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; System.out.println(discreteLogarithm(a, b, m)); }} // This code is contributed by mits
# Python3 program to calculate# discrete logarithmimport math; def discreteLogarithm(a, b, m): n = int(math.sqrt (m) + 1); # Calculate a ^ n an = 1; for i in range(n): an = (an * a) % m; value = [0] * m; # Store all values of a^(n*i) of LHS cur = an; for i in range(1, n + 1): if (value[ cur ] == 0): value[ cur ] = i; cur = (cur * an) % m; cur = b; for i in range(n + 1): # Calculate (a ^ j) * b and check # for collision if (value[cur] > 0): ans = value[cur] * n - i; if (ans < m): return ans; cur = (cur * a) % m; return -1; # Driver codea = 2;b = 3;m = 5;print(discreteLogarithm(a, b, m)); a = 3;b = 7;m = 11;print(discreteLogarithm(a, b, m)); # This code is contributed by mits
// C# program to calculate discrete logarithmusing System; class GFG{ static int discreteLogarithm(int a, int b, int m){ int n = (int) (Math.Sqrt (m) + 1); // Calculate a ^ n int an = 1; for (int i = 0; i < n; ++i) an = (an * a) % m; int[] value = new int[m]; // Store all values of a^(n*i) of LHS for (int i = 1, cur = an; i<= n; ++i) { if (value[ cur ] == 0) value[ cur ] = i; cur = (cur * an) % m; } for (int i = 0, cur = b; i<= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur] > 0) { int ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1;} // Driver codestatic void Main(){ int a = 2, b = 3, m = 5; Console.WriteLine(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; Console.WriteLine(discreteLogarithm(a, b, m));}} // This code is contributed by mits
<?php// PHP program to calculate discrete logarithm function discreteLogarithm($a, $b, $m){ $n = (int)sqrt ($m) + 1; // Calculate a ^ n $an = 1; for ($i = 0; $i < $n; ++$i) $an = ($an * $a) % $m; $value = array_fill(0, $m, NULL); // Store all values of a^(n*i) of LHS for ($i = 1, $cur = $an; $i<= $n; ++$i) { if (! $value[ $cur ]) $value[ $cur ] = $i; $cur = ($cur * $an) % $m; } for ($i = 0, $cur = $b; $i<= $n; ++$i) { // Calculate (a ^ j) * b and check // for collision if ($value[$cur]) { $ans = $value[$cur] * $n - $i; if ($ans < $m) return $ans; } $cur = ($cur * $a) % $m; } return -1;} // Driver code$a = 2;$b = 3;$m = 5;echo discreteLogarithm($a, $b, $m), "\n"; $a = 3;$b = 7;$m = 11;echo discreteLogarithm($a, $b, $m); // This code is contributed by ajit.?>
<script> // Javascript program to calculate // discrete logarithm function discreteLogarithm(a, b, m) { let n = parseInt(Math.sqrt(m), 10) + 1; // Calculate a ^ n let an = 1; for (let i = 0; i < n; ++i) an = (an * a) % m; let value = new Array(m); value.fill(0); // Store all values of a^(n*i) of LHS for (let i = 1, cur = an; i<= n; ++i) { if (value[ cur ] == 0) value[ cur ] = i; cur = (cur * an) % m; } for (let i = 0, cur = b; i<= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur] > 0) { let ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1; } let a = 2, b = 3, m = 5; document.write(discreteLogarithm(a, b, m) + "</br>"); a = 3; b = 7; m = 11; document.write(discreteLogarithm(a, b, m)); </script>
Output:
3
-1
Time complexity: O(sqrt(m)) Auxiliary space: O(sqrt(m))Reference: http://e-maxx-eng.appspot.com/algebra/discrete-log.html https://en.wikipedia.org/wiki/Baby-step_giant-stepThis article is contributed by Shubham Bansal. 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.
jit_t
Mithun Kumar
suresh07
rameshtravel07
germanshephered48
Modular Arithmetic
number-theory
Mathematical
number-theory
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 230,
"s": 54,
"text": "Given three integers a, b and m. Find an integer k such that where a and m are relatively prime. If it is not possible for any k to satisfy this relation, print -1.Examples: "
},
{
"code": null,
"e": 455,
"s": 230,
"text": "Input: 2 3 5\nOutput: 3\nExplanation:\na = 2, b = 3, m = 5\nThe value which satisfies the above equation\nis 3, because \n=> 23 = 2 * 2 * 2 = 8\n=> 23 (mod 5) = 8 (mod 5) \n=> 3\nwhich is equal to b i.e., 3.\n\nInput: 3 7 11\nOutput: -1"
},
{
"code": null,
"e": 784,
"s": 457,
"text": "A Naive approach is to run a loop from 0 to m to cover all possible values of k and check for which value of k, the above relation satisfies. If all the values of k exhausted, print -1. Time complexity of this approach is O(m) An efficient approach is to use baby-step, giant-step algorithm by using meet in the middle trick. "
},
{
"code": null,
"e": 815,
"s": 784,
"text": "Baby-step giant-step algorithm"
},
{
"code": null,
"e": 1125,
"s": 815,
"text": "Given a cyclic group G of order ‘m’, a generator ‘a’ of the group, and a group element ‘b’, the problem is to find an integer ‘k’ such that So what we are going to do(according to Meet in the middle trick) is to split the problem in two parts of each and solve them individually and then find the collision. "
},
{
"code": null,
"e": 1498,
"s": 1125,
"text": "Now according to the baby-step giant-step \nalgorithm, we can write 'k' as \n with \nand and .\nTherefore, we have:\n\n\nTherefore in order to solve, we precompute \n for different values of 'i'. \nThen fix 'b' and tries values of 'j' \nIn RHS of the congruence relation above. It \ntests to see if congruence is satisfied for \nany value of 'j', using precomputed \nvalues of LHS. "
},
{
"code": null,
"e": 1729,
"s": 1498,
"text": "Let’s see how to use above algorithm for our question:-First of all we have to write , where Obviously, any value of k in the interval [0, m) can be represented in this form, where and Replace the ‘k’ in above equality, we get:- "
},
{
"code": null,
"e": 2210,
"s": 1729,
"text": "The term left and right can take only n distinct values as . Therefore we need to generate all these terms for either left or right part of equality and store them in an array or data structure like map/unordered_map in C/C++ or Hashmap in java.Suppose we have stored all values of LHS. Now iterate over all possible terms on the RHS for different values of j and check which value satisfies the LHS equality.If no value satisfies in above step for any candidate of j, print -1. "
},
{
"code": null,
"e": 2456,
"s": 2210,
"text": "The term left and right can take only n distinct values as . Therefore we need to generate all these terms for either left or right part of equality and store them in an array or data structure like map/unordered_map in C/C++ or Hashmap in java."
},
{
"code": null,
"e": 2621,
"s": 2456,
"text": "Suppose we have stored all values of LHS. Now iterate over all possible terms on the RHS for different values of j and check which value satisfies the LHS equality."
},
{
"code": null,
"e": 2693,
"s": 2621,
"text": "If no value satisfies in above step for any candidate of j, print -1. "
},
{
"code": null,
"e": 2697,
"s": 2693,
"text": "C++"
},
{
"code": null,
"e": 2702,
"s": 2697,
"text": "Java"
},
{
"code": null,
"e": 2710,
"s": 2702,
"text": "Python3"
},
{
"code": null,
"e": 2713,
"s": 2710,
"text": "C#"
},
{
"code": null,
"e": 2717,
"s": 2713,
"text": "PHP"
},
{
"code": null,
"e": 2728,
"s": 2717,
"text": "Javascript"
},
{
"code": "// C++ program to calculate discrete logarithm#include<bits/stdc++.h>using namespace std; /* Iterative Function to calculate (x ^ y)%p in O(log y) */int powmod(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // Function to calculate k for given a, b, mint discreteLogarithm(int a, int b, int m) { int n = (int) sqrt (m) + 1; unordered_map<int, int> value; // Store all values of a^(n*i) of LHS for (int i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (int j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision int cur = (powmod (a, j, m) * b) % m; // If collision occurs i.e., LHS = RHS if (value[cur]) { int ans = value[cur] * n - j; // Check whether ans lies below m or not if (ans < m) return ans; } } return -1;} // Driver codeint main(){ int a = 2, b = 3, m = 5; cout << discreteLogarithm(a, b, m) << endl; a = 3, b = 7, m = 11; cout << discreteLogarithm(a, b, m);}",
"e": 4086,
"s": 2728,
"text": null
},
{
"code": "// Java program to calculate discrete logarithm class GFG{/* Iterative Function to calculate (x ^ y)%p inO(log y) */static int powmod(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)>0) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // Function to calculate k for given a, b, mstatic int discreteLogarithm(int a, int b, int m) { int n = (int) (Math.sqrt (m) + 1); int[] value=new int[m]; // Store all values of a^(n*i) of LHS for (int i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (int j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision int cur = (powmod (a, j, m) * b) % m; // If collision occurs i.e., LHS = RHS if (value[cur]>0) { int ans = value[cur] * n - j; // Check whether ans lies below m or not if (ans < m) return ans; } } return -1;} // Driver codepublic static void main(String[] args){ int a = 2, b = 3, m = 5; System.out.println(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; System.out.println(discreteLogarithm(a, b, m));}}// This code is contributed by mits",
"e": 5513,
"s": 4086,
"text": null
},
{
"code": "# Python3 program to calculate# discrete logarithmimport math; # Iterative Function to calculate# (x ^ y)%p in O(log y)def powmod(x, y, p): res = 1; # Initialize result x = x % p; # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p; # y must be even now y = y >> 1; # y = y/2 x = (x * x) % p; return res; # Function to calculate k for given a, b, mdef discreteLogarithm(a, b, m): n = int(math.sqrt(m) + 1); value = [0] * m; # Store all values of a^(n*i) of LHS for i in range(n, 0, -1): value[ powmod (a, i * n, m) ] = i; for j in range(n): # Calculate (a ^ j) * b and check # for collision cur = (powmod (a, j, m) * b) % m; # If collision occurs i.e., LHS = RHS if (value[cur]): ans = value[cur] * n - j; # Check whether ans lies below m or not if (ans < m): return ans; return -1; # Driver codea = 2;b = 3;m = 5;print(discreteLogarithm(a, b, m)); a = 3;b = 7;m = 11;print(discreteLogarithm(a, b, m)); # This code is contributed by mits",
"e": 6754,
"s": 5513,
"text": null
},
{
"code": "// C# program to calculate discrete logarithmusing System;class GFG{/* Iterative Function to calculate (x ^ y)%p inO(log y) */static int powmod(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)>0) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} // Function to calculate k for given a, b, mstatic int discreteLogarithm(int a, int b, int m) { int n = (int) (Math.Sqrt (m) + 1); int[] value=new int[m]; // Store all values of a^(n*i) of LHS for (int i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (int j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision int cur = (powmod (a, j, m) * b) % m; // If collision occurs i.e., LHS = RHS if (value[cur]>0) { int ans = value[cur] * n - j; // Check whether ans lies below m or not if (ans < m) return ans; } } return -1;} // Driver codestatic void Main(){ int a = 2, b = 3, m = 5; Console.WriteLine(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; Console.WriteLine(discreteLogarithm(a, b, m));}}// This code is contributed by mits",
"e": 8169,
"s": 6754,
"text": null
},
{
"code": "<?php// PHP program to calculate// discrete logarithm // Iterative Function to calculate// (x ^ y)%p in O(log y)function powmod($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Function to calculate k for given a, b, mfunction discreteLogarithm($a, $b, $m){ $n = (int)sqrt($m) + 1; $value = array_fill(0, $m, NULL); // Store all values of a^(n*i) of LHS for ($i = $n; $i >= 1; --$i) $value[ powmod ($a, $i * $n, $m) ] = $i; for ($j = 0; $j < $n; ++$j) { // Calculate (a ^ j) * b and check // for collision $cur = (powmod ($a, $j, $m) * $b) % $m; // If collision occurs i.e., LHS = RHS if ($value[$cur]) { $ans = $value[$cur] * $n - $j; // Check whether ans lies below m or not if ($ans < $m) return $ans; } } return -1;} // Driver code$a = 2;$b = 3;$m = 5;echo discreteLogarithm($a, $b, $m), \"\\n\"; $a = 3;$b = 7;$m = 11;echo discreteLogarithm($a, $b, $m), \"\\n\"; // This code is contributed by ajit.?>",
"e": 9536,
"s": 8169,
"text": null
},
{
"code": "<script> // Javascript program to calculate // discrete logarithm /* Iterative Function to calculate (x ^ y)%p in O(log y) */ function powmod(x, y, p) { // Initialize result let res = 1; // Update x if it is more // than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if ((y & 1)>0) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res; } // Function to calculate // k for given a, b, m function discreteLogarithm(a, b, m) { let n = (parseInt(Math.sqrt(m), 10) + 1); let value = new Array(m); value.fill(0); // Store all values of a^(n*i) of LHS for (let i = n; i >= 1; --i) value[ powmod (a, i * n, m) ] = i; for (let j = 0; j < n; ++j) { // Calculate (a ^ j) * b and check // for collision let cur = (powmod (a, j, m) * b) % m; // If collision occurs // i.e., LHS = RHS if (value[cur]>0) { let ans = value[cur] * n - j; // Check whether ans lies // below m or not if (ans < m) return ans; } } return -1; } let a = 2, b = 3, m = 5; document.write( discreteLogarithm(a, b, m) + \"</br>\" ); a = 3; b = 7; m = 11; document.write( discreteLogarithm(a, b, m) + \"</br>\" ); </script>",
"e": 11189,
"s": 9536,
"text": null
},
{
"code": null,
"e": 11199,
"s": 11189,
"text": "Output: "
},
{
"code": null,
"e": 11204,
"s": 11199,
"text": "3\n-1"
},
{
"code": null,
"e": 11507,
"s": 11204,
"text": "Time complexity: O(sqrt(m)*log(b)) Auxiliary space: O(sqrt(m))A possible improvement is to get rid of binary exponentiation or log(b) factor in the second phase of the algorithm. This can be done by keeping a variable that multiplies by ‘a’ each time as ‘an’. Let’s see the program to understand more. "
},
{
"code": null,
"e": 11511,
"s": 11507,
"text": "C++"
},
{
"code": null,
"e": 11516,
"s": 11511,
"text": "Java"
},
{
"code": null,
"e": 11524,
"s": 11516,
"text": "Python3"
},
{
"code": null,
"e": 11527,
"s": 11524,
"text": "C#"
},
{
"code": null,
"e": 11531,
"s": 11527,
"text": "PHP"
},
{
"code": null,
"e": 11542,
"s": 11531,
"text": "Javascript"
},
{
"code": "// C++ program to calculate discrete logarithm#include<bits/stdc++.h>using namespace std; int discreteLogarithm(int a, int b, int m){ int n = (int) sqrt (m) + 1; // Calculate a ^ n int an = 1; for (int i = 0; i<n; ++i) an = (an * a) % m; unordered_map<int, int> value; // Store all values of a^(n*i) of LHS for (int i = 1, cur = an; i<= n; ++i) { if (! value[ cur ]) value[ cur ] = i; cur = (cur * an) % m; } for (int i = 0, cur = b; i<= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur]) { int ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1;} // Driver codeint main(){ int a = 2, b = 3, m = 5; cout << discreteLogarithm(a, b, m) << endl; a = 3, b = 7, m = 11; cout << discreteLogarithm(a, b, m);}",
"e": 12473,
"s": 11542,
"text": null
},
{
"code": "// Java program to calculate discrete logarithm class GFG{ static int discreteLogarithm(int a, int b, int m) { int n = (int) (Math.sqrt (m) + 1); // Calculate a ^ n int an = 1; for (int i = 0; i < n; ++i) an = (an * a) % m; int[] value=new int[m]; // Store all values of a^(n*i) of LHS for (int i = 1, cur = an; i <= n; ++i) { if (value[ cur ] == 0) value[ cur ] = i; cur = (cur * an) % m; } for (int i = 0, cur = b; i <= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur] > 0) { int ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1; } // Driver code public static void main(String[] args) { int a = 2, b = 3, m = 5; System.out.println(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; System.out.println(discreteLogarithm(a, b, m)); }} // This code is contributed by mits",
"e": 13633,
"s": 12473,
"text": null
},
{
"code": "# Python3 program to calculate# discrete logarithmimport math; def discreteLogarithm(a, b, m): n = int(math.sqrt (m) + 1); # Calculate a ^ n an = 1; for i in range(n): an = (an * a) % m; value = [0] * m; # Store all values of a^(n*i) of LHS cur = an; for i in range(1, n + 1): if (value[ cur ] == 0): value[ cur ] = i; cur = (cur * an) % m; cur = b; for i in range(n + 1): # Calculate (a ^ j) * b and check # for collision if (value[cur] > 0): ans = value[cur] * n - i; if (ans < m): return ans; cur = (cur * a) % m; return -1; # Driver codea = 2;b = 3;m = 5;print(discreteLogarithm(a, b, m)); a = 3;b = 7;m = 11;print(discreteLogarithm(a, b, m)); # This code is contributed by mits",
"e": 14465,
"s": 13633,
"text": null
},
{
"code": "// C# program to calculate discrete logarithmusing System; class GFG{ static int discreteLogarithm(int a, int b, int m){ int n = (int) (Math.Sqrt (m) + 1); // Calculate a ^ n int an = 1; for (int i = 0; i < n; ++i) an = (an * a) % m; int[] value = new int[m]; // Store all values of a^(n*i) of LHS for (int i = 1, cur = an; i<= n; ++i) { if (value[ cur ] == 0) value[ cur ] = i; cur = (cur * an) % m; } for (int i = 0, cur = b; i<= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur] > 0) { int ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1;} // Driver codestatic void Main(){ int a = 2, b = 3, m = 5; Console.WriteLine(discreteLogarithm(a, b, m)); a = 3; b = 7; m = 11; Console.WriteLine(discreteLogarithm(a, b, m));}} // This code is contributed by mits",
"e": 15463,
"s": 14465,
"text": null
},
{
"code": "<?php// PHP program to calculate discrete logarithm function discreteLogarithm($a, $b, $m){ $n = (int)sqrt ($m) + 1; // Calculate a ^ n $an = 1; for ($i = 0; $i < $n; ++$i) $an = ($an * $a) % $m; $value = array_fill(0, $m, NULL); // Store all values of a^(n*i) of LHS for ($i = 1, $cur = $an; $i<= $n; ++$i) { if (! $value[ $cur ]) $value[ $cur ] = $i; $cur = ($cur * $an) % $m; } for ($i = 0, $cur = $b; $i<= $n; ++$i) { // Calculate (a ^ j) * b and check // for collision if ($value[$cur]) { $ans = $value[$cur] * $n - $i; if ($ans < $m) return $ans; } $cur = ($cur * $a) % $m; } return -1;} // Driver code$a = 2;$b = 3;$m = 5;echo discreteLogarithm($a, $b, $m), \"\\n\"; $a = 3;$b = 7;$m = 11;echo discreteLogarithm($a, $b, $m); // This code is contributed by ajit.?>",
"e": 16385,
"s": 15463,
"text": null
},
{
"code": "<script> // Javascript program to calculate // discrete logarithm function discreteLogarithm(a, b, m) { let n = parseInt(Math.sqrt(m), 10) + 1; // Calculate a ^ n let an = 1; for (let i = 0; i < n; ++i) an = (an * a) % m; let value = new Array(m); value.fill(0); // Store all values of a^(n*i) of LHS for (let i = 1, cur = an; i<= n; ++i) { if (value[ cur ] == 0) value[ cur ] = i; cur = (cur * an) % m; } for (let i = 0, cur = b; i<= n; ++i) { // Calculate (a ^ j) * b and check // for collision if (value[cur] > 0) { let ans = value[cur] * n - i; if (ans < m) return ans; } cur = (cur * a) % m; } return -1; } let a = 2, b = 3, m = 5; document.write(discreteLogarithm(a, b, m) + \"</br>\"); a = 3; b = 7; m = 11; document.write(discreteLogarithm(a, b, m)); </script>",
"e": 17466,
"s": 16385,
"text": null
},
{
"code": null,
"e": 17476,
"s": 17466,
"text": "Output: "
},
{
"code": null,
"e": 17481,
"s": 17476,
"text": "3\n-1"
},
{
"code": null,
"e": 17952,
"s": 17481,
"text": "Time complexity: O(sqrt(m)) Auxiliary space: O(sqrt(m))Reference: http://e-maxx-eng.appspot.com/algebra/discrete-log.html https://en.wikipedia.org/wiki/Baby-step_giant-stepThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 17958,
"s": 17952,
"text": "jit_t"
},
{
"code": null,
"e": 17971,
"s": 17958,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 17980,
"s": 17971,
"text": "suresh07"
},
{
"code": null,
"e": 17995,
"s": 17980,
"text": "rameshtravel07"
},
{
"code": null,
"e": 18013,
"s": 17995,
"text": "germanshephered48"
},
{
"code": null,
"e": 18032,
"s": 18013,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 18046,
"s": 18032,
"text": "number-theory"
},
{
"code": null,
"e": 18059,
"s": 18046,
"text": "Mathematical"
},
{
"code": null,
"e": 18073,
"s": 18059,
"text": "number-theory"
},
{
"code": null,
"e": 18086,
"s": 18073,
"text": "Mathematical"
},
{
"code": null,
"e": 18105,
"s": 18086,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 18203,
"s": 18105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18233,
"s": 18203,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 18276,
"s": 18233,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 18336,
"s": 18276,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 18351,
"s": 18336,
"text": "C++ Data Types"
},
{
"code": null,
"e": 18375,
"s": 18351,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 18394,
"s": 18375,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 18415,
"s": 18394,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 18429,
"s": 18415,
"text": "Prime Numbers"
},
{
"code": null,
"e": 18471,
"s": 18429,
"text": "Program to find GCD or HCF of two numbers"
}
] |
Ruby redo and retry Statement | 17 Sep, 2019
In Ruby, Redo statement is used to repeat the current iteration of the loop. redo always used inside the loop. The redo statement restarts the loop without evaluating the condition again.
# Ruby program of using redo statement #!/usr/bin/rubyrestart = false # Using for loopfor x in 2..20 if x == 15 if restart == false # Printing values puts "Re-doing when x = " + x.to_s restart = true # Using Redo Statement redo end end puts xend
Output:
2
3
4
5
6
7
8
9
10
11
12
13
14
Re-doing when x = 15
15
16
17
18
19
20
In above example, redo statement apply when x = 15.
To repeat the whole loop iteration from the start the retry statement is used. retry always used inside the loop.
Example #1:
# Ruby program of retry statement # Using do loop10.times do |i| begin puts "Iteration #{i}" raise if i > 2 rescue # Using retry retry endend
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 3
Iteration 3
...
Example #2:
# Ruby program of retry statementdef geeks attempt_again = true p 'checking' begin # This is the point where the control flow jumps p 'crash' raise 'foo' rescue Exception => e if attempt_again attempt_again = false # Using retry retry end endend
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "In Ruby, Redo statement is used to repeat the current iteration of the loop. redo always used inside the loop. The redo statement restarts the loop without evaluating the condition again."
},
{
"code": "# Ruby program of using redo statement #!/usr/bin/rubyrestart = false # Using for loopfor x in 2..20 if x == 15 if restart == false # Printing values puts \"Re-doing when x = \" + x.to_s restart = true # Using Redo Statement redo end end puts xend",
"e": 546,
"s": 216,
"text": null
},
{
"code": null,
"e": 554,
"s": 546,
"text": "Output:"
},
{
"code": null,
"e": 624,
"s": 554,
"text": "2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\nRe-doing when x = 15\n15\n16\n17\n18\n19\n20"
},
{
"code": null,
"e": 676,
"s": 624,
"text": "In above example, redo statement apply when x = 15."
},
{
"code": null,
"e": 790,
"s": 676,
"text": "To repeat the whole loop iteration from the start the retry statement is used. retry always used inside the loop."
},
{
"code": null,
"e": 802,
"s": 790,
"text": "Example #1:"
},
{
"code": "# Ruby program of retry statement # Using do loop10.times do |i| begin puts \"Iteration #{i}\" raise if i > 2 rescue # Using retry retry endend",
"e": 962,
"s": 802,
"text": null
},
{
"code": null,
"e": 970,
"s": 962,
"text": "Output:"
},
{
"code": null,
"e": 1046,
"s": 970,
"text": "Iteration 0\nIteration 1\nIteration 2\nIteration 3\nIteration 3\nIteration 3\n..."
},
{
"code": null,
"e": 1058,
"s": 1046,
"text": "Example #2:"
},
{
"code": "# Ruby program of retry statementdef geeks attempt_again = true p 'checking' begin # This is the point where the control flow jumps p 'crash' raise 'foo' rescue Exception => e if attempt_again attempt_again = false # Using retry retry end endend",
"e": 1362,
"s": 1058,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1362,
"text": "Ruby"
}
] |
How to Replace Values in Column Based on Condition in Pandas? | 28 Nov, 2021
In this article, we are going to discuss the various methods to replace the values in the columns of a dataset in pandas with conditions. This can be done by many methods lets see all of those methods in detail.
With this method, we can access a group of rows or columns with a condition or a boolean array. If we can access it we can also manipulate the values, Yes! this is our first method by the dataframe.loc[] function in pandas we can access a column and change its values with a condition.
Now, we are going to change all the “male” to 1 in the gender column.
Syntax: df.loc[ df[“column_name”] == “some_value”, “column_name”] = “value”
some_value = The value that needs to be replaced
value = The value that should be placed instead.
Note: You can also use other operators to construct the condition to change numerical values..
Python3
# Importing the librariesimport pandas as pdimport numpy as np # dataStudent = { 'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'], 'gender': ['male', 'male', 'male', 'female', 'female', 'male'], 'math score': [50, 100, 70, 80, 75, 40], 'test preparation': ['none', 'completed', 'none', 'completed', 'completed', 'none'],} # creating a Dataframe objectdf = pd.DataFrame(Student) # Applying the conditiondf.loc[df["gender"] == "male", "gender"] = 1
Output:
Another method we are going to see is with the NumPy library. NumPy is a very popular library used for calculations with 2d and 3d arrays. It gives us a very useful method where() to access the specific rows or columns with a condition. We can also use this function to change a specific value of the columns.
This numpy.where() function should be written with the condition followed by the value if the condition is true and a value if the condition is false. Now, we are going to change all the “female” to 0 and “male” to 1 in the gender column.
syntax: df[“column_name”] = np.where(df[“column_name”]==”some_value”, value_if_true, value_if_false)
Python3
# Importing the librariesimport pandas as pdimport numpy as np # datastudent = { 'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'], 'gender': ['male', 'male', 'male', 'female', 'female', 'male'], 'math score': [50, 100, 70, 80, 75, 40], 'test preparation': ['none', 'completed', 'none', 'completed', 'completed', 'none'],} # creating a Dataframe objectdf = pd.DataFrame(student) # Applying the conditiondf["gender"] = np.where(df["gender"] == "female", 0, 1)
Output:
Pandas masking function is made for replacing the values of any row or a column with a condition. Now using this masking condition we are going to change all the “female” to 0 in the gender column.
syntax: df[‘column_name’].mask( df[‘column_name’] == ‘some_value’, value , inplace=True )
Python3
# Importing the librariesimport pandas as pdimport numpy as np # datastudent = { 'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'], 'gender': ['male', 'male', 'male', 'female', 'female', 'male'], 'math score': [50, 100, 70, 80, 75, 40], 'test preparation': ['none', 'completed', 'none', 'completed', 'completed', 'none'],} # creating a Dataframe objectdf = pd.DataFrame(student) # Applying the conditiondf['gender'].mask(df['gender'] == 'female', 0, inplace=True) # Try this too#df['math score'].mask(df['math score'] >=60 ,'good', inplace=True)
Output:
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 266,
"s": 54,
"text": "In this article, we are going to discuss the various methods to replace the values in the columns of a dataset in pandas with conditions. This can be done by many methods lets see all of those methods in detail."
},
{
"code": null,
"e": 552,
"s": 266,
"text": "With this method, we can access a group of rows or columns with a condition or a boolean array. If we can access it we can also manipulate the values, Yes! this is our first method by the dataframe.loc[] function in pandas we can access a column and change its values with a condition."
},
{
"code": null,
"e": 622,
"s": 552,
"text": "Now, we are going to change all the “male” to 1 in the gender column."
},
{
"code": null,
"e": 698,
"s": 622,
"text": "Syntax: df.loc[ df[“column_name”] == “some_value”, “column_name”] = “value”"
},
{
"code": null,
"e": 747,
"s": 698,
"text": "some_value = The value that needs to be replaced"
},
{
"code": null,
"e": 796,
"s": 747,
"text": "value = The value that should be placed instead."
},
{
"code": null,
"e": 891,
"s": 796,
"text": "Note: You can also use other operators to construct the condition to change numerical values.."
},
{
"code": null,
"e": 899,
"s": 891,
"text": "Python3"
},
{
"code": "# Importing the librariesimport pandas as pdimport numpy as np # dataStudent = { 'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'], 'gender': ['male', 'male', 'male', 'female', 'female', 'male'], 'math score': [50, 100, 70, 80, 75, 40], 'test preparation': ['none', 'completed', 'none', 'completed', 'completed', 'none'],} # creating a Dataframe objectdf = pd.DataFrame(Student) # Applying the conditiondf.loc[df[\"gender\"] == \"male\", \"gender\"] = 1",
"e": 1400,
"s": 899,
"text": null
},
{
"code": null,
"e": 1408,
"s": 1400,
"text": "Output:"
},
{
"code": null,
"e": 1719,
"s": 1408,
"text": "Another method we are going to see is with the NumPy library. NumPy is a very popular library used for calculations with 2d and 3d arrays. It gives us a very useful method where() to access the specific rows or columns with a condition. We can also use this function to change a specific value of the columns. "
},
{
"code": null,
"e": 1958,
"s": 1719,
"text": "This numpy.where() function should be written with the condition followed by the value if the condition is true and a value if the condition is false. Now, we are going to change all the “female” to 0 and “male” to 1 in the gender column."
},
{
"code": null,
"e": 2059,
"s": 1958,
"text": "syntax: df[“column_name”] = np.where(df[“column_name”]==”some_value”, value_if_true, value_if_false)"
},
{
"code": null,
"e": 2067,
"s": 2059,
"text": "Python3"
},
{
"code": "# Importing the librariesimport pandas as pdimport numpy as np # datastudent = { 'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'], 'gender': ['male', 'male', 'male', 'female', 'female', 'male'], 'math score': [50, 100, 70, 80, 75, 40], 'test preparation': ['none', 'completed', 'none', 'completed', 'completed', 'none'],} # creating a Dataframe objectdf = pd.DataFrame(student) # Applying the conditiondf[\"gender\"] = np.where(df[\"gender\"] == \"female\", 0, 1)",
"e": 2581,
"s": 2067,
"text": null
},
{
"code": null,
"e": 2589,
"s": 2581,
"text": "Output:"
},
{
"code": null,
"e": 2787,
"s": 2589,
"text": "Pandas masking function is made for replacing the values of any row or a column with a condition. Now using this masking condition we are going to change all the “female” to 0 in the gender column."
},
{
"code": null,
"e": 2877,
"s": 2787,
"text": "syntax: df[‘column_name’].mask( df[‘column_name’] == ‘some_value’, value , inplace=True )"
},
{
"code": null,
"e": 2885,
"s": 2877,
"text": "Python3"
},
{
"code": "# Importing the librariesimport pandas as pdimport numpy as np # datastudent = { 'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'], 'gender': ['male', 'male', 'male', 'female', 'female', 'male'], 'math score': [50, 100, 70, 80, 75, 40], 'test preparation': ['none', 'completed', 'none', 'completed', 'completed', 'none'],} # creating a Dataframe objectdf = pd.DataFrame(student) # Applying the conditiondf['gender'].mask(df['gender'] == 'female', 0, inplace=True) # Try this too#df['math score'].mask(df['math score'] >=60 ,'good', inplace=True)",
"e": 3486,
"s": 2885,
"text": null
},
{
"code": null,
"e": 3494,
"s": 3486,
"text": "Output:"
},
{
"code": null,
"e": 3501,
"s": 3494,
"text": "Picked"
},
{
"code": null,
"e": 3525,
"s": 3501,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3539,
"s": 3525,
"text": "Python-pandas"
},
{
"code": null,
"e": 3546,
"s": 3539,
"text": "Python"
},
{
"code": null,
"e": 3644,
"s": 3546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3676,
"s": 3644,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3703,
"s": 3676,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3724,
"s": 3703,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3747,
"s": 3724,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3778,
"s": 3747,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3834,
"s": 3778,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3876,
"s": 3834,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3918,
"s": 3876,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3957,
"s": 3918,
"text": "Python | Get unique values from a list"
}
] |
JavaScript | promise resolve() Method | 31 May, 2022
The Promise is an object that represents either completion or failure of a user task. A promise in JavaScript can be in three states pending, fulfilled or rejected. The main advantage of using a Promise in JavaScript is that a user can assign callback functions to the promises in case of a rejection or fulfillment of Promise, also by using promises one can easily handle the control flow of all the Asynchronous events or data upcoming. As the name suggests a promise is either kept or broken. So, a promise is either completed(kept) or rejected(broken).Promise resolve() method: Promise.resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened:
If the value is a promise then promise is returned.
If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.
The promise fulfilled with its value will be returned.
Syntax:
Promise.resolve(value);
Parameters: Value(s) to be resolved by this Promise.Return Value: Either the promise of the promise fulfilled with its value is returned.Examples:
javascript
<script> var promise = Promise.resolve(17468); promise.then(function(val) { console.log(val);});//Output: 17468</script>
Output:
17468
The above example is made using old version approach we may also use the newest arrow function based approach and also try to avoid writing var datatype since it may mix up several other variables and may produce incorrect result. Below is the shortest approach for the above stated approach.
Following is the code snippet which shows the other version of the above illustrated approach-
Javascript
Promise.resolve(17468).then((value) => console.log(value)); // This code is contributed by Aman Singla....
Output:
17468
Resolving an array: Here in the below example, we will be using a timer function called setTimeout() will be responsible for the execution of the values which are passed inside resolve() which is passed inside that timer function.
javascript
<script> const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve([89, 45, 323]); }, 5000); }); promise.then(values => { console.log(values[1]);}); </script>
Output:
45
Resolving another Promise: In below example we will be resolving the first promise inside another newly created promise in which we have defined one timer function (setTimeout).
javascript
<script> const promise = Promise.resolve(3126); const promise1 = new Promise((resolve, reject) => { setTimeout(() => { promise.then(val => console.log(val)); }, 5000);}); promise1.then(vals => { console.log(vals);}); </script>
Output:
3126
Supported Browsers:
Google Chrome 32 and above
Mozilla Firefox 29 and above
Opera 19 and above
Safari 8 and above
Edge 12 and above
Internet Explorer not supported
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
sooda367
ysachin2314
amansingla
kumargaurav97520
javascript-functions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 742,
"s": 28,
"text": "The Promise is an object that represents either completion or failure of a user task. A promise in JavaScript can be in three states pending, fulfilled or rejected. The main advantage of using a Promise in JavaScript is that a user can assign callback functions to the promises in case of a rejection or fulfillment of Promise, also by using promises one can easily handle the control flow of all the Asynchronous events or data upcoming. As the name suggests a promise is either kept or broken. So, a promise is either completed(kept) or rejected(broken).Promise resolve() method: Promise.resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: "
},
{
"code": null,
"e": 794,
"s": 742,
"text": "If the value is a promise then promise is returned."
},
{
"code": null,
"e": 920,
"s": 794,
"text": "If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state."
},
{
"code": null,
"e": 975,
"s": 920,
"text": "The promise fulfilled with its value will be returned."
},
{
"code": null,
"e": 984,
"s": 975,
"text": "Syntax: "
},
{
"code": null,
"e": 1008,
"s": 984,
"text": "Promise.resolve(value);"
},
{
"code": null,
"e": 1157,
"s": 1008,
"text": "Parameters: Value(s) to be resolved by this Promise.Return Value: Either the promise of the promise fulfilled with its value is returned.Examples: "
},
{
"code": null,
"e": 1168,
"s": 1157,
"text": "javascript"
},
{
"code": "<script> var promise = Promise.resolve(17468); promise.then(function(val) { console.log(val);});//Output: 17468</script>",
"e": 1295,
"s": 1168,
"text": null
},
{
"code": null,
"e": 1304,
"s": 1295,
"text": "Output: "
},
{
"code": null,
"e": 1310,
"s": 1304,
"text": "17468"
},
{
"code": null,
"e": 1603,
"s": 1310,
"text": "The above example is made using old version approach we may also use the newest arrow function based approach and also try to avoid writing var datatype since it may mix up several other variables and may produce incorrect result. Below is the shortest approach for the above stated approach."
},
{
"code": null,
"e": 1698,
"s": 1603,
"text": "Following is the code snippet which shows the other version of the above illustrated approach-"
},
{
"code": null,
"e": 1709,
"s": 1698,
"text": "Javascript"
},
{
"code": "Promise.resolve(17468).then((value) => console.log(value)); // This code is contributed by Aman Singla....",
"e": 1816,
"s": 1709,
"text": null
},
{
"code": null,
"e": 1824,
"s": 1816,
"text": "Output:"
},
{
"code": null,
"e": 1830,
"s": 1824,
"text": "17468"
},
{
"code": null,
"e": 2062,
"s": 1830,
"text": "Resolving an array: Here in the below example, we will be using a timer function called setTimeout() will be responsible for the execution of the values which are passed inside resolve() which is passed inside that timer function."
},
{
"code": null,
"e": 2073,
"s": 2062,
"text": "javascript"
},
{
"code": "<script> const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve([89, 45, 323]); }, 5000); }); promise.then(values => { console.log(values[1]);}); </script>",
"e": 2287,
"s": 2073,
"text": null
},
{
"code": null,
"e": 2296,
"s": 2287,
"text": "Output: "
},
{
"code": null,
"e": 2300,
"s": 2296,
"text": "45 "
},
{
"code": null,
"e": 2478,
"s": 2300,
"text": "Resolving another Promise: In below example we will be resolving the first promise inside another newly created promise in which we have defined one timer function (setTimeout)."
},
{
"code": null,
"e": 2489,
"s": 2478,
"text": "javascript"
},
{
"code": "<script> const promise = Promise.resolve(3126); const promise1 = new Promise((resolve, reject) => { setTimeout(() => { promise.then(val => console.log(val)); }, 5000);}); promise1.then(vals => { console.log(vals);}); </script>",
"e": 2736,
"s": 2489,
"text": null
},
{
"code": null,
"e": 2745,
"s": 2736,
"text": "Output: "
},
{
"code": null,
"e": 2751,
"s": 2745,
"text": "3126 "
},
{
"code": null,
"e": 2772,
"s": 2751,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 2799,
"s": 2772,
"text": "Google Chrome 32 and above"
},
{
"code": null,
"e": 2828,
"s": 2799,
"text": "Mozilla Firefox 29 and above"
},
{
"code": null,
"e": 2847,
"s": 2828,
"text": "Opera 19 and above"
},
{
"code": null,
"e": 2866,
"s": 2847,
"text": "Safari 8 and above"
},
{
"code": null,
"e": 2884,
"s": 2866,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 2916,
"s": 2884,
"text": "Internet Explorer not supported"
},
{
"code": null,
"e": 3135,
"s": 2916,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3144,
"s": 3135,
"text": "sooda367"
},
{
"code": null,
"e": 3156,
"s": 3144,
"text": "ysachin2314"
},
{
"code": null,
"e": 3167,
"s": 3156,
"text": "amansingla"
},
{
"code": null,
"e": 3184,
"s": 3167,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 3205,
"s": 3184,
"text": "javascript-functions"
},
{
"code": null,
"e": 3212,
"s": 3205,
"text": "Picked"
},
{
"code": null,
"e": 3223,
"s": 3212,
"text": "JavaScript"
},
{
"code": null,
"e": 3240,
"s": 3223,
"text": "Web Technologies"
},
{
"code": null,
"e": 3338,
"s": 3240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3399,
"s": 3338,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3471,
"s": 3399,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3511,
"s": 3471,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3563,
"s": 3511,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3604,
"s": 3563,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3666,
"s": 3604,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3699,
"s": 3666,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3760,
"s": 3699,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3810,
"s": 3760,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Exceptional Split in String | 22 Apr, 2020
Sometimes, while working with Strings, we may need to perform the split operation. The straight forward split is easy. But sometimes, we may have a problem in which we need to perform split on certain character but have exceptions. This discusses split on comma, with exception that comma should not be enclosed by brackets. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + strip()This is brute force way in which we perform this task. In this we construct the each element of list as words in String accounting for brackets and comma to perform split.
# Python3 code to demonstrate working of # Exceptional Split in String# Using loop + split() # initializing stringtest_str = "gfg, is, (best, for), geeks" # printing original stringprint("The original string is : " + test_str) # Exceptional Split in String# Using loop + split()temp = ''res = []check = 0for ele in test_str: if ele == '(': check += 1 elif ele == ')': check -= 1 if ele == ', ' and check == 0: if temp.strip(): res.append(temp) temp = '' else: temp += eleif temp.strip(): res.append(temp) # printing result print("The string after exceptional split : " + str(res))
The original string is : gfg, is, (best, for), geeks
The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']
Method #2 : Using regex()This is yet another way in which this task can be performed. In this, we use a regex instead of manual brute force logic for brackets comma and omit that from getting split.
# Python3 code to demonstrate working of # Exceptional Split in String# Using regex()import re # initializing stringtest_str = "gfg, is, (best, for), geeks" # printing original stringprint("The original string is : " + test_str) # Exceptional Split in String# Using regex()res = re.split(r', (?!\S\)|\()', test_str) # printing result print("The string after exceptional split : " + str(res))
The original string is : gfg, is, (best, for), geeks
The string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 416,
"s": 28,
"text": "Sometimes, while working with Strings, we may need to perform the split operation. The straight forward split is easy. But sometimes, we may have a problem in which we need to perform split on certain character but have exceptions. This discusses split on comma, with exception that comma should not be enclosed by brackets. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 620,
"s": 416,
"text": "Method #1 : Using loop + strip()This is brute force way in which we perform this task. In this we construct the each element of list as words in String accounting for brackets and comma to perform split."
},
{
"code": "# Python3 code to demonstrate working of # Exceptional Split in String# Using loop + split() # initializing stringtest_str = \"gfg, is, (best, for), geeks\" # printing original stringprint(\"The original string is : \" + test_str) # Exceptional Split in String# Using loop + split()temp = ''res = []check = 0for ele in test_str: if ele == '(': check += 1 elif ele == ')': check -= 1 if ele == ', ' and check == 0: if temp.strip(): res.append(temp) temp = '' else: temp += eleif temp.strip(): res.append(temp) # printing result print(\"The string after exceptional split : \" + str(res)) ",
"e": 1267,
"s": 620,
"text": null
},
{
"code": null,
"e": 1399,
"s": 1267,
"text": "The original string is : gfg, is, (best, for), geeks\nThe string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']\n"
},
{
"code": null,
"e": 1600,
"s": 1401,
"text": "Method #2 : Using regex()This is yet another way in which this task can be performed. In this, we use a regex instead of manual brute force logic for brackets comma and omit that from getting split."
},
{
"code": "# Python3 code to demonstrate working of # Exceptional Split in String# Using regex()import re # initializing stringtest_str = \"gfg, is, (best, for), geeks\" # printing original stringprint(\"The original string is : \" + test_str) # Exceptional Split in String# Using regex()res = re.split(r', (?!\\S\\)|\\()', test_str) # printing result print(\"The string after exceptional split : \" + str(res)) ",
"e": 1997,
"s": 1600,
"text": null
},
{
"code": null,
"e": 2129,
"s": 1997,
"text": "The original string is : gfg, is, (best, for), geeks\nThe string after exceptional split : ['gfg', ' is', ' (best, for)', ' geeks']\n"
},
{
"code": null,
"e": 2152,
"s": 2129,
"text": "Python string-programs"
},
{
"code": null,
"e": 2159,
"s": 2152,
"text": "Python"
},
{
"code": null,
"e": 2175,
"s": 2159,
"text": "Python Programs"
},
{
"code": null,
"e": 2273,
"s": 2175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2318,
"s": 2273,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2334,
"s": 2318,
"text": "Deque in Python"
},
{
"code": null,
"e": 2356,
"s": 2334,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2372,
"s": 2356,
"text": "Queue in Python"
},
{
"code": null,
"e": 2422,
"s": 2372,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2444,
"s": 2422,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2478,
"s": 2444,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 2517,
"s": 2478,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2554,
"s": 2517,
"text": "Python Program for Fibonacci numbers"
}
] |
File.OpenRead() Method in C# with Examples | 25 Feb, 2021
File.OpenRead(String) is an inbuilt File class method which is used to open an existing file for reading.Syntax:
public static System.IO.FileStream OpenRead (string path);
Parameter: This function accepts a parameter which is illustrated below:
path: This is the specified file which is going to be opened for reading.
Exceptions:
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
ArgumentNullException: The path is null.
PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: The specified path is invalid.
UnauthorizedAccessException: The path specified a directory. OR the caller does not have the required permission.
FileNotFoundException: The file specified in the path was not found.
NotSupportedException: The path is in an invalid format.
IOException: An I/O error occurred while opening the file.
Return Value: Returns a read-only FileStream on the specified path.Below are the programs to illustrate the File.OpenRead(String) method.Program 1: Before running the below code, a file file.txt is created with some contents shown below
Below code open the file file.txt for reading.
C#
// C# program to illustrate the usage// of File.OpenRead(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class Test { public static void Main() { // Specifying a file string path = @"file.txt"; // Opening the existing file for reading using(FileStream fs = File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { // Printing the file contents Console.WriteLine(temp.GetString(b)); } } }}
Executing:
GeeksforGeeks
Program 2: Initially, a file file.txt is created with some contents shown below-
This below code will overwrite the file contents with other specified contents then final contents will be printed.
C#
// C# program to illustrate the usage// of File.OpenRead(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Opening the file for overwriting with // another contents using(FileStream fs = File.OpenWrite(path)) { Byte[] info = new UTF8Encoding(true).GetBytes("GFG is a CS portal."); fs.Write(info, 0, info.Length); } // Opening the existing file for reading using(FileStream fs = File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { // Printing the file contents Console.WriteLine(temp.GetString(b)); } } }}
Executing:
GFG is a CS portal.
arorakashish0911
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C# | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 143,
"s": 28,
"text": "File.OpenRead(String) is an inbuilt File class method which is used to open an existing file for reading.Syntax: "
},
{
"code": null,
"e": 202,
"s": 143,
"text": "public static System.IO.FileStream OpenRead (string path);"
},
{
"code": null,
"e": 277,
"s": 202,
"text": "Parameter: This function accepts a parameter which is illustrated below: "
},
{
"code": null,
"e": 351,
"s": 277,
"text": "path: This is the specified file which is going to be opened for reading."
},
{
"code": null,
"e": 364,
"s": 351,
"text": "Exceptions: "
},
{
"code": null,
"e": 510,
"s": 364,
"text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars."
},
{
"code": null,
"e": 551,
"s": 510,
"text": "ArgumentNullException: The path is null."
},
{
"code": null,
"e": 654,
"s": 551,
"text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 713,
"s": 654,
"text": "DirectoryNotFoundException: The specified path is invalid."
},
{
"code": null,
"e": 827,
"s": 713,
"text": "UnauthorizedAccessException: The path specified a directory. OR the caller does not have the required permission."
},
{
"code": null,
"e": 896,
"s": 827,
"text": "FileNotFoundException: The file specified in the path was not found."
},
{
"code": null,
"e": 953,
"s": 896,
"text": "NotSupportedException: The path is in an invalid format."
},
{
"code": null,
"e": 1012,
"s": 953,
"text": "IOException: An I/O error occurred while opening the file."
},
{
"code": null,
"e": 1250,
"s": 1012,
"text": "Return Value: Returns a read-only FileStream on the specified path.Below are the programs to illustrate the File.OpenRead(String) method.Program 1: Before running the below code, a file file.txt is created with some contents shown below "
},
{
"code": null,
"e": 1298,
"s": 1250,
"text": "Below code open the file file.txt for reading. "
},
{
"code": null,
"e": 1301,
"s": 1298,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.OpenRead(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class Test { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Opening the existing file for reading using(FileStream fs = File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { // Printing the file contents Console.WriteLine(temp.GetString(b)); } } }}",
"e": 1966,
"s": 1301,
"text": null
},
{
"code": null,
"e": 1979,
"s": 1966,
"text": "Executing: "
},
{
"code": null,
"e": 1993,
"s": 1979,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 2075,
"s": 1993,
"text": "Program 2: Initially, a file file.txt is created with some contents shown below- "
},
{
"code": null,
"e": 2192,
"s": 2075,
"text": "This below code will overwrite the file contents with other specified contents then final contents will be printed. "
},
{
"code": null,
"e": 2195,
"s": 2192,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.OpenRead(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Opening the file for overwriting with // another contents using(FileStream fs = File.OpenWrite(path)) { Byte[] info = new UTF8Encoding(true).GetBytes(\"GFG is a CS portal.\"); fs.Write(info, 0, info.Length); } // Opening the existing file for reading using(FileStream fs = File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { // Printing the file contents Console.WriteLine(temp.GetString(b)); } } }}",
"e": 3129,
"s": 2195,
"text": null
},
{
"code": null,
"e": 3140,
"s": 3129,
"text": "Executing:"
},
{
"code": null,
"e": 3160,
"s": 3140,
"text": "GFG is a CS portal."
},
{
"code": null,
"e": 3177,
"s": 3160,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3198,
"s": 3177,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 3201,
"s": 3198,
"text": "C#"
},
{
"code": null,
"e": 3299,
"s": 3201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3342,
"s": 3299,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3391,
"s": 3342,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3414,
"s": 3391,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 3430,
"s": 3414,
"text": "C# | List Class"
},
{
"code": null,
"e": 3458,
"s": 3430,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 3519,
"s": 3458,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 3542,
"s": 3519,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 3564,
"s": 3542,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 3589,
"s": 3564,
"text": "Lambda Expressions in C#"
}
] |
TELNET and SSH in Cisco devices | 09 Aug, 2019
We can take access to a cisco router or switch either through a console cable or taking remote access through well known protocols Telnet or ssh (Secure Shell). Telnet and ssh are both application layer protocols used to take remote access and manage a device.
1. Telnet:As stated, Telnet is an application layer protocol which uses TCP port number 23, used to take remote access of a device.
Features –
It doesn’t support authentication.Data is sent in clear text therefore less secure.No encryption mechanism is used.Designed to work in local networks only.
It doesn’t support authentication.
Data is sent in clear text therefore less secure.
No encryption mechanism is used.
Designed to work in local networks only.
Configuration –
There is a simple topology in which two routers are directly connected to each other namely Router1 and Router2. Router1 have IP address 192.168.1.1/24 on its fa0/0 port and Router2 has IP address 192.168.1.2/24 on its fa0/0 port.Here, we will enable telnet on Router1 and take access through Router2.Configuring telnet on Router1:
Router1(config)#line vty 0 4
Router1(config-line)#password GeeksforGeeks
Router1(config-line)#exit
Here, 0 4 means that we can have 5 concurrent sessions at a time.Taking access through Router2:
Router2#telnet 192.168.1.1
Router1>
Note – On Cisco devices, if you want to take access of a device, you have to use vty lines for it.
Troubleshooting –While using telnet or ssh, keep these things in mind:
The (client) device through which you want to take access should be reachable to the (server) device you want to take access.If the device is reachable and you are not able to Telnet, then you have not set a password on vty line. It is mandatory to set a password on vty line while using Telnet or SSH.
The (client) device through which you want to take access should be reachable to the (server) device you want to take access.
If the device is reachable and you are not able to Telnet, then you have not set a password on vty line. It is mandatory to set a password on vty line while using Telnet or SSH.
Note –AAA services can also be used to set password on line vty lines. Either a local database of a device (router) or ACS server can be used for the password for vty lines.But here we are talking about a simple configuration only.
2. Secure Shell (SSH):SSH is also an application client-server protocol used to take remote access of a device. It uses TCP port number 23.
Features –
Unlike telnet, it provides authentication methods.The data sent is in encrypted form.It is designed to work in public network.It uses public key for encryption mechanism.
Unlike telnet, it provides authentication methods.
The data sent is in encrypted form.
It is designed to work in public network.
It uses public key for encryption mechanism.
In short, SSH is more secure than telnet and has almost replaced telnet.
Configuration –
We are using the same simple topology. Router1 have IP address 192.168.1.1/24 on its fa0/0 port and Router2 has IP address 192.168.1.2/24 on its fa0/0 port.We will ssh Router1 from Router2 Configuring ssh on Router1.
Router(config)#ip domain-name GeeksforGeeks.com
Router(config)#hostname Router1
Router1(config)#line vty 0 4
Router1(config-line)#transport input ssh
Router1(config-line)password GeeksforGeeks
Router1(config-line)#login
Router1(config)#crypto key generate rsa label Cisco modulus 1024
Here, note that it is necessary to give domain name as ssh uses it and password for encryption purpose.If domain-name and hostname are not provided then crypro keys will not be generated. We have provided a password for vty line login and at last we have created key of 1024 bytes and labelled it as Cisco.
Note –The last command “crypto key generate rsa label Cisco modulus 1024” will be executed only if your router supports security features like router 3700.If this command is not supported type command:
Router1(config)#line vty 0 4
Router1(config-line)#crypto key generate rsa
After this, it will ask for the size of which you want to generate your key so type 512 or 1024Now, we will try to ssh from Router2 to Router1.
Router2#ssh -l Cisco 192.168.1.1
Here, -l means login which is followed by the username and then the IP address of the device which we want to take remote access.Troubleshooting –While configuring ssh, take these things into consideration:
Domain name and hostname should be provided.Crypto keys should be generatedPassword on the vty line should be provided (i.e no local database is used).
Domain name and hostname should be provided.
Crypto keys should be generated
Password on the vty line should be provided (i.e no local database is used).
Note –If using local database of the router i.e username and password configured on router locally and not on vty lines then login local command will be used.
Router1(config-line)#login local
Application Layer
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
Differences between IPv4 and IPv6
Wireless Application Protocol
Socket Programming in Python
GSM in Wireless Communication
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
Data encryption standard (DES) | Set 1 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 289,
"s": 28,
"text": "We can take access to a cisco router or switch either through a console cable or taking remote access through well known protocols Telnet or ssh (Secure Shell). Telnet and ssh are both application layer protocols used to take remote access and manage a device."
},
{
"code": null,
"e": 421,
"s": 289,
"text": "1. Telnet:As stated, Telnet is an application layer protocol which uses TCP port number 23, used to take remote access of a device."
},
{
"code": null,
"e": 432,
"s": 421,
"text": "Features –"
},
{
"code": null,
"e": 588,
"s": 432,
"text": "It doesn’t support authentication.Data is sent in clear text therefore less secure.No encryption mechanism is used.Designed to work in local networks only."
},
{
"code": null,
"e": 623,
"s": 588,
"text": "It doesn’t support authentication."
},
{
"code": null,
"e": 673,
"s": 623,
"text": "Data is sent in clear text therefore less secure."
},
{
"code": null,
"e": 706,
"s": 673,
"text": "No encryption mechanism is used."
},
{
"code": null,
"e": 747,
"s": 706,
"text": "Designed to work in local networks only."
},
{
"code": null,
"e": 763,
"s": 747,
"text": "Configuration –"
},
{
"code": null,
"e": 1095,
"s": 763,
"text": "There is a simple topology in which two routers are directly connected to each other namely Router1 and Router2. Router1 have IP address 192.168.1.1/24 on its fa0/0 port and Router2 has IP address 192.168.1.2/24 on its fa0/0 port.Here, we will enable telnet on Router1 and take access through Router2.Configuring telnet on Router1:"
},
{
"code": null,
"e": 1195,
"s": 1095,
"text": "Router1(config)#line vty 0 4\nRouter1(config-line)#password GeeksforGeeks \nRouter1(config-line)#exit"
},
{
"code": null,
"e": 1291,
"s": 1195,
"text": "Here, 0 4 means that we can have 5 concurrent sessions at a time.Taking access through Router2:"
},
{
"code": null,
"e": 1327,
"s": 1291,
"text": "Router2#telnet 192.168.1.1\nRouter1>"
},
{
"code": null,
"e": 1426,
"s": 1327,
"text": "Note – On Cisco devices, if you want to take access of a device, you have to use vty lines for it."
},
{
"code": null,
"e": 1497,
"s": 1426,
"text": "Troubleshooting –While using telnet or ssh, keep these things in mind:"
},
{
"code": null,
"e": 1800,
"s": 1497,
"text": "The (client) device through which you want to take access should be reachable to the (server) device you want to take access.If the device is reachable and you are not able to Telnet, then you have not set a password on vty line. It is mandatory to set a password on vty line while using Telnet or SSH."
},
{
"code": null,
"e": 1926,
"s": 1800,
"text": "The (client) device through which you want to take access should be reachable to the (server) device you want to take access."
},
{
"code": null,
"e": 2104,
"s": 1926,
"text": "If the device is reachable and you are not able to Telnet, then you have not set a password on vty line. It is mandatory to set a password on vty line while using Telnet or SSH."
},
{
"code": null,
"e": 2336,
"s": 2104,
"text": "Note –AAA services can also be used to set password on line vty lines. Either a local database of a device (router) or ACS server can be used for the password for vty lines.But here we are talking about a simple configuration only."
},
{
"code": null,
"e": 2476,
"s": 2336,
"text": "2. Secure Shell (SSH):SSH is also an application client-server protocol used to take remote access of a device. It uses TCP port number 23."
},
{
"code": null,
"e": 2487,
"s": 2476,
"text": "Features –"
},
{
"code": null,
"e": 2658,
"s": 2487,
"text": "Unlike telnet, it provides authentication methods.The data sent is in encrypted form.It is designed to work in public network.It uses public key for encryption mechanism."
},
{
"code": null,
"e": 2709,
"s": 2658,
"text": "Unlike telnet, it provides authentication methods."
},
{
"code": null,
"e": 2745,
"s": 2709,
"text": "The data sent is in encrypted form."
},
{
"code": null,
"e": 2787,
"s": 2745,
"text": "It is designed to work in public network."
},
{
"code": null,
"e": 2832,
"s": 2787,
"text": "It uses public key for encryption mechanism."
},
{
"code": null,
"e": 2905,
"s": 2832,
"text": "In short, SSH is more secure than telnet and has almost replaced telnet."
},
{
"code": null,
"e": 2921,
"s": 2905,
"text": "Configuration –"
},
{
"code": null,
"e": 3138,
"s": 2921,
"text": "We are using the same simple topology. Router1 have IP address 192.168.1.1/24 on its fa0/0 port and Router2 has IP address 192.168.1.2/24 on its fa0/0 port.We will ssh Router1 from Router2 Configuring ssh on Router1."
},
{
"code": null,
"e": 3424,
"s": 3138,
"text": "Router(config)#ip domain-name GeeksforGeeks.com\nRouter(config)#hostname Router1\nRouter1(config)#line vty 0 4\nRouter1(config-line)#transport input ssh\nRouter1(config-line)password GeeksforGeeks \nRouter1(config-line)#login\nRouter1(config)#crypto key generate rsa label Cisco modulus 1024"
},
{
"code": null,
"e": 3731,
"s": 3424,
"text": "Here, note that it is necessary to give domain name as ssh uses it and password for encryption purpose.If domain-name and hostname are not provided then crypro keys will not be generated. We have provided a password for vty line login and at last we have created key of 1024 bytes and labelled it as Cisco."
},
{
"code": null,
"e": 3933,
"s": 3731,
"text": "Note –The last command “crypto key generate rsa label Cisco modulus 1024” will be executed only if your router supports security features like router 3700.If this command is not supported type command:"
},
{
"code": null,
"e": 4008,
"s": 3933,
"text": "Router1(config)#line vty 0 4\nRouter1(config-line)#crypto key generate rsa "
},
{
"code": null,
"e": 4152,
"s": 4008,
"text": "After this, it will ask for the size of which you want to generate your key so type 512 or 1024Now, we will try to ssh from Router2 to Router1."
},
{
"code": null,
"e": 4186,
"s": 4152,
"text": "Router2#ssh -l Cisco 192.168.1.1 "
},
{
"code": null,
"e": 4393,
"s": 4186,
"text": "Here, -l means login which is followed by the username and then the IP address of the device which we want to take remote access.Troubleshooting –While configuring ssh, take these things into consideration:"
},
{
"code": null,
"e": 4545,
"s": 4393,
"text": "Domain name and hostname should be provided.Crypto keys should be generatedPassword on the vty line should be provided (i.e no local database is used)."
},
{
"code": null,
"e": 4590,
"s": 4545,
"text": "Domain name and hostname should be provided."
},
{
"code": null,
"e": 4622,
"s": 4590,
"text": "Crypto keys should be generated"
},
{
"code": null,
"e": 4699,
"s": 4622,
"text": "Password on the vty line should be provided (i.e no local database is used)."
},
{
"code": null,
"e": 4858,
"s": 4699,
"text": "Note –If using local database of the router i.e username and password configured on router locally and not on vty lines then login local command will be used."
},
{
"code": null,
"e": 4891,
"s": 4858,
"text": "Router1(config-line)#login local"
},
{
"code": null,
"e": 4909,
"s": 4891,
"text": "Application Layer"
},
{
"code": null,
"e": 4927,
"s": 4909,
"text": "Computer Networks"
},
{
"code": null,
"e": 4945,
"s": 4927,
"text": "Computer Networks"
},
{
"code": null,
"e": 5043,
"s": 4945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5075,
"s": 5043,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 5101,
"s": 5075,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 5131,
"s": 5101,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 5165,
"s": 5131,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 5195,
"s": 5165,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 5224,
"s": 5195,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 5254,
"s": 5224,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 5280,
"s": 5254,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 5320,
"s": 5280,
"text": "Mobile Internet Protocol (or Mobile IP)"
}
] |
Python | Sort an array according to absolute difference | 11 Oct, 2019
Given an array of N distinct elements and a number val, rearrange the array elements according to the absolute difference with val, i. e., element having minimum difference comes first and so on. Also the order of array elements should be maintained in case two or more elements have equal differences.
Examples:
Input: val = 6, a = [7, 12, 2, 4, 8, 0]Output: a = [7 4 8 2 12 0]
Explanation:Consider the absolute difference of each array element and ‘val’7 – 6 = 112- 6 = 62 – 6 = 4 (abs)4 – 6 = 2 (abs)8 – 6 = 20 – 6 = 6 (abs)So, according to the obtained differences, sort the array differences in increasing order,1, 2, 2, 4, 6, 6 is obtained, and their corresponding array elements are 7, 4, 8, 2, 12, 0.
Input: val = -2, a = [5, 2, 0, -4]Output: a = [0 -4 2 5]
Approach: Normally a dictionary in Python can hold only one value corresponding to a key. But in this problem we may have to store multiple values for a particular key. Clearly, simple dictionary cannot be used, we need something like a multimap in C++. So, here Default dictionary is use, which works as Multimap in Python. Following are the steps to solve the problem.
Store values in dictionary, where key is absolute difference between ‘val’ and array elements (i.e. abs(val-a[i])) and value is array elements (i.e. a[i])
In multiimap, the values will be already in sorted order according to key because it implements self-balancing-binary-search-tree internally.
Update the values of original array by storing the dictionary elements one by one.
Below is the implementation of the above approach.
# Python program to sort the array# according to a value val # Using Default dictionary (works as Multimap in Python)from collections import defaultdictdef rearrange(a, n, val): # initialize Default dictionary dict = defaultdict(list) # Store values in dictionary (i.e. multimap) where, # key: absolute difference between 'val' # and array elements (i.e. abs(val-a[i])) and # value: array elements (i.e. a[i]) for i in range(0, n): dict[abs(val-a[i])].append(a[i]) index = 0 # Update the values of original array # by storing the dictionary elements one by one for i in dict: pos = 0 while (pos<len(dict[i])): a[index]= dict[i][pos] index+= 1 pos+= 1 # Driver code a =[7, 12, 2, 4, 8, 0]val = 6 # len(a) gives the length of the listrearrange(a, len(a), val) # print the modified final listfor i in a: print(i, end =' ')
7 4 8 2 12 0
Time Complexity: O(N * Log N)Auxiliary Space: O(N)
Alternative Approach: Use a 2-D matrix of size n*2 to store the absolute difference and index at (i, 0) and (i, 1). Sort the 2-D matrix. According to the inbuilt matrix property, the matrix gets sorted in terms of first element, and if the first element is same, it gets sorted according to the second element. Get the index and print the array element accordingly.
Below is the implementation of above approach.
def printsorted(a, n, val): # declare a 2-D matrix b =[[0 for x in range(2)] for y in range(n)] for i in range(0, n): b[i][0] = abs(a[i]-val) b[i][1] = i b.sort() for i in range(0, n): print a[b[i][1]], a = [7, 12, 2, 4, 8, 0]n = len(a) val = 6printsorted(a, n, val)
7 4 8 2 12 0
Time Complexity: O(N * Log N)Auxiliary Space: O(N)
Akanksha_Rai
nidhi_biet
Python dictionary-programs
python-dict
Sorting Quiz
Arrays
Sorting
python-dict
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subarrays with average K
Introduction to Data Structures
Window Sliding Technique
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Next Greater Element
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 357,
"s": 54,
"text": "Given an array of N distinct elements and a number val, rearrange the array elements according to the absolute difference with val, i. e., element having minimum difference comes first and so on. Also the order of array elements should be maintained in case two or more elements have equal differences."
},
{
"code": null,
"e": 367,
"s": 357,
"text": "Examples:"
},
{
"code": null,
"e": 433,
"s": 367,
"text": "Input: val = 6, a = [7, 12, 2, 4, 8, 0]Output: a = [7 4 8 2 12 0]"
},
{
"code": null,
"e": 763,
"s": 433,
"text": "Explanation:Consider the absolute difference of each array element and ‘val’7 – 6 = 112- 6 = 62 – 6 = 4 (abs)4 – 6 = 2 (abs)8 – 6 = 20 – 6 = 6 (abs)So, according to the obtained differences, sort the array differences in increasing order,1, 2, 2, 4, 6, 6 is obtained, and their corresponding array elements are 7, 4, 8, 2, 12, 0."
},
{
"code": null,
"e": 820,
"s": 763,
"text": "Input: val = -2, a = [5, 2, 0, -4]Output: a = [0 -4 2 5]"
},
{
"code": null,
"e": 1191,
"s": 820,
"text": "Approach: Normally a dictionary in Python can hold only one value corresponding to a key. But in this problem we may have to store multiple values for a particular key. Clearly, simple dictionary cannot be used, we need something like a multimap in C++. So, here Default dictionary is use, which works as Multimap in Python. Following are the steps to solve the problem."
},
{
"code": null,
"e": 1346,
"s": 1191,
"text": "Store values in dictionary, where key is absolute difference between ‘val’ and array elements (i.e. abs(val-a[i])) and value is array elements (i.e. a[i])"
},
{
"code": null,
"e": 1488,
"s": 1346,
"text": "In multiimap, the values will be already in sorted order according to key because it implements self-balancing-binary-search-tree internally."
},
{
"code": null,
"e": 1571,
"s": 1488,
"text": "Update the values of original array by storing the dictionary elements one by one."
},
{
"code": null,
"e": 1622,
"s": 1571,
"text": "Below is the implementation of the above approach."
},
{
"code": "# Python program to sort the array# according to a value val # Using Default dictionary (works as Multimap in Python)from collections import defaultdictdef rearrange(a, n, val): # initialize Default dictionary dict = defaultdict(list) # Store values in dictionary (i.e. multimap) where, # key: absolute difference between 'val' # and array elements (i.e. abs(val-a[i])) and # value: array elements (i.e. a[i]) for i in range(0, n): dict[abs(val-a[i])].append(a[i]) index = 0 # Update the values of original array # by storing the dictionary elements one by one for i in dict: pos = 0 while (pos<len(dict[i])): a[index]= dict[i][pos] index+= 1 pos+= 1 # Driver code a =[7, 12, 2, 4, 8, 0]val = 6 # len(a) gives the length of the listrearrange(a, len(a), val) # print the modified final listfor i in a: print(i, end =' ') ",
"e": 2613,
"s": 1622,
"text": null
},
{
"code": null,
"e": 2627,
"s": 2613,
"text": "7 4 8 2 12 0\n"
},
{
"code": null,
"e": 2678,
"s": 2627,
"text": "Time Complexity: O(N * Log N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 3044,
"s": 2678,
"text": "Alternative Approach: Use a 2-D matrix of size n*2 to store the absolute difference and index at (i, 0) and (i, 1). Sort the 2-D matrix. According to the inbuilt matrix property, the matrix gets sorted in terms of first element, and if the first element is same, it gets sorted according to the second element. Get the index and print the array element accordingly."
},
{
"code": null,
"e": 3091,
"s": 3044,
"text": "Below is the implementation of above approach."
},
{
"code": "def printsorted(a, n, val): # declare a 2-D matrix b =[[0 for x in range(2)] for y in range(n)] for i in range(0, n): b[i][0] = abs(a[i]-val) b[i][1] = i b.sort() for i in range(0, n): print a[b[i][1]], a = [7, 12, 2, 4, 8, 0]n = len(a) val = 6printsorted(a, n, val) ",
"e": 3455,
"s": 3091,
"text": null
},
{
"code": null,
"e": 3469,
"s": 3455,
"text": "7 4 8 2 12 0\n"
},
{
"code": null,
"e": 3520,
"s": 3469,
"text": "Time Complexity: O(N * Log N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 3533,
"s": 3520,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3544,
"s": 3533,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3571,
"s": 3544,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 3583,
"s": 3571,
"text": "python-dict"
},
{
"code": null,
"e": 3596,
"s": 3583,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 3603,
"s": 3596,
"text": "Arrays"
},
{
"code": null,
"e": 3611,
"s": 3603,
"text": "Sorting"
},
{
"code": null,
"e": 3623,
"s": 3611,
"text": "python-dict"
},
{
"code": null,
"e": 3630,
"s": 3623,
"text": "Arrays"
},
{
"code": null,
"e": 3638,
"s": 3630,
"text": "Sorting"
},
{
"code": null,
"e": 3736,
"s": 3638,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3770,
"s": 3736,
"text": "Count of subarrays with average K"
},
{
"code": null,
"e": 3802,
"s": 3770,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 3827,
"s": 3802,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 3886,
"s": 3827,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 3907,
"s": 3886,
"text": "Next Greater Element"
},
{
"code": null,
"e": 3918,
"s": 3907,
"text": "Merge Sort"
},
{
"code": null,
"e": 3940,
"s": 3918,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 3950,
"s": 3940,
"text": "QuickSort"
},
{
"code": null,
"e": 3965,
"s": 3950,
"text": "Insertion Sort"
}
] |
Difference between #include<> and #include” ” in C/C++ with Examples | 08 Dec, 2021
Pre-requisites: Header files in C/ C++ and its uses
The difference between the two types is in the location where the preprocessor searches for the file to be included in the code.
#include <filename> // Standard library header
#include “filename” // User defined header
#include<filename>
#include<> is for pre-defined header files. If the header file is predefined then simply write the header file name in angular brackets.
Example:
#include <iostream>#include <stdio.h>#include <stdlib.h>
The preprocessor searches in an implementation-dependent manner, normally in search directories pre-designated by the compiler/IDE. This means the compiler will search in locations where standard library headers are residing. The header files can be found at default locations like /usr/include or /usr/local/include. This method is normally used to include standard library header files.
Example: Below is the C++ program to demonstrate the above concept:
C
// C program to demonstrate // the above concept#include <stdio.h> // Driver codeint main() { printf("GeeksforGeeks | "); printf("A computer science portal for geeks"); return 0;}
Output:
GeeksforGeeks | A computer science portal for geeks
#include “FILE_NAME”
#include ” “ is for header files that programmer defines. If a programmer has written his/ her own header file, then write the header file name in quotes.
Example:
#include “mult.h” Here, mul.h is header file written by programmer.
The preprocessor searches in the same directory as the file containing the directive. The compiler will search for these header files in the current folder or -I defined folders. This method is normally used to include programmer-defined header files.
mul.h Header file:
// mul.hint mul(int a, int b){ return(a * b);}
Below is the C program to include and use the header file mul.h:
C
// C program to demonstrate // the above approach // Include user-defined // header file#include "mul.h" // Driver codeint main(){ int a = 10; int b = 20; // Invoke the function defined in // header file int c = mul(a, b); printf("%d", c); return 0;}
Output:
200
#include<> vs #include””
Case 1: Include standard library header using notation #include””.
C
// C program to demonstrate // the difference// Header file#include "stdio.h" // Driver codeint main() { int a = 10; printf("%d", a); return 0;}
Output:
10
Explanation:#include ” ” will search ./ first. Then it will search the default include path. One can use the below command to print the include path.
gcc -v -o a filename.c
Case2: Include standard header file using the notation #include<>
C
// C program to demonstrate // the difference// Header file#include <stdio.h> // Driver codeint main() { int a = 10; printf("%d", a); return 0;}
Output:
10
Case 3: Include standard header file using both notation #include”” and #include<>, such as stdio.h
// stdio.hint add(int a, int b){ return(a + b);}
C
// C program to demonstrate // the difference between // "" and <> // This will include the standard// header file#include <stdio.h> // This will include the user-defined// header file#include "stdio.h" // Driver codeint main(){ int a = 10; int b = 20; // Invoke the function defined in // header file int c = add(a, b); printf("Result of addition is: %d", c); return 0;}
Output:
Explanation:
1. When stdio.h is created in the current directory then the code in Case 1 will generate an error but the code in Case 2 will work fine.2. ” ” and < > can be included together in the same code and the code will work fine since the search path priority is different for the two notations. Here, “” will include the user-defined header file and <> will include the standard header file.
C Language
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 106,
"s": 54,
"text": "Pre-requisites: Header files in C/ C++ and its uses"
},
{
"code": null,
"e": 235,
"s": 106,
"text": "The difference between the two types is in the location where the preprocessor searches for the file to be included in the code."
},
{
"code": null,
"e": 283,
"s": 235,
"text": "#include <filename> // Standard library header"
},
{
"code": null,
"e": 327,
"s": 283,
"text": "#include “filename” // User defined header"
},
{
"code": null,
"e": 346,
"s": 327,
"text": "#include<filename>"
},
{
"code": null,
"e": 484,
"s": 346,
"text": "#include<> is for pre-defined header files. If the header file is predefined then simply write the header file name in angular brackets. "
},
{
"code": null,
"e": 493,
"s": 484,
"text": "Example:"
},
{
"code": null,
"e": 550,
"s": 493,
"text": "#include <iostream>#include <stdio.h>#include <stdlib.h>"
},
{
"code": null,
"e": 939,
"s": 550,
"text": "The preprocessor searches in an implementation-dependent manner, normally in search directories pre-designated by the compiler/IDE. This means the compiler will search in locations where standard library headers are residing. The header files can be found at default locations like /usr/include or /usr/local/include. This method is normally used to include standard library header files."
},
{
"code": null,
"e": 1007,
"s": 939,
"text": "Example: Below is the C++ program to demonstrate the above concept:"
},
{
"code": null,
"e": 1009,
"s": 1007,
"text": "C"
},
{
"code": "// C program to demonstrate // the above concept#include <stdio.h> // Driver codeint main() { printf(\"GeeksforGeeks | \"); printf(\"A computer science portal for geeks\"); return 0;}",
"e": 1193,
"s": 1009,
"text": null
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Output:"
},
{
"code": null,
"e": 1253,
"s": 1201,
"text": "GeeksforGeeks | A computer science portal for geeks"
},
{
"code": null,
"e": 1274,
"s": 1253,
"text": "#include “FILE_NAME”"
},
{
"code": null,
"e": 1430,
"s": 1274,
"text": "#include ” “ is for header files that programmer defines. If a programmer has written his/ her own header file, then write the header file name in quotes. "
},
{
"code": null,
"e": 1439,
"s": 1430,
"text": "Example:"
},
{
"code": null,
"e": 1507,
"s": 1439,
"text": "#include “mult.h” Here, mul.h is header file written by programmer."
},
{
"code": null,
"e": 1760,
"s": 1507,
"text": "The preprocessor searches in the same directory as the file containing the directive. The compiler will search for these header files in the current folder or -I defined folders. This method is normally used to include programmer-defined header files. "
},
{
"code": null,
"e": 1779,
"s": 1760,
"text": "mul.h Header file:"
},
{
"code": null,
"e": 1829,
"s": 1779,
"text": "// mul.hint mul(int a, int b){ return(a * b);}"
},
{
"code": null,
"e": 1894,
"s": 1829,
"text": "Below is the C program to include and use the header file mul.h:"
},
{
"code": null,
"e": 1896,
"s": 1894,
"text": "C"
},
{
"code": "// C program to demonstrate // the above approach // Include user-defined // header file#include \"mul.h\" // Driver codeint main(){ int a = 10; int b = 20; // Invoke the function defined in // header file int c = mul(a, b); printf(\"%d\", c); return 0;}",
"e": 2162,
"s": 1896,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2162,
"text": "Output:"
},
{
"code": null,
"e": 2174,
"s": 2170,
"text": "200"
},
{
"code": null,
"e": 2199,
"s": 2174,
"text": "#include<> vs #include””"
},
{
"code": null,
"e": 2266,
"s": 2199,
"text": "Case 1: Include standard library header using notation #include””."
},
{
"code": null,
"e": 2268,
"s": 2266,
"text": "C"
},
{
"code": "// C program to demonstrate // the difference// Header file#include \"stdio.h\" // Driver codeint main() { int a = 10; printf(\"%d\", a); return 0;}",
"e": 2417,
"s": 2268,
"text": null
},
{
"code": null,
"e": 2425,
"s": 2417,
"text": "Output:"
},
{
"code": null,
"e": 2428,
"s": 2425,
"text": "10"
},
{
"code": null,
"e": 2578,
"s": 2428,
"text": "Explanation:#include ” ” will search ./ first. Then it will search the default include path. One can use the below command to print the include path."
},
{
"code": null,
"e": 2601,
"s": 2578,
"text": "gcc -v -o a filename.c"
},
{
"code": null,
"e": 2667,
"s": 2601,
"text": "Case2: Include standard header file using the notation #include<>"
},
{
"code": null,
"e": 2669,
"s": 2667,
"text": "C"
},
{
"code": "// C program to demonstrate // the difference// Header file#include <stdio.h> // Driver codeint main() { int a = 10; printf(\"%d\", a); return 0;}",
"e": 2818,
"s": 2669,
"text": null
},
{
"code": null,
"e": 2826,
"s": 2818,
"text": "Output:"
},
{
"code": null,
"e": 2829,
"s": 2826,
"text": "10"
},
{
"code": null,
"e": 2929,
"s": 2829,
"text": "Case 3: Include standard header file using both notation #include”” and #include<>, such as stdio.h"
},
{
"code": null,
"e": 2981,
"s": 2929,
"text": "// stdio.hint add(int a, int b){ return(a + b);}"
},
{
"code": null,
"e": 2983,
"s": 2981,
"text": "C"
},
{
"code": "// C program to demonstrate // the difference between // \"\" and <> // This will include the standard// header file#include <stdio.h> // This will include the user-defined// header file#include \"stdio.h\" // Driver codeint main(){ int a = 10; int b = 20; // Invoke the function defined in // header file int c = add(a, b); printf(\"Result of addition is: %d\", c); return 0;}",
"e": 3372,
"s": 2983,
"text": null
},
{
"code": null,
"e": 3380,
"s": 3372,
"text": "Output:"
},
{
"code": null,
"e": 3393,
"s": 3380,
"text": "Explanation:"
},
{
"code": null,
"e": 3780,
"s": 3393,
"text": "1. When stdio.h is created in the current directory then the code in Case 1 will generate an error but the code in Case 2 will work fine.2. ” ” and < > can be included together in the same code and the code will work fine since the search path priority is different for the two notations. Here, “” will include the user-defined header file and <> will include the standard header file."
},
{
"code": null,
"e": 3791,
"s": 3780,
"text": "C Language"
},
{
"code": null,
"e": 3795,
"s": 3791,
"text": "C++"
},
{
"code": null,
"e": 3814,
"s": 3795,
"text": "Difference Between"
},
{
"code": null,
"e": 3818,
"s": 3814,
"text": "CPP"
},
{
"code": null,
"e": 3916,
"s": 3818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3964,
"s": 3916,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3985,
"s": 3964,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4011,
"s": 3985,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 4056,
"s": 4011,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 4094,
"s": 4056,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 4112,
"s": 4094,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 4155,
"s": 4112,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4201,
"s": 4155,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4255,
"s": 4201,
"text": "Priority Queue in C++ Standard Template Library (STL)"
}
] |
What is Java Parallel Streams? | 24 Dec, 2021
Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any java code has one stream of processing, where it is executed sequentially. Whereas by using parallel streams, we can divide the code into multiple streams that are executed in parallel on separate cores and the final result is the combination of the individual outcomes. The order of execution, however, is not under our control.
Therefore, it is advisable to use parallel streams in cases where no matter what is the order of execution, the result is unaffected and the state of one element does not affect the other as well as the source of the data also remains unaffected.
Parallel Streams were introduced to increase the performance of a program, but opting for parallel streams isn’t always the best choice. There are certain instances in which we need the code to be executed in a certain order and in these cases, we better use sequential streams to perform our task at the cost of performance. The performance difference between the two kinds of streams is only of concern for large-scale programs or complex projects. For small-scale programs, it may not even be noticeable. Basically, you should consider using Parallel Streams when the sequential stream behaves poorly.
There are two ways we can create which are listed below and described later as follows:
Using parallel() method on a streamUsing parallelStream() on a Collection
Using parallel() method on a stream
Using parallelStream() on a Collection
Method 1: Using parallel() method on a stream
The parallel() method of the BaseStream interface returns an equivalent parallel stream. Let us explain how it would work with the help of an example.
In the code given below, we create a file object which points to a pre-existent ‘txt’ file in the system. Then we create a Stream that reads from the text file one line at a time. Then we use the parallel() method to print the read file on the console. The order of execution is different for each run, you can observe this in the output. The two outputs given below have different orders of execution.
Example
Java
// Java Program to Illustrate Parallel Streams// Using parallel() method on a Stream // Importing required classesimport java.io.File;import java.io.IOException;import java.nio.file.Files;import java.util.stream.Stream; // Main class// ParallelStreamTestpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a File object File fileName = new File("M:\\Documents\\Textfile.txt"); // Create a Stream of string type // using the lines() method to // read one line at a time from the text file Stream<String> text = Files.lines(fileName.toPath()); // Creating parallel streams using parallel() method // later using forEach() to print on console text.parallel().forEach(System.out::println); // Closing the Stream // using close() method text.close(); }}
Output:
1A
Output 1
1B
Output 2
Method 2: Using parallelStream() on a Collection
The parallelStream() method of the Collection interface returns a possible parallel stream with the collection as the source. Let us explain the working with the help of an example.
Implementation:
In the code given below, we are again using parallel streams but here we are using a List to read from the text file. Therefore, we need the parallelStream() method.
Example
Java
// Java Program to Illustrate Parallel Streams// using parallelStream() method on a Stream // Importing required classesimport java.io.File;import java.io.IOException;import java.nio.file.Files;import java.util.*; // Main class// ParallelStreamsTestpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a File object File fileName = new File("M:\\Documents\\List_Textfile.txt"); // Reading the lines of the text file by // create a List using readAllLines() method List<String> text = Files.readAllLines(fileName.toPath()); // Creating parallel streams by creating a List // using readAllLines() method text.parallelStream().forEach(System.out::println); }}
Output:
Output
ihsanalgul55
simmytarika5
Java Parallel-Streams
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": "\n24 Dec, 2021"
},
{
"code": null,
"e": 506,
"s": 53,
"text": "Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any java code has one stream of processing, where it is executed sequentially. Whereas by using parallel streams, we can divide the code into multiple streams that are executed in parallel on separate cores and the final result is the combination of the individual outcomes. The order of execution, however, is not under our control."
},
{
"code": null,
"e": 753,
"s": 506,
"text": "Therefore, it is advisable to use parallel streams in cases where no matter what is the order of execution, the result is unaffected and the state of one element does not affect the other as well as the source of the data also remains unaffected."
},
{
"code": null,
"e": 1358,
"s": 753,
"text": "Parallel Streams were introduced to increase the performance of a program, but opting for parallel streams isn’t always the best choice. There are certain instances in which we need the code to be executed in a certain order and in these cases, we better use sequential streams to perform our task at the cost of performance. The performance difference between the two kinds of streams is only of concern for large-scale programs or complex projects. For small-scale programs, it may not even be noticeable. Basically, you should consider using Parallel Streams when the sequential stream behaves poorly."
},
{
"code": null,
"e": 1446,
"s": 1358,
"text": "There are two ways we can create which are listed below and described later as follows:"
},
{
"code": null,
"e": 1521,
"s": 1446,
"text": "Using parallel() method on a streamUsing parallelStream() on a Collection "
},
{
"code": null,
"e": 1557,
"s": 1521,
"text": "Using parallel() method on a stream"
},
{
"code": null,
"e": 1597,
"s": 1557,
"text": "Using parallelStream() on a Collection "
},
{
"code": null,
"e": 1643,
"s": 1597,
"text": "Method 1: Using parallel() method on a stream"
},
{
"code": null,
"e": 1794,
"s": 1643,
"text": "The parallel() method of the BaseStream interface returns an equivalent parallel stream. Let us explain how it would work with the help of an example."
},
{
"code": null,
"e": 2197,
"s": 1794,
"text": "In the code given below, we create a file object which points to a pre-existent ‘txt’ file in the system. Then we create a Stream that reads from the text file one line at a time. Then we use the parallel() method to print the read file on the console. The order of execution is different for each run, you can observe this in the output. The two outputs given below have different orders of execution."
},
{
"code": null,
"e": 2206,
"s": 2197,
"text": "Example "
},
{
"code": null,
"e": 2211,
"s": 2206,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Parallel Streams// Using parallel() method on a Stream // Importing required classesimport java.io.File;import java.io.IOException;import java.nio.file.Files;import java.util.stream.Stream; // Main class// ParallelStreamTestpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a File object File fileName = new File(\"M:\\\\Documents\\\\Textfile.txt\"); // Create a Stream of string type // using the lines() method to // read one line at a time from the text file Stream<String> text = Files.lines(fileName.toPath()); // Creating parallel streams using parallel() method // later using forEach() to print on console text.parallel().forEach(System.out::println); // Closing the Stream // using close() method text.close(); }}",
"e": 3126,
"s": 2211,
"text": null
},
{
"code": null,
"e": 3135,
"s": 3126,
"text": "Output: "
},
{
"code": null,
"e": 3138,
"s": 3135,
"text": "1A"
},
{
"code": null,
"e": 3147,
"s": 3138,
"text": "Output 1"
},
{
"code": null,
"e": 3152,
"s": 3149,
"text": "1B"
},
{
"code": null,
"e": 3161,
"s": 3152,
"text": "Output 2"
},
{
"code": null,
"e": 3210,
"s": 3161,
"text": "Method 2: Using parallelStream() on a Collection"
},
{
"code": null,
"e": 3392,
"s": 3210,
"text": "The parallelStream() method of the Collection interface returns a possible parallel stream with the collection as the source. Let us explain the working with the help of an example."
},
{
"code": null,
"e": 3408,
"s": 3392,
"text": "Implementation:"
},
{
"code": null,
"e": 3574,
"s": 3408,
"text": "In the code given below, we are again using parallel streams but here we are using a List to read from the text file. Therefore, we need the parallelStream() method."
},
{
"code": null,
"e": 3582,
"s": 3574,
"text": "Example"
},
{
"code": null,
"e": 3587,
"s": 3582,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Parallel Streams// using parallelStream() method on a Stream // Importing required classesimport java.io.File;import java.io.IOException;import java.nio.file.Files;import java.util.*; // Main class// ParallelStreamsTestpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a File object File fileName = new File(\"M:\\\\Documents\\\\List_Textfile.txt\"); // Reading the lines of the text file by // create a List using readAllLines() method List<String> text = Files.readAllLines(fileName.toPath()); // Creating parallel streams by creating a List // using readAllLines() method text.parallelStream().forEach(System.out::println); }}",
"e": 4412,
"s": 3587,
"text": null
},
{
"code": null,
"e": 4420,
"s": 4412,
"text": "Output:"
},
{
"code": null,
"e": 4427,
"s": 4420,
"text": "Output"
},
{
"code": null,
"e": 4440,
"s": 4427,
"text": "ihsanalgul55"
},
{
"code": null,
"e": 4453,
"s": 4440,
"text": "simmytarika5"
},
{
"code": null,
"e": 4475,
"s": 4453,
"text": "Java Parallel-Streams"
},
{
"code": null,
"e": 4480,
"s": 4475,
"text": "Java"
},
{
"code": null,
"e": 4485,
"s": 4480,
"text": "Java"
}
] |
What is the difference between visibility:hidden and display:none ? | 07 Oct, 2021
Both the visibility & display property is quite useful in CSS. The visibility: “hidden”; property is used to specify whether an element is visible or not in a web document but the hidden elements take up space in the web document. The visibility is a property in CSS that specifies the visibility behavior of an element. The display property in CSS defines how the components( such as div, hyperlink, heading, etc) are going to be placed on the web page. The display: “none” property is used to specify whether an element exists or not on the website.
Visibility property: This property is used to specify whether an element is visible or not in a web document but the hidden elements take up space in the web document.
Syntax:
visibility: visible| hidden | collapse | initial | inherit;
Property Values:
visible: It is used to specify the element to be visible. It is a default value.
hidden: Element is not visible, but it affects layout.
collapse: It hides the element when it is used on a table row or a cell.
initial: It sets the visibility property to its default value.
inherit: This property is inherited from its parent element.
Display property: The Display property in CSS defines how the components(div, hyperlink, heading, etc) are going to be placed on the web page.
Syntax:
display: none | inline | block | inline-block;
Property Values:
none: It will not display any element.
inline: It is the default value. It renders the element as an inline element.
block: It renders the element as a block-level element.
inline-block: It renders the element as a block box inside an inline box.
So, the difference between display: “none”; and visibility: “hidden”; right from the name itself we can tell the difference as display: “none”; completely gets rids of the tag, as it had never existed in the HTML page whereas visibility: “hidden”; just makes the tag invisible, it will still on the HTML page occupying space it’s just invisible.
Example: This example illustrates the use of the visibility property & display property in CSS.
HTML
<!DOCTYPE html><html><head> <title> Difference between display:"none"; and visibility: "hidden"; </title></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> display:"none"; and visibility: "hidden"; </h3> <div class="display"> <b> display: <span style="display:none"> display:none </span> "none"; </b> </div> <br> <div class="visibility"> <b> visibility: <span style="visibility:hidden"> visibility:hidden </span> "hidden"; </b> </div> <p> You can see that the display: "none"; don't have any blank space and visibility: "hidden": has the blank space. </p> </center></body></html>
Output: In the visibility span, the tag still exists as you can see space between, whereas as display got rid of the tag.
Display and Visibility in JavaScript:
Syntax:
display = “none”;
document.getElementById("Id").style.display = "none";
visibility = “hidden”;
document.getElementById("Id").style.visibility = "hidden";
Example: This example illustrates the use of display property & visibility property in Javascript.
HTML
<!DOCTYPE html><html><head> <style> .container { width: 800px; height: 200px; border: 2px solid black; } .right { float: right; margin: 10px; } .left { float: left; margin: 10px; } #geek { width: 200px; height: 55px; background-color: yellow; } #geek1 { width: 200px; height: 55px; background-color: purple; } </style></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <b> Effect of <code>display:"none"</code> and <code>visibility="hidden"</code> </b> <br> <div class="container"> <div class="right"> <div id="geek1"> On clicking the below button this div tag still exists but invisible. </div> <br> <button onclick="visibility()"> visibility="hidden" </button> <p> This line will be still and won't go up as the <br>above div tag still exists but invisible. </p> </div> <div class="left"> <div id="geek"> On clicking the below button this div tag won't exist. </div> <br> <button onclick="display()">display="none"</button> <p>This line will go up as the above div tag none.</p> </div> </div> </center> <script> function display() { document.getElementById("geek").style.display = "none"; } function visibility() { document.getElementById("geek1").style.visibility = "hidden"; } </script></body></html>
Output: From the below output, when the display button is clicked then the whole page shifts upward & occupying the space of the deleted <div> tag while when the visibility button is clicked, it doesn’t shift as the <div> tag still exists in invisible form.
bhaskargeeksforgeeks
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 580,
"s": 28,
"text": "Both the visibility & display property is quite useful in CSS. The visibility: “hidden”; property is used to specify whether an element is visible or not in a web document but the hidden elements take up space in the web document. The visibility is a property in CSS that specifies the visibility behavior of an element. The display property in CSS defines how the components( such as div, hyperlink, heading, etc) are going to be placed on the web page. The display: “none” property is used to specify whether an element exists or not on the website."
},
{
"code": null,
"e": 748,
"s": 580,
"text": "Visibility property: This property is used to specify whether an element is visible or not in a web document but the hidden elements take up space in the web document."
},
{
"code": null,
"e": 756,
"s": 748,
"text": "Syntax:"
},
{
"code": null,
"e": 816,
"s": 756,
"text": "visibility: visible| hidden | collapse | initial | inherit;"
},
{
"code": null,
"e": 834,
"s": 816,
"text": "Property Values: "
},
{
"code": null,
"e": 915,
"s": 834,
"text": "visible: It is used to specify the element to be visible. It is a default value."
},
{
"code": null,
"e": 970,
"s": 915,
"text": "hidden: Element is not visible, but it affects layout."
},
{
"code": null,
"e": 1043,
"s": 970,
"text": "collapse: It hides the element when it is used on a table row or a cell."
},
{
"code": null,
"e": 1106,
"s": 1043,
"text": "initial: It sets the visibility property to its default value."
},
{
"code": null,
"e": 1167,
"s": 1106,
"text": "inherit: This property is inherited from its parent element."
},
{
"code": null,
"e": 1311,
"s": 1167,
"text": "Display property: The Display property in CSS defines how the components(div, hyperlink, heading, etc) are going to be placed on the web page. "
},
{
"code": null,
"e": 1319,
"s": 1311,
"text": "Syntax:"
},
{
"code": null,
"e": 1366,
"s": 1319,
"text": "display: none | inline | block | inline-block;"
},
{
"code": null,
"e": 1383,
"s": 1366,
"text": "Property Values:"
},
{
"code": null,
"e": 1422,
"s": 1383,
"text": "none: It will not display any element."
},
{
"code": null,
"e": 1500,
"s": 1422,
"text": "inline: It is the default value. It renders the element as an inline element."
},
{
"code": null,
"e": 1556,
"s": 1500,
"text": "block: It renders the element as a block-level element."
},
{
"code": null,
"e": 1630,
"s": 1556,
"text": "inline-block: It renders the element as a block box inside an inline box."
},
{
"code": null,
"e": 1976,
"s": 1630,
"text": "So, the difference between display: “none”; and visibility: “hidden”; right from the name itself we can tell the difference as display: “none”; completely gets rids of the tag, as it had never existed in the HTML page whereas visibility: “hidden”; just makes the tag invisible, it will still on the HTML page occupying space it’s just invisible."
},
{
"code": null,
"e": 2072,
"s": 1976,
"text": "Example: This example illustrates the use of the visibility property & display property in CSS."
},
{
"code": null,
"e": 2077,
"s": 2072,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> Difference between display:\"none\"; and visibility: \"hidden\"; </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> display:\"none\"; and visibility: \"hidden\"; </h3> <div class=\"display\"> <b> display: <span style=\"display:none\"> display:none </span> \"none\"; </b> </div> <br> <div class=\"visibility\"> <b> visibility: <span style=\"visibility:hidden\"> visibility:hidden </span> \"hidden\"; </b> </div> <p> You can see that the display: \"none\"; don't have any blank space and visibility: \"hidden\": has the blank space. </p> </center></body></html>",
"e": 3020,
"s": 2077,
"text": null
},
{
"code": null,
"e": 3142,
"s": 3020,
"text": "Output: In the visibility span, the tag still exists as you can see space between, whereas as display got rid of the tag."
},
{
"code": null,
"e": 3180,
"s": 3142,
"text": "Display and Visibility in JavaScript:"
},
{
"code": null,
"e": 3189,
"s": 3180,
"text": " Syntax:"
},
{
"code": null,
"e": 3207,
"s": 3189,
"text": "display = “none”;"
},
{
"code": null,
"e": 3261,
"s": 3207,
"text": "document.getElementById(\"Id\").style.display = \"none\";"
},
{
"code": null,
"e": 3284,
"s": 3261,
"text": "visibility = “hidden”;"
},
{
"code": null,
"e": 3343,
"s": 3284,
"text": "document.getElementById(\"Id\").style.visibility = \"hidden\";"
},
{
"code": null,
"e": 3442,
"s": 3343,
"text": "Example: This example illustrates the use of display property & visibility property in Javascript."
},
{
"code": null,
"e": 3447,
"s": 3442,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <style> .container { width: 800px; height: 200px; border: 2px solid black; } .right { float: right; margin: 10px; } .left { float: left; margin: 10px; } #geek { width: 200px; height: 55px; background-color: yellow; } #geek1 { width: 200px; height: 55px; background-color: purple; } </style></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <b> Effect of <code>display:\"none\"</code> and <code>visibility=\"hidden\"</code> </b> <br> <div class=\"container\"> <div class=\"right\"> <div id=\"geek1\"> On clicking the below button this div tag still exists but invisible. </div> <br> <button onclick=\"visibility()\"> visibility=\"hidden\" </button> <p> This line will be still and won't go up as the <br>above div tag still exists but invisible. </p> </div> <div class=\"left\"> <div id=\"geek\"> On clicking the below button this div tag won't exist. </div> <br> <button onclick=\"display()\">display=\"none\"</button> <p>This line will go up as the above div tag none.</p> </div> </div> </center> <script> function display() { document.getElementById(\"geek\").style.display = \"none\"; } function visibility() { document.getElementById(\"geek1\").style.visibility = \"hidden\"; } </script></body></html>",
"e": 5275,
"s": 3447,
"text": null
},
{
"code": null,
"e": 5533,
"s": 5275,
"text": "Output: From the below output, when the display button is clicked then the whole page shifts upward & occupying the space of the deleted <div> tag while when the visibility button is clicked, it doesn’t shift as the <div> tag still exists in invisible form."
},
{
"code": null,
"e": 5554,
"s": 5533,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 5569,
"s": 5554,
"text": "CSS-Properties"
},
{
"code": null,
"e": 5583,
"s": 5569,
"text": "CSS-Questions"
},
{
"code": null,
"e": 5590,
"s": 5583,
"text": "Picked"
},
{
"code": null,
"e": 5594,
"s": 5590,
"text": "CSS"
},
{
"code": null,
"e": 5611,
"s": 5594,
"text": "Web Technologies"
},
{
"code": null,
"e": 5638,
"s": 5611,
"text": "Web technologies Questions"
}
] |
Lexicographically smallest and largest substring of size k | 10 Jun, 2021
Given String str and an integer k, find the lexicographically smallest and largest substring of length kLexicography order, also called as alphabetical order or dictionary order,
A < B <... < Y < Z < a < b <.. < y < z
Examples:
Input : String: hello
Size: 2
Distinct Substring: [el, he, ll, lo]
Output : Smallest Substring: el
Largest Substring: lo
Input : String: geeksforgeeks
Size: 3
Distinct Substring: [eek, eks, for, gee, ksf, org, rge, sfo]
Output : Smallest Substring: eek
Largest Substring: sfo
We initialize max and min as first substring of size k. We traverse remaining substrings, by removing first character of previous substring and adding last character of new string. We keep track of the lexicographically largest and smallest.
C++
Java
Python3
C#
Javascript
// CPP program to find lexicographically// largest and smallest substrings of size k.#include<bits/stdc++.h> using namespace std; void getSmallestAndLargest(string s, int k) { // Initialize min and max as // first substring of size k string currStr = s.substr(0, k); string lexMin = currStr; string lexMax = currStr; // Consider all remaining substrings. We consider // every substring ending with index i. for (int i = k; i < s.length(); i++) { currStr = currStr.substr(1, k) + s[i]; if (lexMax < currStr) lexMax = currStr; if (lexMin >currStr) lexMin = currStr; } // Print result. cout << (lexMin) << endl; cout << (lexMax) << endl; } // Driver Code int main() { string str = "GeeksForGeeks"; int k = 3; getSmallestAndLargest(str, k); } // This code is contributed by// Sanjit_Prasad
// Java program to find lexicographically largest and smallest// substrings of size k. public class GFG { public static void getSmallestAndLargest(String s, int k) { // Initialize min and max as first substring of size k String currStr = s.substring(0, k); String lexMin = currStr; String lexMax = currStr; // Consider all remaining substrings. We consider // every substring ending with index i. for (int i = k; i < s.length(); i++) { currStr = currStr.substring(1, k) + s.charAt(i); if (lexMax.compareTo(currStr) < 0) lexMax = currStr; if (lexMin.compareTo(currStr) > 0) lexMin = currStr; } // Print result. System.out.println(lexMin); System.out.println(lexMax); } // Driver Code public static void main(String[] args) { String str = "GeeksForGeeks"; int k = 3; getSmallestAndLargest(str, k); }}
# Python 3 program to find lexicographically# largest and smallest substrings of size k.def getSmallestAndLargest(s, k): # Initialize min and max as # first substring of size k currStr = s[:k] lexMin = currStr lexMax = currStr # Consider all remaining substrings. # We consider every substring ending # with index i. for i in range(k, len(s)): currStr = currStr[1 : k] + s[i] if (lexMax < currStr): lexMax = currStr if (lexMin >currStr): lexMin = currStr # Print result. print(lexMin) print(lexMax) # Driver Codeif __name__ == '__main__': str1 = "GeeksForGeeks" k = 3 getSmallestAndLargest(str1, k) # This code is contributed by# Surendra_Gangwar
// C# program to find lexicographically// largest and smallest substrings of size k.using System; class GFG{ // Function to compare two strings static int CompareTo(String s1, String s2) { for (int i = 0; i < s1.Length || i < s2.Length; i++) { if (s1[i] < s2[i]) return -1; else if (s1[i] > s2[i]) return 1; } return 0; } static void getSmallestAndLargest(String s, int k) { // Initialize min and max as // first substring of size k String currStr = s.Substring(0, k); String lexMin = currStr; String lexMax = currStr; // Consider all remaining substrings. // We consider every substring // ending with index i. for (int i = k; i < s.Length; i++) { currStr = currStr.Substring(1, k - 1) + "" + s[i]; if (CompareTo(lexMax, currStr) < 0) lexMax = currStr; if (CompareTo(lexMin, currStr) > 0) lexMin = currStr; } // Print result. Console.WriteLine(lexMin); Console.WriteLine(lexMax); } // Driver Code public static void Main(String[] args) { String str = "GeeksForGeeks"; int k = 3; getSmallestAndLargest(str, k); }} // This code is contributed by// sanjeev2552
<script> // JavaScript program to find lexicographically // largest and smallest substrings of size k. function getSmallestAndLargest(s, k) { // Initialize min and max as // first substring of size k var currStr = s.substring(0, k); var lexMin = currStr; var lexMax = currStr; // Consider all remaining substrings. // We consider every substring // ending with index i. for (var i = k; i < s.length; i++) { currStr = currStr.substring(1, k) + s[i]; if (lexMax < currStr) lexMax = currStr; if (lexMin > currStr) lexMin = currStr; } // Print result. document.write(lexMin + "<br>"); document.write(lexMax + "<br>"); } // Driver Code var str = "GeeksForGeeks"; var k = 3; getSmallestAndLargest(str, k); </script>
For
sFo
Sanjit_Prasad
SURENDRA_GANGWAR
sanjeev2552
rdtank
sliding-window
Java Programs
Strings
sliding-window
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
Java program to count the occurrence of each character in a string using Hashmap
How to Iterate HashMap in Java?
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 234,
"s": 54,
"text": "Given String str and an integer k, find the lexicographically smallest and largest substring of length kLexicography order, also called as alphabetical order or dictionary order, "
},
{
"code": null,
"e": 274,
"s": 234,
"text": " A < B <... < Y < Z < a < b <.. < y < z"
},
{
"code": null,
"e": 286,
"s": 274,
"text": "Examples: "
},
{
"code": null,
"e": 613,
"s": 286,
"text": "Input : String: hello\n Size: 2\n Distinct Substring: [el, he, ll, lo]\nOutput : Smallest Substring: el\n Largest Substring: lo\n\nInput : String: geeksforgeeks\n Size: 3\n Distinct Substring: [eek, eks, for, gee, ksf, org, rge, sfo]\nOutput : Smallest Substring: eek\n Largest Substring: sfo"
},
{
"code": null,
"e": 859,
"s": 615,
"text": "We initialize max and min as first substring of size k. We traverse remaining substrings, by removing first character of previous substring and adding last character of new string. We keep track of the lexicographically largest and smallest. "
},
{
"code": null,
"e": 863,
"s": 859,
"text": "C++"
},
{
"code": null,
"e": 868,
"s": 863,
"text": "Java"
},
{
"code": null,
"e": 876,
"s": 868,
"text": "Python3"
},
{
"code": null,
"e": 879,
"s": 876,
"text": "C#"
},
{
"code": null,
"e": 890,
"s": 879,
"text": "Javascript"
},
{
"code": "// CPP program to find lexicographically// largest and smallest substrings of size k.#include<bits/stdc++.h> using namespace std; void getSmallestAndLargest(string s, int k) { // Initialize min and max as // first substring of size k string currStr = s.substr(0, k); string lexMin = currStr; string lexMax = currStr; // Consider all remaining substrings. We consider // every substring ending with index i. for (int i = k; i < s.length(); i++) { currStr = currStr.substr(1, k) + s[i]; if (lexMax < currStr) lexMax = currStr; if (lexMin >currStr) lexMin = currStr; } // Print result. cout << (lexMin) << endl; cout << (lexMax) << endl; } // Driver Code int main() { string str = \"GeeksForGeeks\"; int k = 3; getSmallestAndLargest(str, k); } // This code is contributed by// Sanjit_Prasad",
"e": 1893,
"s": 890,
"text": null
},
{
"code": "// Java program to find lexicographically largest and smallest// substrings of size k. public class GFG { public static void getSmallestAndLargest(String s, int k) { // Initialize min and max as first substring of size k String currStr = s.substring(0, k); String lexMin = currStr; String lexMax = currStr; // Consider all remaining substrings. We consider // every substring ending with index i. for (int i = k; i < s.length(); i++) { currStr = currStr.substring(1, k) + s.charAt(i); if (lexMax.compareTo(currStr) < 0) lexMax = currStr; if (lexMin.compareTo(currStr) > 0) lexMin = currStr; } // Print result. System.out.println(lexMin); System.out.println(lexMax); } // Driver Code public static void main(String[] args) { String str = \"GeeksForGeeks\"; int k = 3; getSmallestAndLargest(str, k); }}",
"e": 2896,
"s": 1893,
"text": null
},
{
"code": "# Python 3 program to find lexicographically# largest and smallest substrings of size k.def getSmallestAndLargest(s, k): # Initialize min and max as # first substring of size k currStr = s[:k] lexMin = currStr lexMax = currStr # Consider all remaining substrings. # We consider every substring ending # with index i. for i in range(k, len(s)): currStr = currStr[1 : k] + s[i] if (lexMax < currStr): lexMax = currStr if (lexMin >currStr): lexMin = currStr # Print result. print(lexMin) print(lexMax) # Driver Codeif __name__ == '__main__': str1 = \"GeeksForGeeks\" k = 3 getSmallestAndLargest(str1, k) # This code is contributed by# Surendra_Gangwar",
"e": 3638,
"s": 2896,
"text": null
},
{
"code": "// C# program to find lexicographically// largest and smallest substrings of size k.using System; class GFG{ // Function to compare two strings static int CompareTo(String s1, String s2) { for (int i = 0; i < s1.Length || i < s2.Length; i++) { if (s1[i] < s2[i]) return -1; else if (s1[i] > s2[i]) return 1; } return 0; } static void getSmallestAndLargest(String s, int k) { // Initialize min and max as // first substring of size k String currStr = s.Substring(0, k); String lexMin = currStr; String lexMax = currStr; // Consider all remaining substrings. // We consider every substring // ending with index i. for (int i = k; i < s.Length; i++) { currStr = currStr.Substring(1, k - 1) + \"\" + s[i]; if (CompareTo(lexMax, currStr) < 0) lexMax = currStr; if (CompareTo(lexMin, currStr) > 0) lexMin = currStr; } // Print result. Console.WriteLine(lexMin); Console.WriteLine(lexMax); } // Driver Code public static void Main(String[] args) { String str = \"GeeksForGeeks\"; int k = 3; getSmallestAndLargest(str, k); }} // This code is contributed by// sanjeev2552",
"e": 5019,
"s": 3638,
"text": null
},
{
"code": "<script> // JavaScript program to find lexicographically // largest and smallest substrings of size k. function getSmallestAndLargest(s, k) { // Initialize min and max as // first substring of size k var currStr = s.substring(0, k); var lexMin = currStr; var lexMax = currStr; // Consider all remaining substrings. // We consider every substring // ending with index i. for (var i = k; i < s.length; i++) { currStr = currStr.substring(1, k) + s[i]; if (lexMax < currStr) lexMax = currStr; if (lexMin > currStr) lexMin = currStr; } // Print result. document.write(lexMin + \"<br>\"); document.write(lexMax + \"<br>\"); } // Driver Code var str = \"GeeksForGeeks\"; var k = 3; getSmallestAndLargest(str, k); </script>",
"e": 5898,
"s": 5019,
"text": null
},
{
"code": null,
"e": 5906,
"s": 5898,
"text": "For\nsFo"
},
{
"code": null,
"e": 5922,
"s": 5908,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 5939,
"s": 5922,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 5951,
"s": 5939,
"text": "sanjeev2552"
},
{
"code": null,
"e": 5958,
"s": 5951,
"text": "rdtank"
},
{
"code": null,
"e": 5973,
"s": 5958,
"text": "sliding-window"
},
{
"code": null,
"e": 5987,
"s": 5973,
"text": "Java Programs"
},
{
"code": null,
"e": 5995,
"s": 5987,
"text": "Strings"
},
{
"code": null,
"e": 6010,
"s": 5995,
"text": "sliding-window"
},
{
"code": null,
"e": 6018,
"s": 6010,
"text": "Strings"
},
{
"code": null,
"e": 6116,
"s": 6018,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6154,
"s": 6116,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 6211,
"s": 6154,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 6240,
"s": 6211,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 6321,
"s": 6240,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 6353,
"s": 6321,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 6399,
"s": 6353,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 6424,
"s": 6399,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6484,
"s": 6424,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 6499,
"s": 6484,
"text": "C++ Data Types"
}
] |
Find One’s Complement of an Integer in C++ | In this section, we will see how to find the 1’s complete of an integer. We can use the complement operator to do this task very fast, but it will make 32bit complemented value (4-bype integer). Here we want complement of n bit numbers.
Suppose we have a number say 22. The binary equivalent is 10110. The complemented value is 01001 which is same as 9. Now the question comes, how to find this value? At first we have to find number of bits of the given number. Suppose the count is c (here c = 5 for 22). We have to make 5 1s. So this will be 11111. To make this, we will shift 1 to the left c number of times, then subtract 1 from it. After shifting 1 to the left 5 times, it will be 100000, then subtract 1, so it will be 11111. After that perform XOR operation with the 11111 and 10110 to get the complement.
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int findComplement(int n) {
int bit_count = floor(log2(n))+1;
int ones = ((1 << bit_count) - 1);
return ones ^ n;
}
int main() {
int number = 22;
cout << "One's Complement of " << number << " is: " << findComplement(number);
}
One's Complement of 22 is: 9 | [
{
"code": null,
"e": 1299,
"s": 1062,
"text": "In this section, we will see how to find the 1’s complete of an integer. We can use the complement operator to do this task very fast, but it will make 32bit complemented value (4-bype integer). Here we want complement of n bit numbers."
},
{
"code": null,
"e": 1876,
"s": 1299,
"text": "Suppose we have a number say 22. The binary equivalent is 10110. The complemented value is 01001 which is same as 9. Now the question comes, how to find this value? At first we have to find number of bits of the given number. Suppose the count is c (here c = 5 for 22). We have to make 5 1s. So this will be 11111. To make this, we will shift 1 to the left c number of times, then subtract 1 from it. After shifting 1 to the left 5 times, it will be 100000, then subtract 1, so it will be 11111. After that perform XOR operation with the 11111 and 10110 to get the complement."
},
{
"code": null,
"e": 1887,
"s": 1876,
"text": " Live Demo"
},
{
"code": null,
"e": 2187,
"s": 1887,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint findComplement(int n) {\n int bit_count = floor(log2(n))+1;\n int ones = ((1 << bit_count) - 1);\n return ones ^ n;\n}\nint main() {\n int number = 22;\n cout << \"One's Complement of \" << number << \" is: \" << findComplement(number);\n}"
},
{
"code": null,
"e": 2216,
"s": 2187,
"text": "One's Complement of 22 is: 9"
}
] |
Python For Data Science — Advanced Guide to Plotly Dash Interactive Visualizations | by Nicholas Leong | Towards Data Science | Greetings data practitioners,I assume you are aware of the increase in demand for people who know how to communicate data. This is exactly why we should always seek to improve, learn more, and sharpen our skills in the data science industry.
Even with all the hype around Machine Learning, Data Visualizations do not lose their importance. Exploratory Data Analysis is often required before any Machine Learning is even planned out.
Large tech companies often need to communicate the data they own. We are the ones that execute.
A very good example would be google and their known, google trends.
Hence, building clean and beautiful visualizations is a valuable skill that will definitely make you stand out from the crowd.
Have you heard of Dash by Plotly?
Dash is the new kid on the block. I wrote about it here.
towardsdatascience.com
Basically, Dash is the new Python library that allows you to build amazing data visualization apps with highly customization user interface without the need to know any HTML, CSS, or Javascript.
It takes away the headaches of deploying apps, making it mobile responsive and easily maintainable.
But you know that already, what was I thinking.
You’re not here for that, you want to know more.
In this article, we will talk about how you can add more customizations to your Dash web app. We will also go in-depth on how you can update the dashboard without any interactions, in real-time.
Dash visualizations are based on Plotly.It’s important that you understand the fundamentals of building simple Plotly Graphs. I wrote about building the basic Plotly graphs here, covering the concepts you need to understand while building any sort of graph.
towardsdatascience.com
In order to work with Plotly, you will need to perform some soft transformations on your data with Pandas.
I got you covered. I happen to have written A Guide to Pandas as well.If you need to refresh your memory on Pandas, please go through it.
towardsdatascience.com
pip install dash
Working with Jupyter Notebooks...
import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as goimport pandas as pdfrom dash.dependencies import Input, Output
In this section, we will be talking about making your dashboard live.
Yes, you heard it right.
Dash allows its users to automate dashboards in real-time by updating its data source, without any interactions whatsoever. This is achieved by implementing the interval component.
The interval component from dash core components is a trigger that will fire callbacks periodically. To implement this on the app, simply connect the interval to a tag or graph you need to update, and let the magic happen.
We will explore this with a simple example.
app = dash.Dash()app.layout = html.Div([ html.H1(id='live-counter'), dcc.Interval( id='1-second-interval', interval=1000, n_intervals=0 )])@app.callback(Output('live-counter', 'children'), [Input('1-second-interval', 'n_intervals')])def update_layout(n): return 'This app has updated itself for {} times, every second.'.format(n)if __name__ == '__main__': app.run_server()
In this section, we have simply defined an H1 tag and an interval component.We then defined a callback function, taking the interval component as an input and the H1 tag as the output.
An important property in the component is the interval property, which defines how often the component will trigger. Here, we are taking 1-second intervals.
What this means is that the callback function will trigger every 1 second automatically.
Lastly, we can make use of the n property in the interval component which updates itself according to the time interval we have defined. Simply insert n as part of the text we displayed to show the real-time changes.
Let’s bring it up a notch, shall we?How do we implement this for an actual graph?
Simple, we update the graph itself.
In this block of code, we are simply defining a graph component and an interval component. We then defined a callback function, taking the interval component as an input and the graph’s figure as the output.
Before I jump into the explanation, a good flow chart always helps.
For every second, new data with a random number is appended into our data source. A new graph is then plotted based on that updated data source. The graph on the app is then replaced with the updated graph.
Here, we have simply inserted random numbers as data into our data source. However, if you are following, you will know that you can easily append/overwrite your data source based on your pipeline.
Are you web-scraping data in real-time?
Are you visualizing transactional data for your website?
You can easily declare that as your data source and visualize it every second/minute/day.
I hope you realize by now how powerful Dash is. It is only up to your imagination on how you can take advantage of it.
Note: Be mindful of updating graphs in too small of an interval. It is not wise to have real-time data without having a real use case for it because there might be extremely heavy computations in updating data sources, not to mention plotting extremely heavy graphs.
So you’re able to build graphs and automate them by now. What’s next?
You need to design and customize your web app so it looks beautiful to the user. From color to positioning, Dash allows you to do so easily with a line of code.
CSS stands for Cascading Style Sheets which is the main language to style your HTML tags. If you wish to beautify your web app, learning CSS is a must.
Dash allows you to add CSS in the Python code itself.For nearly every component in Dash, there is a property named ‘style’ which allows you to declare the CSS for that component through a Python Dictionary.
html.H1(children='Hello World!',style={'width':'20%','display':'inline-block'})
That’s cool and all. However, there is a better way to declare your CSS if your web app scales.
Exclusively declaring CSS for each component is inefficient, it will also slow down the load time for the app.
Hence, we can use the Classname solution in Dash, which is essentially the class attribute for your HTML element.
In the same folder where you started your Dash code, create another folder named assets and place all your CSS and Javascript code in it. By default, the latest Dash version will read everything that ends with .css and .js from the assets folder and apply it to the web app.
app.py:
app = dash.Dash(__name__)app.layout = html.H1(children='Hello World!', className= 'H1-Text H1-Text-Display')if __name__ == '__main__': app.run_server()
app.css:
.H1-Text{ width:20%;}.H1-Text-Display{ display:inline-block;}
This way, you can reuse classes for different components in your Dash code. It makes it cleaner and faster.
Note: In order for Dash to read the assets folder by default, kindly include __name__ in while declaring app = dash.Dash(__name__).
Congratulations,you’ve taken yourself to the next level in Dash.
In this article, you’ve learned —
Dash — Real-Time UpdatesDash — Adding CSS
Dash — Real-Time Updates
Dash — Adding CSS
The limit is the sky. Now go, build something, and share it with me. I’m waiting.
We are not done yet with our data journey. I am working on more stories, writings, and guides on the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data.
As usual, I end with a quote.
Data is the new science. Big Data holds the answers. — Pat Gelsinger, CEO of VMware
You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers!
I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data.
Thanks for reading! If you want to get in touch with me, feel free to reach me at [email protected] or my LinkedIn Profile. You can also view the code for previous write-ups in my Github. | [
{
"code": null,
"e": 413,
"s": 171,
"text": "Greetings data practitioners,I assume you are aware of the increase in demand for people who know how to communicate data. This is exactly why we should always seek to improve, learn more, and sharpen our skills in the data science industry."
},
{
"code": null,
"e": 604,
"s": 413,
"text": "Even with all the hype around Machine Learning, Data Visualizations do not lose their importance. Exploratory Data Analysis is often required before any Machine Learning is even planned out."
},
{
"code": null,
"e": 700,
"s": 604,
"text": "Large tech companies often need to communicate the data they own. We are the ones that execute."
},
{
"code": null,
"e": 768,
"s": 700,
"text": "A very good example would be google and their known, google trends."
},
{
"code": null,
"e": 895,
"s": 768,
"text": "Hence, building clean and beautiful visualizations is a valuable skill that will definitely make you stand out from the crowd."
},
{
"code": null,
"e": 929,
"s": 895,
"text": "Have you heard of Dash by Plotly?"
},
{
"code": null,
"e": 986,
"s": 929,
"text": "Dash is the new kid on the block. I wrote about it here."
},
{
"code": null,
"e": 1009,
"s": 986,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1204,
"s": 1009,
"text": "Basically, Dash is the new Python library that allows you to build amazing data visualization apps with highly customization user interface without the need to know any HTML, CSS, or Javascript."
},
{
"code": null,
"e": 1304,
"s": 1204,
"text": "It takes away the headaches of deploying apps, making it mobile responsive and easily maintainable."
},
{
"code": null,
"e": 1352,
"s": 1304,
"text": "But you know that already, what was I thinking."
},
{
"code": null,
"e": 1401,
"s": 1352,
"text": "You’re not here for that, you want to know more."
},
{
"code": null,
"e": 1596,
"s": 1401,
"text": "In this article, we will talk about how you can add more customizations to your Dash web app. We will also go in-depth on how you can update the dashboard without any interactions, in real-time."
},
{
"code": null,
"e": 1854,
"s": 1596,
"text": "Dash visualizations are based on Plotly.It’s important that you understand the fundamentals of building simple Plotly Graphs. I wrote about building the basic Plotly graphs here, covering the concepts you need to understand while building any sort of graph."
},
{
"code": null,
"e": 1877,
"s": 1854,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1984,
"s": 1877,
"text": "In order to work with Plotly, you will need to perform some soft transformations on your data with Pandas."
},
{
"code": null,
"e": 2122,
"s": 1984,
"text": "I got you covered. I happen to have written A Guide to Pandas as well.If you need to refresh your memory on Pandas, please go through it."
},
{
"code": null,
"e": 2145,
"s": 2122,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2162,
"s": 2145,
"text": "pip install dash"
},
{
"code": null,
"e": 2196,
"s": 2162,
"text": "Working with Jupyter Notebooks..."
},
{
"code": null,
"e": 2369,
"s": 2196,
"text": "import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as goimport pandas as pdfrom dash.dependencies import Input, Output"
},
{
"code": null,
"e": 2439,
"s": 2369,
"text": "In this section, we will be talking about making your dashboard live."
},
{
"code": null,
"e": 2464,
"s": 2439,
"text": "Yes, you heard it right."
},
{
"code": null,
"e": 2645,
"s": 2464,
"text": "Dash allows its users to automate dashboards in real-time by updating its data source, without any interactions whatsoever. This is achieved by implementing the interval component."
},
{
"code": null,
"e": 2868,
"s": 2645,
"text": "The interval component from dash core components is a trigger that will fire callbacks periodically. To implement this on the app, simply connect the interval to a tag or graph you need to update, and let the magic happen."
},
{
"code": null,
"e": 2912,
"s": 2868,
"text": "We will explore this with a simple example."
},
{
"code": null,
"e": 3335,
"s": 2912,
"text": "app = dash.Dash()app.layout = html.Div([ html.H1(id='live-counter'), dcc.Interval( id='1-second-interval', interval=1000, n_intervals=0 )])@app.callback(Output('live-counter', 'children'), [Input('1-second-interval', 'n_intervals')])def update_layout(n): return 'This app has updated itself for {} times, every second.'.format(n)if __name__ == '__main__': app.run_server()"
},
{
"code": null,
"e": 3520,
"s": 3335,
"text": "In this section, we have simply defined an H1 tag and an interval component.We then defined a callback function, taking the interval component as an input and the H1 tag as the output."
},
{
"code": null,
"e": 3677,
"s": 3520,
"text": "An important property in the component is the interval property, which defines how often the component will trigger. Here, we are taking 1-second intervals."
},
{
"code": null,
"e": 3766,
"s": 3677,
"text": "What this means is that the callback function will trigger every 1 second automatically."
},
{
"code": null,
"e": 3983,
"s": 3766,
"text": "Lastly, we can make use of the n property in the interval component which updates itself according to the time interval we have defined. Simply insert n as part of the text we displayed to show the real-time changes."
},
{
"code": null,
"e": 4065,
"s": 3983,
"text": "Let’s bring it up a notch, shall we?How do we implement this for an actual graph?"
},
{
"code": null,
"e": 4101,
"s": 4065,
"text": "Simple, we update the graph itself."
},
{
"code": null,
"e": 4309,
"s": 4101,
"text": "In this block of code, we are simply defining a graph component and an interval component. We then defined a callback function, taking the interval component as an input and the graph’s figure as the output."
},
{
"code": null,
"e": 4377,
"s": 4309,
"text": "Before I jump into the explanation, a good flow chart always helps."
},
{
"code": null,
"e": 4584,
"s": 4377,
"text": "For every second, new data with a random number is appended into our data source. A new graph is then plotted based on that updated data source. The graph on the app is then replaced with the updated graph."
},
{
"code": null,
"e": 4782,
"s": 4584,
"text": "Here, we have simply inserted random numbers as data into our data source. However, if you are following, you will know that you can easily append/overwrite your data source based on your pipeline."
},
{
"code": null,
"e": 4822,
"s": 4782,
"text": "Are you web-scraping data in real-time?"
},
{
"code": null,
"e": 4879,
"s": 4822,
"text": "Are you visualizing transactional data for your website?"
},
{
"code": null,
"e": 4969,
"s": 4879,
"text": "You can easily declare that as your data source and visualize it every second/minute/day."
},
{
"code": null,
"e": 5088,
"s": 4969,
"text": "I hope you realize by now how powerful Dash is. It is only up to your imagination on how you can take advantage of it."
},
{
"code": null,
"e": 5355,
"s": 5088,
"text": "Note: Be mindful of updating graphs in too small of an interval. It is not wise to have real-time data without having a real use case for it because there might be extremely heavy computations in updating data sources, not to mention plotting extremely heavy graphs."
},
{
"code": null,
"e": 5425,
"s": 5355,
"text": "So you’re able to build graphs and automate them by now. What’s next?"
},
{
"code": null,
"e": 5586,
"s": 5425,
"text": "You need to design and customize your web app so it looks beautiful to the user. From color to positioning, Dash allows you to do so easily with a line of code."
},
{
"code": null,
"e": 5738,
"s": 5586,
"text": "CSS stands for Cascading Style Sheets which is the main language to style your HTML tags. If you wish to beautify your web app, learning CSS is a must."
},
{
"code": null,
"e": 5945,
"s": 5738,
"text": "Dash allows you to add CSS in the Python code itself.For nearly every component in Dash, there is a property named ‘style’ which allows you to declare the CSS for that component through a Python Dictionary."
},
{
"code": null,
"e": 6025,
"s": 5945,
"text": "html.H1(children='Hello World!',style={'width':'20%','display':'inline-block'})"
},
{
"code": null,
"e": 6121,
"s": 6025,
"text": "That’s cool and all. However, there is a better way to declare your CSS if your web app scales."
},
{
"code": null,
"e": 6232,
"s": 6121,
"text": "Exclusively declaring CSS for each component is inefficient, it will also slow down the load time for the app."
},
{
"code": null,
"e": 6346,
"s": 6232,
"text": "Hence, we can use the Classname solution in Dash, which is essentially the class attribute for your HTML element."
},
{
"code": null,
"e": 6621,
"s": 6346,
"text": "In the same folder where you started your Dash code, create another folder named assets and place all your CSS and Javascript code in it. By default, the latest Dash version will read everything that ends with .css and .js from the assets folder and apply it to the web app."
},
{
"code": null,
"e": 6629,
"s": 6621,
"text": "app.py:"
},
{
"code": null,
"e": 6784,
"s": 6629,
"text": "app = dash.Dash(__name__)app.layout = html.H1(children='Hello World!', className= 'H1-Text H1-Text-Display')if __name__ == '__main__': app.run_server()"
},
{
"code": null,
"e": 6793,
"s": 6784,
"text": "app.css:"
},
{
"code": null,
"e": 6855,
"s": 6793,
"text": ".H1-Text{ width:20%;}.H1-Text-Display{ display:inline-block;}"
},
{
"code": null,
"e": 6963,
"s": 6855,
"text": "This way, you can reuse classes for different components in your Dash code. It makes it cleaner and faster."
},
{
"code": null,
"e": 7095,
"s": 6963,
"text": "Note: In order for Dash to read the assets folder by default, kindly include __name__ in while declaring app = dash.Dash(__name__)."
},
{
"code": null,
"e": 7160,
"s": 7095,
"text": "Congratulations,you’ve taken yourself to the next level in Dash."
},
{
"code": null,
"e": 7194,
"s": 7160,
"text": "In this article, you’ve learned —"
},
{
"code": null,
"e": 7236,
"s": 7194,
"text": "Dash — Real-Time UpdatesDash — Adding CSS"
},
{
"code": null,
"e": 7261,
"s": 7236,
"text": "Dash — Real-Time Updates"
},
{
"code": null,
"e": 7279,
"s": 7261,
"text": "Dash — Adding CSS"
},
{
"code": null,
"e": 7361,
"s": 7279,
"text": "The limit is the sky. Now go, build something, and share it with me. I’m waiting."
},
{
"code": null,
"e": 7625,
"s": 7361,
"text": "We are not done yet with our data journey. I am working on more stories, writings, and guides on the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data."
},
{
"code": null,
"e": 7655,
"s": 7625,
"text": "As usual, I end with a quote."
},
{
"code": null,
"e": 7739,
"s": 7655,
"text": "Data is the new science. Big Data holds the answers. — Pat Gelsinger, CEO of VMware"
},
{
"code": null,
"e": 7912,
"s": 7739,
"text": "You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers!"
},
{
"code": null,
"e": 8133,
"s": 7912,
"text": "I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data."
}
] |
How can I install or enable innoDB in MySQL? | In order to enable innoDB in MySQ, you need to work around my.ini file. However, in MySQL version 8, the default storage engine is innoDB. Check the same from my.ini file −
You can even set this at the time of table creation −
mysql> create table DemoTable
(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentFirstName varchar(100),
StudentLastName varchar(100),
StudentAge int
) ENGINE=InnoDB;
Query OK, 0 rows affected (1.66 sec)
Let us now run a query to check the engine type of specific table −
mysql> select table_name,engine from information_schema.tables where table_name="DemoTable";
This will produce the following output −
+--------------+--------+
| TABLE_NAME | ENGINE |
+--------------+--------+
| DemoTable | InnoDB |
+--------------+--------+
1 row in set (0.16 sec) | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "In order to enable innoDB in MySQ, you need to work around my.ini file. However, in MySQL version 8, the default storage engine is innoDB. Check the same from my.ini file −"
},
{
"code": null,
"e": 1289,
"s": 1235,
"text": "You can even set this at the time of table creation −"
},
{
"code": null,
"e": 1520,
"s": 1289,
"text": "mysql> create table DemoTable\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentFirstName varchar(100),\n StudentLastName varchar(100),\n StudentAge int\n ) ENGINE=InnoDB;\nQuery OK, 0 rows affected (1.66 sec)"
},
{
"code": null,
"e": 1588,
"s": 1520,
"text": "Let us now run a query to check the engine type of specific table −"
},
{
"code": null,
"e": 1681,
"s": 1588,
"text": "mysql> select table_name,engine from information_schema.tables where table_name=\"DemoTable\";"
},
{
"code": null,
"e": 1722,
"s": 1681,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1876,
"s": 1722,
"text": "+--------------+--------+\n| TABLE_NAME | ENGINE |\n+--------------+--------+\n| DemoTable | InnoDB |\n+--------------+--------+\n1 row in set (0.16 sec)"
}
] |
C# | Math.Truncate() Method - GeeksforGeeks | 02 Jul, 2021
In C#, Math.Truncate() is a math class method which is used to compute an integral part of a specified decimal number or double-precision floating-point number. This method can be overloaded by passing the different type of parameters to it as follows:
Math.Truncate(Decimal)
Math.Truncate(Double)
This method is used to compute an integral part of a specified decimal number.
Syntax:
public static decimal Truncate(decimal dec)
Parameter:
dec: It is the specified number which is to be truncated and type of this parameter is System.Decimal.
Return Type: This method only return the integral part of dec and discard the fractional part. The type of this method is System.Decimal.
Example:
C#
// C# Program to illustrate the// Math.Truncate(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // variables of Decimal type Decimal dec = 45.89511m; Decimal dec2 = 54569.478021m; // using function and displaying result Console.WriteLine(Math.Truncate(dec)); Console.WriteLine(Math.Truncate(dec2)); }}
Output:
45
54569
This method is used to compute an integral part of a specified double precision floating point number.
Syntax:
public static double Truncate(decimal dob)
Parameter:
dob: It is the specified number which is to be truncated and type of this parameter is System.Double.
Return Type: This method only returns an integral part of dob and discard the fractional part. The type of this method is System.Double.
Note: If dob is NaN, then method will return NaN value and If dob is PositiveInfinity, then method will return PositiveInfinity value. If dob is NegativeInfinity, then method will return NegativeInfinity value.
Example:
C#
// C# Program to illustrate the// Math.Truncate(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // variables of Double type Double dob = 45649.25649800; Double dob2 = 2000150.2654459780; // using function and displaying result Console.WriteLine(Math.Truncate(dob)); Console.WriteLine(Math.Truncate(dob2)); }}
Output:
45649
2000150
There can be other ways to truncate numbers like casting it to an int, but it does not always work. As compare to other Math methods, this is probably the most reliable way to perform the required tasks.
sagartomar9927
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object | [
{
"code": null,
"e": 24013,
"s": 23985,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 24266,
"s": 24013,
"text": "In C#, Math.Truncate() is a math class method which is used to compute an integral part of a specified decimal number or double-precision floating-point number. This method can be overloaded by passing the different type of parameters to it as follows:"
},
{
"code": null,
"e": 24289,
"s": 24266,
"text": "Math.Truncate(Decimal)"
},
{
"code": null,
"e": 24311,
"s": 24289,
"text": "Math.Truncate(Double)"
},
{
"code": null,
"e": 24390,
"s": 24311,
"text": "This method is used to compute an integral part of a specified decimal number."
},
{
"code": null,
"e": 24399,
"s": 24390,
"text": "Syntax: "
},
{
"code": null,
"e": 24443,
"s": 24399,
"text": "public static decimal Truncate(decimal dec)"
},
{
"code": null,
"e": 24454,
"s": 24443,
"text": "Parameter:"
},
{
"code": null,
"e": 24557,
"s": 24454,
"text": "dec: It is the specified number which is to be truncated and type of this parameter is System.Decimal."
},
{
"code": null,
"e": 24695,
"s": 24557,
"text": "Return Type: This method only return the integral part of dec and discard the fractional part. The type of this method is System.Decimal."
},
{
"code": null,
"e": 24705,
"s": 24695,
"text": "Example: "
},
{
"code": null,
"e": 24708,
"s": 24705,
"text": "C#"
},
{
"code": "// C# Program to illustrate the// Math.Truncate(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // variables of Decimal type Decimal dec = 45.89511m; Decimal dec2 = 54569.478021m; // using function and displaying result Console.WriteLine(Math.Truncate(dec)); Console.WriteLine(Math.Truncate(dec2)); }}",
"e": 25109,
"s": 24708,
"text": null
},
{
"code": null,
"e": 25118,
"s": 25109,
"text": "Output: "
},
{
"code": null,
"e": 25127,
"s": 25118,
"text": "45\n54569"
},
{
"code": null,
"e": 25230,
"s": 25127,
"text": "This method is used to compute an integral part of a specified double precision floating point number."
},
{
"code": null,
"e": 25239,
"s": 25230,
"text": "Syntax: "
},
{
"code": null,
"e": 25282,
"s": 25239,
"text": "public static double Truncate(decimal dob)"
},
{
"code": null,
"e": 25293,
"s": 25282,
"text": "Parameter:"
},
{
"code": null,
"e": 25395,
"s": 25293,
"text": "dob: It is the specified number which is to be truncated and type of this parameter is System.Double."
},
{
"code": null,
"e": 25532,
"s": 25395,
"text": "Return Type: This method only returns an integral part of dob and discard the fractional part. The type of this method is System.Double."
},
{
"code": null,
"e": 25743,
"s": 25532,
"text": "Note: If dob is NaN, then method will return NaN value and If dob is PositiveInfinity, then method will return PositiveInfinity value. If dob is NegativeInfinity, then method will return NegativeInfinity value."
},
{
"code": null,
"e": 25753,
"s": 25743,
"text": "Example: "
},
{
"code": null,
"e": 25756,
"s": 25753,
"text": "C#"
},
{
"code": "// C# Program to illustrate the// Math.Truncate(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // variables of Double type Double dob = 45649.25649800; Double dob2 = 2000150.2654459780; // using function and displaying result Console.WriteLine(Math.Truncate(dob)); Console.WriteLine(Math.Truncate(dob2)); }}",
"e": 26163,
"s": 25756,
"text": null
},
{
"code": null,
"e": 26172,
"s": 26163,
"text": "Output: "
},
{
"code": null,
"e": 26186,
"s": 26172,
"text": "45649\n2000150"
},
{
"code": null,
"e": 26391,
"s": 26186,
"text": "There can be other ways to truncate numbers like casting it to an int, but it does not always work. As compare to other Math methods, this is probably the most reliable way to perform the required tasks. "
},
{
"code": null,
"e": 26406,
"s": 26391,
"text": "sagartomar9927"
},
{
"code": null,
"e": 26418,
"s": 26406,
"text": "CSharp-Math"
},
{
"code": null,
"e": 26432,
"s": 26418,
"text": "CSharp-method"
},
{
"code": null,
"e": 26435,
"s": 26432,
"text": "C#"
},
{
"code": null,
"e": 26533,
"s": 26435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26542,
"s": 26533,
"text": "Comments"
},
{
"code": null,
"e": 26555,
"s": 26542,
"text": "Old Comments"
},
{
"code": null,
"e": 26578,
"s": 26555,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 26606,
"s": 26578,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26652,
"s": 26606,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26667,
"s": 26652,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26707,
"s": 26667,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26730,
"s": 26707,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26748,
"s": 26730,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26779,
"s": 26748,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26801,
"s": 26779,
"text": "C# | Abstract Classes"
}
] |
How to find similar words in vector of strings in R? | Sometimes strings in a vector of strings have spelling errors and we want to extract the similar words to avoid that spelling error because similar words are likely to represent the correct and incorrect form of a word. This can be done by using agrep with lapply function.
Live Demo
x1<-c("India","United Kingdoms","Indiaa","Egyypt","United
Kingdom","Turkey","Egypt","Belaarus","Belarus")
lapply(x1,agrep,x1,value=TRUE)
[[1]]
[1] "India" "Indiaa"
[[2]]
[1] "United Kingdoms" "United Kingdom"
[[3]]
[1] "India" "Indiaa"
[[4]]
[1] "Egyypt" "Egypt"
[[5]]
[1] "United Kingdoms" "United Kingdom"
[[6]]
[1] "Turkey"
[[7]]
[1] "Egyypt" "Egypt"
[[8]]
[1] "Belaarus" "Belarus"
[[9]]
[1] "Belaarus" "Belarus"
Live Demo
x2<-c("Alhadi","Umair","Omar","Alhadi","Shanti","Shant","Umaer","Peter","Rahul","Pattrick","P
eeter","Rahuls")
lapply(x2,agrep,x2,value=TRUE)
[[1]]
[1] "Al-hadi" "Alhadi"
[[2]]
[1] "Umair" "Umaer"
[[3]]
[1] "Omar"
[[4]]
[1] "Al-hadi" "Alhadi"
[[5]]
[1] "Shanti" "Shant"
[[6]]
[1] "Shanti" "Shant"
[[7]]
[1] "Umair" "Umaer"
[[8]]
[1] "Peter" "Peeter"
[[9]]
[1] "Rahul" "Rahuls"
[[10]]
[1] "Pattrick"
[[11]]
[1] "Peter" "Peeter"
[[12]]
[1] "Rahul" "Rahuls"
Live Demo
x3<-c("Alabamaa","New Yorky","New
Yok","Alabma","Florida","Illinois","Texas","Illinoise")
lapply(x3,agrep,x3,value=TRUE)
[[1]]
[1] "Alabamaa"
[[2]]
[1] "New Yorky"
[[3]]
[1] "New Yorky" "New Yok"
[[4]]
[1] "Alabamaa" "Alabma"
[[5]]
[1] "Florida"
[[6]]
[1] "Illinois" "Illinoise"
[[7]]
[1] "Texas"
[[8]]
[1] "Illinois" "Illinoise" | [
{
"code": null,
"e": 1336,
"s": 1062,
"text": "Sometimes strings in a vector of strings have spelling errors and we want to extract the similar words to avoid that spelling error because similar words are likely to represent the correct and incorrect form of a word. This can be done by using agrep with lapply function."
},
{
"code": null,
"e": 1347,
"s": 1336,
"text": " Live Demo"
},
{
"code": null,
"e": 1484,
"s": 1347,
"text": "x1<-c(\"India\",\"United Kingdoms\",\"Indiaa\",\"Egyypt\",\"United\nKingdom\",\"Turkey\",\"Egypt\",\"Belaarus\",\"Belarus\")\nlapply(x1,agrep,x1,value=TRUE)"
},
{
"code": null,
"e": 1763,
"s": 1484,
"text": "[[1]]\n[1] \"India\" \"Indiaa\"\n[[2]]\n[1] \"United Kingdoms\" \"United Kingdom\"\n[[3]]\n[1] \"India\" \"Indiaa\"\n[[4]]\n[1] \"Egyypt\" \"Egypt\"\n[[5]]\n[1] \"United Kingdoms\" \"United Kingdom\"\n[[6]]\n[1] \"Turkey\"\n[[7]]\n[1] \"Egyypt\" \"Egypt\"\n[[8]]\n[1] \"Belaarus\" \"Belarus\"\n[[9]]\n[1] \"Belaarus\" \"Belarus\""
},
{
"code": null,
"e": 1774,
"s": 1763,
"text": " Live Demo"
},
{
"code": null,
"e": 1916,
"s": 1774,
"text": "x2<-c(\"Alhadi\",\"Umair\",\"Omar\",\"Alhadi\",\"Shanti\",\"Shant\",\"Umaer\",\"Peter\",\"Rahul\",\"Pattrick\",\"P\neeter\",\"Rahuls\")\nlapply(x2,agrep,x2,value=TRUE)"
},
{
"code": null,
"e": 2229,
"s": 1916,
"text": "[[1]]\n[1] \"Al-hadi\" \"Alhadi\"\n[[2]]\n[1] \"Umair\" \"Umaer\"\n[[3]]\n[1] \"Omar\"\n[[4]]\n[1] \"Al-hadi\" \"Alhadi\"\n[[5]]\n[1] \"Shanti\" \"Shant\"\n[[6]]\n[1] \"Shanti\" \"Shant\"\n[[7]]\n[1] \"Umair\" \"Umaer\"\n[[8]]\n[1] \"Peter\" \"Peeter\"\n[[9]]\n[1] \"Rahul\" \"Rahuls\"\n[[10]]\n[1] \"Pattrick\"\n[[11]]\n[1] \"Peter\" \"Peeter\"\n[[12]]\n[1] \"Rahul\" \"Rahuls\""
},
{
"code": null,
"e": 2240,
"s": 2229,
"text": " Live Demo"
},
{
"code": null,
"e": 2361,
"s": 2240,
"text": "x3<-c(\"Alabamaa\",\"New Yorky\",\"New\nYok\",\"Alabma\",\"Florida\",\"Illinois\",\"Texas\",\"Illinoise\")\nlapply(x3,agrep,x3,value=TRUE)"
},
{
"code": null,
"e": 2570,
"s": 2361,
"text": "[[1]]\n[1] \"Alabamaa\"\n[[2]]\n[1] \"New Yorky\"\n[[3]]\n[1] \"New Yorky\" \"New Yok\"\n[[4]]\n[1] \"Alabamaa\" \"Alabma\"\n[[5]]\n[1] \"Florida\"\n[[6]]\n[1] \"Illinois\" \"Illinoise\"\n[[7]]\n[1] \"Texas\"\n[[8]]\n[1] \"Illinois\" \"Illinoise\""
}
] |
How to get index of object inside an array that matches the condition in jQuery ? - GeeksforGeeks | 15 Oct, 2020
jQuery is a free and open-source JavaScript library designed to add interactivity to the HTML web pages. jQuery is similar to JavaScript in terms of functionality but what makes it popular is its simplicity and ease of use. jQuery comes bundles with inbuilt methods that help achieve the desired output. In this article, we will discuss the two methods in jQuery that can be used to get the index of an object inside an array that matches the given condition. The two methods are discussed as follows.
findIndex(): This method executes the function passed as a parameter for each element present in the array.Syntax:array.findIndex(function(curr, index, arr), thisVal)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is true. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned.some(): The arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.Syntax:array.some(function(curr, index, arr), thisval)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is “true”. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned.
findIndex(): This method executes the function passed as a parameter for each element present in the array.Syntax:array.findIndex(function(curr, index, arr), thisVal)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is true. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned.
Syntax:array.findIndex(function(curr, index, arr), thisVal)
array.findIndex(function(curr, index, arr), thisVal)
Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.
curr: Current element of the array on which the function will be executed. This ismandatory parameter.
index: Index of the current element. This is optional parameter.
arr: Array to which the current element belongs. This is optional parameter.
thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.
Return value: This method returns the index of the first element for which the returnvalue of the function is true. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned.
some(): The arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.Syntax:array.some(function(curr, index, arr), thisval)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is “true”. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned.
Syntax:array.some(function(curr, index, arr), thisval)
array.some(function(curr, index, arr), thisval)
Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.
curr: Current element of the array on which the function will be executed. This ismandatory parameter.
index: Index of the current element. This is optional parameter.
arr: Array to which the current element belongs. This is optional parameter.
thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.
Return value: This method returns the index of the first element for which the returnvalue of the function is “true”. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned.
Approach 1: In the first approach, we show the procedure for finding the index of an object in an array that matches a given condition using the findIndex() method of jQuery. The findIndex() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable. The value of the index variable is returned to the console. Similarly, for the index1 variable, there is more than one object having age=”20′′. In this situation, the index of the first matched object is returned. If no match is present then the output is -1.
// Write JavaScript code herevar arr = [ { name: "ram", age: "20" }, { name: "sam", age: "20" }, { name: "tom", age: "19" }, { name: "harry", age: "19" }]; var index; arr.findIndex(function (entry, i) { if (entry.name == "tom") { index = i; return true; }}); // Arrow function expression ( =>) is // an alternative to a traditional // function expression// It has limited use and returns the// index of the first element for /// which the function returns "true"index1 = arr.findIndex(x => x.age === "20"); console.log(index);console.log(index1);
Output:
2
0
Approach 2: In the second approach, we show the procedure for finding the index of an object in an array that matches a given condition using the some() method of jQuery. The some() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable. The value of the index variable is returned to the console.
// Write Javascript code herevar arr = [ { name: "ram", age: "20" }, { name: "sam", age: "21" }, { name: "tom", age: "19" }, { name: "harry", age: "19" }]; var index; arr.some(function (entry, i) { if (entry.name == "tom") { index = i; return true; }}); console.log(index);
Output:
2
jQuery-Misc
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
How to get the value in an input text box using jQuery ?
Difference Between JavaScript and jQuery
QR Code Generator using HTML, CSS and jQuery
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25675,
"s": 25647,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 26177,
"s": 25675,
"text": "jQuery is a free and open-source JavaScript library designed to add interactivity to the HTML web pages. jQuery is similar to JavaScript in terms of functionality but what makes it popular is its simplicity and ease of use. jQuery comes bundles with inbuilt methods that help achieve the desired output. In this article, we will discuss the two methods in jQuery that can be used to get the index of an object inside an array that matches the given condition. The two methods are discussed as follows."
},
{
"code": null,
"e": 27938,
"s": 26177,
"text": "findIndex(): This method executes the function passed as a parameter for each element present in the array.Syntax:array.findIndex(function(curr, index, arr), thisVal)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is true. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned.some(): The arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.Syntax:array.some(function(curr, index, arr), thisval)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is “true”. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned."
},
{
"code": null,
"e": 28803,
"s": 27938,
"text": "findIndex(): This method executes the function passed as a parameter for each element present in the array.Syntax:array.findIndex(function(curr, index, arr), thisVal)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is true. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned."
},
{
"code": null,
"e": 28863,
"s": 28803,
"text": "Syntax:array.findIndex(function(curr, index, arr), thisVal)"
},
{
"code": null,
"e": 28916,
"s": 28863,
"text": "array.findIndex(function(curr, index, arr), thisVal)"
},
{
"code": null,
"e": 29347,
"s": 28916,
"text": "Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional."
},
{
"code": null,
"e": 29450,
"s": 29347,
"text": "curr: Current element of the array on which the function will be executed. This ismandatory parameter."
},
{
"code": null,
"e": 29515,
"s": 29450,
"text": "index: Index of the current element. This is optional parameter."
},
{
"code": null,
"e": 29592,
"s": 29515,
"text": "arr: Array to which the current element belongs. This is optional parameter."
},
{
"code": null,
"e": 29771,
"s": 29592,
"text": "thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional."
},
{
"code": null,
"e": 30040,
"s": 29771,
"text": "Return value: This method returns the index of the first element for which the returnvalue of the function is true. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned."
},
{
"code": null,
"e": 30937,
"s": 30040,
"text": "some(): The arr.some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method.Syntax:array.some(function(curr, index, arr), thisval)Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional.Return value: This method returns the index of the first element for which the returnvalue of the function is “true”. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned."
},
{
"code": null,
"e": 30992,
"s": 30937,
"text": "Syntax:array.some(function(curr, index, arr), thisval)"
},
{
"code": null,
"e": 31040,
"s": 30992,
"text": "array.some(function(curr, index, arr), thisval)"
},
{
"code": null,
"e": 31471,
"s": 31040,
"text": "Parameter:curr: Current element of the array on which the function will be executed. This ismandatory parameter.index: Index of the current element. This is optional parameter.arr: Array to which the current element belongs. This is optional parameter.thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional."
},
{
"code": null,
"e": 31574,
"s": 31471,
"text": "curr: Current element of the array on which the function will be executed. This ismandatory parameter."
},
{
"code": null,
"e": 31639,
"s": 31574,
"text": "index: Index of the current element. This is optional parameter."
},
{
"code": null,
"e": 31716,
"s": 31639,
"text": "arr: Array to which the current element belongs. This is optional parameter."
},
{
"code": null,
"e": 31895,
"s": 31716,
"text": "thisVal: This value is passed to the function as its “this” value. If this parameter isnot specified, the value “undefined” is passed as “this” value. This parameter is optional."
},
{
"code": null,
"e": 32166,
"s": 31895,
"text": "Return value: This method returns the index of the first element for which the returnvalue of the function is “true”. If no match is found it returns -1. If there is more than one element thatfulfills the criteria then the index of the first matched element is returned."
},
{
"code": null,
"e": 32896,
"s": 32166,
"text": "Approach 1: In the first approach, we show the procedure for finding the index of an object in an array that matches a given condition using the findIndex() method of jQuery. The findIndex() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable. The value of the index variable is returned to the console. Similarly, for the index1 variable, there is more than one object having age=”20′′. In this situation, the index of the first matched object is returned. If no match is present then the output is -1."
},
{
"code": "// Write JavaScript code herevar arr = [ { name: \"ram\", age: \"20\" }, { name: \"sam\", age: \"20\" }, { name: \"tom\", age: \"19\" }, { name: \"harry\", age: \"19\" }]; var index; arr.findIndex(function (entry, i) { if (entry.name == \"tom\") { index = i; return true; }}); // Arrow function expression ( =>) is // an alternative to a traditional // function expression// It has limited use and returns the// index of the first element for /// which the function returns \"true\"index1 = arr.findIndex(x => x.age === \"20\"); console.log(index);console.log(index1); ",
"e": 33482,
"s": 32896,
"text": null
},
{
"code": null,
"e": 33490,
"s": 33482,
"text": "Output:"
},
{
"code": null,
"e": 33497,
"s": 33490,
"text": " 2\n 0\n"
},
{
"code": null,
"e": 34018,
"s": 33497,
"text": "Approach 2: In the second approach, we show the procedure for finding the index of an object in an array that matches a given condition using the some() method of jQuery. The some() method takes a function as the first parameter. This function is executed on every element of the array and the element for which the function returns “true” is the one that matched the specified condition. Thus the index of this matched element is stored in the index variable. The value of the index variable is returned to the console."
},
{
"code": "// Write Javascript code herevar arr = [ { name: \"ram\", age: \"20\" }, { name: \"sam\", age: \"21\" }, { name: \"tom\", age: \"19\" }, { name: \"harry\", age: \"19\" }]; var index; arr.some(function (entry, i) { if (entry.name == \"tom\") { index = i; return true; }}); console.log(index);",
"e": 34329,
"s": 34018,
"text": null
},
{
"code": null,
"e": 34337,
"s": 34329,
"text": "Output:"
},
{
"code": null,
"e": 34341,
"s": 34337,
"text": " 2\n"
},
{
"code": null,
"e": 34353,
"s": 34341,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 34360,
"s": 34353,
"text": "JQuery"
},
{
"code": null,
"e": 34377,
"s": 34360,
"text": "Web Technologies"
},
{
"code": null,
"e": 34475,
"s": 34377,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34484,
"s": 34475,
"text": "Comments"
},
{
"code": null,
"e": 34497,
"s": 34484,
"text": "Old Comments"
},
{
"code": null,
"e": 34570,
"s": 34497,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 34593,
"s": 34570,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 34650,
"s": 34593,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 34691,
"s": 34650,
"text": "Difference Between JavaScript and jQuery"
},
{
"code": null,
"e": 34736,
"s": 34691,
"text": "QR Code Generator using HTML, CSS and jQuery"
},
{
"code": null,
"e": 34778,
"s": 34736,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 34811,
"s": 34778,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34873,
"s": 34811,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34916,
"s": 34873,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
SAP HANA - Quick Guide | SAP HANA is a combination of HANA Database, Data Modeling, HANA Administration and Data Provisioning in one single suite. In SAP HANA, HANA stands for High-Performance Analytic Appliance.
According to former SAP executive, Dr. Vishal Sikka, HANA stands for Hasso’s New Architecture. HANA developed interest by mid-2011 and various fortune 500 companies started considering it as an option to maintain Business Warehouse needs after that.
The main features of SAP HANA are given below −
SAP HANA is a combination of software and hardware innovation to process huge amount of real time data.
SAP HANA is a combination of software and hardware innovation to process huge amount of real time data.
Based on multi core architecture in distributed system environment.
Based on multi core architecture in distributed system environment.
Based on row and column type of data-storage in database.
Based on row and column type of data-storage in database.
Used extensively in Memory Computing Engine (IMCE) to process and analyze massive amount of real time data.
Used extensively in Memory Computing Engine (IMCE) to process and analyze massive amount of real time data.
It reduces cost of ownership, increases application performance, enables new applications to run on real time environment that were not possible before.
It reduces cost of ownership, increases application performance, enables new applications to run on real time environment that were not possible before.
It is written in C++, supports and runs on only one Operating System Suse Linux Enterprise Server 11 SP1/2.
It is written in C++, supports and runs on only one Operating System Suse Linux Enterprise Server 11 SP1/2.
Today, most successful companies respond quickly to market changes and new opportunities. A key to this is the effective and efficient use of data and information by analyst and managers.
HANA overcomes the limitations mentioned below −
Due to increase in “Data Volume”, it is a challenge for the companies to provide access to real time data for analysis and business use.
Due to increase in “Data Volume”, it is a challenge for the companies to provide access to real time data for analysis and business use.
It involves high maintenance cost for IT companies to store and maintain large data volumes.
It involves high maintenance cost for IT companies to store and maintain large data volumes.
Due to unavailability of real time data, analysis and processing results are delayed.
Due to unavailability of real time data, analysis and processing results are delayed.
SAP has partnered with leading IT hardware vendors like IBM, Dell, Cisco etc. and combined it with SAP licensed services and technology to sell SAP HANA platform.
There are, total, 11 vendors that manufacture HANA Appliances and provide onsite support for installation and configuration of HANA system.
Top few Vendors include −
IBM
Dell
HP
Cisco
Fujitsu
Lenovo (China)
NEC
Huawei
According to statistics provided by SAP, IBM is one of major vendor of SAP HANA hardware appliances and has a market share of 50-52% but according to another market survey conducted by HANA clients, IBM has a market hold up to 70%.
HANA Hardware vendors provide preconfigured appliances for hardware, Operating System and SAP software product.
Vendor finalizes the installation by an onsite setup and configuration of HANA components. This onsite visit includes deployment of HANA system in Data Center, Connectivity to Organization Network, SAP system ID adaption, updates from Solution Manager, SAP Router Connectivity, SSL Enablement and other system configuration.
Customer/Client starts with connectivity of Data Source system and BI clients. HANA Studio Installation is completed on local system and HANA system is added to perform Data modeling and administration.
An In-Memory database means all the data from source system is stored in a RAM memory. In a conventional Database system, all data is stored in hard disk. SAP HANA In-Memory Database wastes no time in loading the data from hard disk to RAM. It provides faster access of data to multicore CPUs for information processing and analysis.
The main features of SAP HANA in-memory database are −
SAP HANA is Hybrid In-memory database.
SAP HANA is Hybrid In-memory database.
It combines row based, column based and Object Oriented base technology.
It combines row based, column based and Object Oriented base technology.
It uses parallel processing with multicore CPU Architecture.
It uses parallel processing with multicore CPU Architecture.
Conventional Database reads memory data in 5 milliseconds. SAP HANA In-Memory database reads data in 5 nanoseconds.
Conventional Database reads memory data in 5 milliseconds. SAP HANA In-Memory database reads data in 5 nanoseconds.
It means, memory reads in HANA database are 1 million times faster than a conventional database hard disk memory reads.
Analysts want to see current data immediately in real time and do not want to wait for data until it is loaded to SAP BW system. SAP HANA In-Memory processing allows loading of real time data with use of various data provisioning techniques.
HANA database takes advantage of in-memory processing to deliver the fastest data-retrieval speeds, which is enticing to companies struggling with high-scale online transactions or timely forecasting and planning.
HANA database takes advantage of in-memory processing to deliver the fastest data-retrieval speeds, which is enticing to companies struggling with high-scale online transactions or timely forecasting and planning.
Disk-based storage is still the enterprise standard and price of RAM has been declining steadily, so memory-intensive architectures will eventually replace slow, mechanical spinning disks and will lower the cost of data storage.
Disk-based storage is still the enterprise standard and price of RAM has been declining steadily, so memory-intensive architectures will eventually replace slow, mechanical spinning disks and will lower the cost of data storage.
In-Memory Column-based storage provides data compression up to 11 times, thus, reducing the storage space of huge data.
In-Memory Column-based storage provides data compression up to 11 times, thus, reducing the storage space of huge data.
This speed advantages offered by RAM storage system are further enhanced by the use of multi-core CPUs, multiple CPUs per node and multiple nodes per server in a distributed environment.
This speed advantages offered by RAM storage system are further enhanced by the use of multi-core CPUs, multiple CPUs per node and multiple nodes per server in a distributed environment.
SAP HANA studio is an Eclipse-based tool. SAP HANA studio is both, the central development environment and the main administration tool for HANA system. Additional features are −
It is a client tool, which can be used to access local or remote HANA system.
It is a client tool, which can be used to access local or remote HANA system.
It provides an environment for HANA Administration, HANA Information Modeling and Data Provisioning in HANA database.
It provides an environment for HANA Administration, HANA Information Modeling and Data Provisioning in HANA database.
SAP HANA Studio can be used on following platforms −
Microsoft Windows 32 and 64 bit versions of: Windows XP, Windows Vista, Windows 7
Microsoft Windows 32 and 64 bit versions of: Windows XP, Windows Vista, Windows 7
SUSE Linux Enterprise Server SLES11: x86 64 bit
SUSE Linux Enterprise Server SLES11: x86 64 bit
Mac OS, HANA studio client is not available
Mac OS, HANA studio client is not available
Depending on HANA Studio installation, not all features may be available. At the time of Studio installation, specify the features you want to install as per the role. To work on most recent version of HANA studio, Software Life Cycle Manager can be used for client update.
SAP HANA Studio provides perspectives to work on the following HANA features. You can choose Perspective in HANA Studio from the following option −
HANA Studio → Window → Open Perspective → Other
Toolset for various administration tasks, excluding transportable design-time repository objects. General troubleshooting tools like tracing, the catalog browser and SQL Console are also included.
It provides Toolset for content development. It addresses, in particular, the DataMarts and ABAP on SAP HANA scenarios, which do not include SAP HANA native application development (XS).
SAP HANA system contains a small Web server, which can be used to host small applications. It provides Toolset for developing SAP HANA native applications like application code written in Java and HTML.
By default, all features are installed.
To Perform HANA Database Administration and monitoring features, SAP HANA Administration Console Perspective can be used.
Administrator Editor can be accessed in several ways −
From System View Toolbar − Choose Open Administration default button
From System View Toolbar − Choose Open Administration default button
In System View − Double Click on HANA System or Open Perspective
In System View − Double Click on HANA System or Open Perspective
In Administration View: HANA studio provides multiple tabs to check configuration and health of the HANA system. Overview Tab tells General Information like, Operational Status, start time of first and last started service, version, build date and time, Platform, hardware manufacturer, etc.
Single or multiple systems can be added to HANA studio for administration and information modeling purpose. To add new HANA system, host name, instance number and database user name and password is required.
Port 3615 should be open to connect to Database
Port 31015 Instance No 10
Port 30015 Instance No 00
SSh port should also be opened
To add a system to HANA studio, follow the given steps.
Right Click in Navigator space and click on Add System. Enter HANA system details, i.e. Host name & Instance number and click next.
Enter Database user name and password to connect to SAP HANA database. Click on Next and then Finish.
Once you click on Finish, HANA system will be added to System View for administration and modeling purpose. Each HANA system has two main sub-nodes, Catalog and Content.
It contains all available Schemas i.e. all data structures, tables and data, Column views, Procedures that can be used in Content tab.
The Content tab contains design time repository, which holds all information of data models created with the HANA Modeler. These models are organized in Packages. The content node provides different views on same physical data.
System Monitor in HANA studio provides an overview of all your HANA system at a glance. From System Monitor, you can drill down into details of an individual system in Administration Editor. It tells about Data Disk, Log disk, Trace Disk, Alerts on resource usage with priority.
The following Information is available in System Monitor −
SAP HANA Information Modeler; also known as HANA Data Modeler is heart of HANA System. It enables to create modeling views at the top of database tables and implement business logic to create a meaningful report for analysis.
Provides multiple views of transactional data stored in physical tables of HANA database for analysis and business logic purpose.
Provides multiple views of transactional data stored in physical tables of HANA database for analysis and business logic purpose.
Informational modeler only works for column based storage tables.
Informational modeler only works for column based storage tables.
Information Modeling Views are consumed by Java or HTML based applications or SAP tools like SAP Lumira or Analysis Office for reporting purpose.
Information Modeling Views are consumed by Java or HTML based applications or SAP tools like SAP Lumira or Analysis Office for reporting purpose.
Also possible to use third party tools like MS Excel to connect to HANA and create reports.
Also possible to use third party tools like MS Excel to connect to HANA and create reports.
SAP HANA Modeling Views exploit real power of SAP HANA.
SAP HANA Modeling Views exploit real power of SAP HANA.
There are three types of Information Views, defined as −
Attribute View
Analytic View
Calculation View
SAP HANA Modeler Views can only be created on the top of Column based tables. Storing data in Column tables is not a new thing. Earlier it was assumed that storing data in Columnar based structure takes more memory size and not performance Optimized.
With evolution of SAP HANA, HANA used column based data storage in Information views and presented the real benefits of columnar tables over Row based tables.
In a Column store table, Data is stored vertically. So, similar data types come together as shown in the example above. It provides faster memory read and write operations with help of In-Memory Computing Engine.
In a conventional database, data is stored in Row based structure i.e. horizontally. SAP HANA stores data in both row and Column based structure. This provides Performance optimization, flexibility and data compression in HANA database.
Storing Data in Columnar based table has following benefits −
Data Compression
Data Compression
Faster read and write access to tables as compared to conventional Row based storage
Faster read and write access to tables as compared to conventional Row based storage
Flexibility & parallel processing
Flexibility & parallel processing
Perform Aggregations and Calculations at higher speed
Perform Aggregations and Calculations at higher speed
There are various methods and algorithms how data can be stored in Column based structure- Dictionary Compressed, Run Length Compressed and many more.
In Dictionary Compressed, cells are stored in form of numbers in tables and numeral cells are always performance optimized as compared to characters.
In Run length compressed, it saves the multiplier with cell value in numerical format and multiplier shows repetitive value in table.
It is always advisable to use Column based storage, if SQL statement has to perform aggregate functions and calculations. Column based tables always perform better when running aggregate functions like Sum, Count, Max, Min.
Row based storage is preferred when output has to return complete row. The example given below makes it easy to understand.
In the above example, while running an Aggregate function (Sum) in sales column with Where clause, it will only use Date and Sales column while running SQL query so if it is column based storage table then it will be performance optimized, faster as data is required only from two columns.
While running a simple Select query, full row has to be printed in output so it is advisable to store table as Row based in this scenario.
Attributes are non-measurable elements in a database table. They represent master data and similar to characteristics of BW. Attribute Views are dimensions in a database or are used to join dimensions or other attribute views in modeling.
Important features are −
Attribute views are used in Analytic and Calculation views.
Attribute view represent master data.
Used to filter size of dimension tables in Analytic and Calculation View.
Analytic Views use power of SAP HANA to perform calculations and aggregation functions on the tables in database. It has at least one fact table that has measures and primary keys of dimension tables and surrounded by dimension tables contain master data.
Important features are −
Analytic views are designed to perform Star schema queries.
Analytic views are designed to perform Star schema queries.
Analytic views contain at least one fact table and multiple dimension tables with master data and perform calculations and aggregations
Analytic views contain at least one fact table and multiple dimension tables with master data and perform calculations and aggregations
They are similar to Info Cubes and Info objects in SAP BW.
They are similar to Info Cubes and Info objects in SAP BW.
Analytic views can be created on top of Attribute views and Fact tables and performs calculations like number of unit sold, total price, etc.
Analytic views can be created on top of Attribute views and Fact tables and performs calculations like number of unit sold, total price, etc.
Calculation Views are used on top of Analytic and Attribute views to perform complex calculations, which are not possible with Analytic Views. Calculation view is a combination of base column tables, Attribute views and Analytic views to provide business logic.
Important features are −
Calculation Views are defined either graphical using HANA Modeling feature or scripted in the SQL.
Calculation Views are defined either graphical using HANA Modeling feature or scripted in the SQL.
It is created to perform complex calculations, which are not possible with other views- Attribute and Analytic views of SAP HANA modeler.
It is created to perform complex calculations, which are not possible with other views- Attribute and Analytic views of SAP HANA modeler.
One or more Attribute views and Analytic views are consumed with help of inbuilt functions like Projects, Union, Join, Rank in a Calculation View.
One or more Attribute views and Analytic views are consumed with help of inbuilt functions like Projects, Union, Join, Rank in a Calculation View.
SAP HANA was initially, developed in Java and C++ and designed to run only Operating System Suse Linux Enterprise Server 11. SAP HANA system consists of multiple components that are responsible to emphasize computing power of HANA system.
Most important component of SAP HANA system is Index Server, which contains SQL/MDX processor to handle query statements for database.
Most important component of SAP HANA system is Index Server, which contains SQL/MDX processor to handle query statements for database.
HANA system contains Name Server, Preprocessor Server, Statistics Server and XS engine, which is used to communicate and host small web applications and various other components.
HANA system contains Name Server, Preprocessor Server, Statistics Server and XS engine, which is used to communicate and host small web applications and various other components.
Index Server is heart of SAP HANA database system. It contains actual data and engines for processing that data. When SQL or MDX is fired for SAP HANA system, an Index Server takes care of all these requests and processes them. All HANA processing takes place in Index Server.
Index Server contains Data engines to handle all SQL/MDX statements that come to HANA database system. It also has Persistence Layer that is responsible for durability of HANA system and ensures HANA system is restored to most recent state when there is restart of system failure.
Index Server also has Session and Transaction Manager, which manage transactions and keep track of all running and closed transactions.
It is responsible for processing SQL/MDX transactions with data engines responsible to run queries. It segments all query requests and direct them to correct engine for the performance Optimization.
It also ensures that all SQL/MDX requests are authorized and also provide error handling for efficient processing of these statements. It contains several engines and processors for query execution −
MDX (Multi Dimension Expression) is query language for OLAP systems like SQL is used for Relational database. MDX Engine is responsible to handle queries and manipulates multidimensional data stored in OLAP cubes.
MDX (Multi Dimension Expression) is query language for OLAP systems like SQL is used for Relational database. MDX Engine is responsible to handle queries and manipulates multidimensional data stored in OLAP cubes.
Planning Engine is responsible to run planning operations within SAP HANA database.
Planning Engine is responsible to run planning operations within SAP HANA database.
Calculation Engine converts data into Calculation models to create logical execution plan to support parallel processing of statements.
Calculation Engine converts data into Calculation models to create logical execution plan to support parallel processing of statements.
Stored Procedure processor executes procedure calls for optimized processing; it converts OLAP cubes to HANA optimized cubes.
Stored Procedure processor executes procedure calls for optimized processing; it converts OLAP cubes to HANA optimized cubes.
It is responsible to coordinate all database transactions and keep track of all running and closed transactions.
When a transaction is executed or failed, Transaction manager notifies relevant data engine to take necessary actions.
Session management component is responsible to initialize and manage sessions and connections for SAP HANA system using predefined session parameters.
It is responsible for durability and atomicity of transactions in HANA system. Persistence layer provides built in disaster recovery system for HANA database.
It ensures database is restored to most recent state and ensures that all the transactions are completed or undone in case of a system failure or restart.
It is also responsible to manage data and transaction logs and also contain data backup, log backup and configuration back of HANA system. Backups are stored as save points in the Data Volumes via a Save Point coordinator, which is normally set to take back every 5-10 minutes.
Preprocessor Server in SAP HANA system is used for text data analysis.
Index Server uses preprocessor server for analyzing text data and extracting the information from text data when text search capabilities are used.
NAME server contains System Landscape information of HANA system. In distributed environment, there are multiple nodes with each node has multiple CPU’s, Name server holds topology of HANA system and has information about all the running components and information is spread on all the components.
Topology of SAP HANA system is recorded here.
Topology of SAP HANA system is recorded here.
It decreases the time in re-indexing as it holds which data is on which server in distributed environment.
It decreases the time in re-indexing as it holds which data is on which server in distributed environment.
This server checks and analyzes the health of all components in HANA system. Statistical Server is responsible for collecting the data related to system resources, their allocation and consumption of the resources and overall performance of HANA system.
It also provides historical data related to system performance for analyses purpose, to check and fix performance related issues in HANA system.
XS engine helps external Java and HTML based applications to access HANA system with help of XS client. As SAP HANA system contains a web server which can be used to host small JAVA/HTML based applications.
XS Engine transforms the persistence model stored in database into consumption model for clients exposed via HTTP/HTTPS.
SAP Host agent should be installed on all the machines that are part of SAP HANA system Landscape. SAP Host agent is used by Software Update Manager SUM for installing automatic updates to all components of HANA system in distributed environment.
LM structure of SAP HANA system contains information about current installation details. This information is used by Software Update Manager to install automatic updates on HANA system components.
This diagnostic agent provides all data to SAP Solution Manager to monitor SAP HANA system. This agent provides all the information about HANA database, which include database current state and general information.
It provides configuration details of HANA system when SAP SOLMAN is integrated with SAP HANA system.
SAP HANA studio repository helps HANA developers to update current version of HANA studio to latest versions. Studio Repository holds the code which does this update.
SAP Market Place is used to install updates for SAP systems. Software Update Manager for HANA system helps is update of HANA system from SAP Market place.
It is used for software downloads, customer messages, SAP Notes and requesting license keys for HANA system. It is also used to distribute HANA studio to end user’s systems.
SAP HANA Modeler option is used to create Information views on the top of schemas → tables in HANA database. These views are consumed by JAVA/HTML based applications or SAP Applications like SAP Lumira, Office Analysis or third party software like MS Excel for reporting purpose to meet business logic and to perform analysis and extract information.
HANA Modeling is done on the top of tables available in Catalog tab under Schema in HANA studio and all views are saved under Content table under Package.
You can create new Package under Content tab in HANA studio using right click on Content and New.
All Modeling Views created inside one package comes under the same package in HANA studio and categorized according to View Type.
Each View has different structure for Dimension and Fact tables. Dim tables are defined with master data and Fact table has Primary Key for dimension tables and measures like Number of Unit sold, Average delay time, Total Price, etc.
Fact Table contains Primary Keys for Dimension table and measures. They are joined with Dimension tables in HANA Views to meet business logic.
Example of Measures − Number of unit sold, Total Price, Average Delay time, etc.
Dimension Table contains master data and is joined with one or more fact tables to make some business logic. Dimension tables are used to create schemas with fact tables and can be normalized.
Example of Dimension Table − Customer, Product, etc.
Suppose a company sells products to customers. Every sale is a fact that happens within the company and the fact table is used to record these facts.
For example, row 3 in the fact table records the fact that customer 1 (Brian) bought one item on day 4. And, in a complete example, we would also have a product table and a time table so that we know what she bought and exactly when.
The fact table lists events that happen in our company (or at least the events that we want to analyze- No of Unit Sold, Margin, and Sales Revenue). The Dimension tables list the factors (Customer, Time, and Product) by which we want to analyze the data.
Schemas are logical description of tables in Data Warehouse. Schemas are created by joining multiple fact and Dimension tables to meet some business logic.
Database uses relational model to store data. However, Data Warehouse use Schemas that join dimensions and fact tables to meet business logic. There are three types of Schemas used in a Data Warehouse −
Star Schema
Snowflakes Schema
Galaxy Schema
In Star Schema, Each Dimension is joined to one single Fact table. Each Dimension is represented by only one dimension and is not further normalized.
Dimension Table contains set of attribute that are used to analyze the data.
Example − In example given below, we have a Fact table FactSales that has Primary keys for all the Dim tables and measures units_sold and dollars_ sold to do analysis.
We have four Dimension tables − DimTime, DimItem, DimBranch, DimLocation
Each Dimension table is connected to Fact table as Fact table has Primary Key for each Dimension Tables that is used to join two tables.
Facts/Measures in Fact Table are used for analysis purpose along with attribute in Dimension tables.
In Snowflakes schema, some of Dimension tables are further, normalized and Dim tables are connected to single Fact Table. Normalization is used to organize attributes and tables of database to minimize the data redundancy.
Normalization involves breaking a table into less redundant smaller tables without losing any information and smaller tables are joined to Dimension table.
In the above example, DimItem and DimLocation Dimension tables are normalized without losing any information. This is called Snowflakes schema where dimension tables are further normalized to smaller tables.
In Galaxy Schema, there are multiple Fact tables and Dimension tables. Each Fact table stores primary keys of few Dimension tables and measures/facts to do analysis.
In the above example, there are two Fact tables FactSales, FactShipping and multiple Dimension tables joined to Fact tables. Each Fact table contains Primary Key for joined Dim tables and measures/Facts to perform analysis.
Tables in HANA database can be accessed from HANA Studio in Catalogue tab under Schemas. New tables can be created using the two methods given below −
Using SQL editor
Using GUI option
SQL Console can be opened by selecting Schema name, in which, new table has to be created using System View SQL Editor option or by Right click on Schema name as shown below −
Once SQL Editor is opened, Schema name can be confirmed from the name written on the top of SQL Editor. New table can be created using SQL Create Table statement −
Create column Table Test1 (
ID INTEGER,
NAME VARCHAR(10),
PRIMARY KEY (ID)
);
In this SQL statement, we have created a Column table “Test1”, defined data types of table and Primary Key.
Once you write Create table SQL query, click on Execute option on top of SQL editor right side. Once the statement is executed, we will get a confirmation message as shown in snapshot given below −
Statement 'Create column Table Test1 (ID INTEGER,NAME VARCHAR(10), PRIMARY KEY (ID))'
successfully executed in 13 ms 761 μs (server processing time: 12 ms 979 μs) − Rows Affected: 0
Execution statement also tells about the time taken to execute the statement. Once statement is successfully executed, right click on Table tab under Schema name in System View and refresh. New Table will be reflected in the list of tables under Schema name.
Insert statement is used to enter the data in the Table using SQL editor.
Insert into TEST1 Values (1,'ABCD')
Insert into TEST1 Values (2,'EFGH');
Click on Execute.
You can right click on Table name and use Open Data Definition to see data type of the table. Open Data Preview/Open Content to see table contents.
Another way to create a table in HANA database is by using GUI option in HANA Studio.
Right Click on Table tab under Schema → Select ‘New Table’ option as shown in snapshot given below.
Once you click on New Table → It will open a window to enter the Table name, Choose Schema name from drop down, Define Table type from drop down list: Column Store or Row Store.
Define data type as shown below. Columns can be added by clicking on + sign, Primary Key can be chosen by clicking on cell under Primary key in front of Column name, Not Null will be active by default.
Once columns are added, click on Execute.
Once you Execute (F8), Right Click on Table Tab → Refresh. New Table will be reflected in the list of tables under chosen Schema. Below Insert Option can be used to insert data in table. Select statement to see content of table.
You can right click on Table name and use Open Data Definition to see data type of the table. Open Data Preview/Open Content to see table contents.
To use tables from one Schema to create views we should provide access on the Schema to the default user who runs all the Views in HANA Modeling. This can be done by going to SQL editor and running this query −
GRANT SELECT ON SCHEMA "<SCHEMA_NAME>" TO _SYS_REPO WITH GRANT OPTION
SAP HANA Packages are shown under Content tab in HANA studio. All HANA modeling is saved inside Packages.
You can create a new Package by Right Click on Content Tab → New → Package
You can also create a Sub Package under a Package by right clicking on the Package name. When we right click on the Package we get 7 Options: We can create HANA Views Attribute Views, Analytical Views, and Calculation Views under a Package.
You can also create Decision Table, Define Analytic Privilege and create Procedures in a Package.
When you right click on Package and click on New, you can also create sub packages in a Package. You have to enter Package Name, Description while creating a Package.
Attribute Views in SAP HANA Modeling are created on the top of Dimension tables. They are used to join Dimension tables or other Attribute Views. You can also copy a new Attribute View from already existing Attribute Views inside other Packages but that doesn’t let you change the View Attributes.
Attribute Views in HANA are used to join Dimension tables or other Attribute Views.
Attribute Views in HANA are used to join Dimension tables or other Attribute Views.
Attribute Views are used in Analytical and Calculation Views for analysis to pass master data.
Attribute Views are used in Analytical and Calculation Views for analysis to pass master data.
They are similar to Characteristics in BM and contain master data.
They are similar to Characteristics in BM and contain master data.
Attribute Views are used for performance optimization in large size Dimension tables, you can limit the number of attributes in an Attribute View which are further used for Reporting and analysis purpose.
Attribute Views are used for performance optimization in large size Dimension tables, you can limit the number of attributes in an Attribute View which are further used for Reporting and analysis purpose.
Attribute Views are used to model master data to give some context.
Attribute Views are used to model master data to give some context.
Choose the Package name under which you want to create an Attribute View. Right Click on Package → Go to New → Attribute View
When you click on Attribute View, New Window will open. Enter Attribute View name and description. From the drop down list, choose View Type and sub type. In sub type, there are three types of Attribute views − Standard, Time, and Derived.
Time subtype Attribute View is a special type of Attribute view that adds a Time Dimension to Data Foundation. When you enter the Attribute name, Type and Subtype and click on Finish, it will open three work panes −
Scenario pane that has Data Foundation and Semantic Layer.
Scenario pane that has Data Foundation and Semantic Layer.
Details Pane shows attribute of all tables added to Data Foundation and joining between them.
Details Pane shows attribute of all tables added to Data Foundation and joining between them.
Output pane where we can add attributes from Detail pane to filter in the report.
Output pane where we can add attributes from Detail pane to filter in the report.
You can add Objects to Data Foundation, by clicking on ‘+’ sign written next to Data Foundation. You can add multiple Dimension tables and Attribute Views in the Scenario Pane and join them using a Primary Key.
When you click on Add Object in Data Foundation, you will get a search bar from where you can add Dimension tables and Attribute views to Scenario Pane. Once Tables or Attribute Views are added to Data Foundation, they can be joined using a Primary Key in Details Pane as shown below.
Once joining is done, choose multiple attributes in details pane, right click and Add to Output. All columns will be added to Output pane. Now Click on Activate option and you will get a confirmation message in job log.
Now you can right click on the Attribute View and go for Data Preview.
Note − When a View is not activated, it has diamond mark on it. However, once you activate it, that diamond disappears that confirms that View has been activated successfully.
Once you click on Data Preview, it will show all the attributes that has been added to Output pane under Available Objects.
These Objects can be added to Labels and Value axis by right click and adding or by dragging the objects as shown below −
Analytic View is in the form of Star schema, wherein we join one Fact table to multiple Dimension tables. Analytic views use real power of SAP HANA to perform complex calculations and aggregate functions by joining tables in form of star schema and by executing Star schema queries.
Following are the properties of SAP HANA Analytic View −
Analytic Views are used to perform complex calculations and Aggregate functions like Sum, Count, Min, Max, Etc.
Analytic Views are used to perform complex calculations and Aggregate functions like Sum, Count, Min, Max, Etc.
Analytic Views are designed to run Start schema queries.
Analytic Views are designed to run Start schema queries.
Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains primary key for each Dim table and measures.
Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains primary key for each Dim table and measures.
Analytic Views are similar to Info Objects and Info sets of SAP BW.
Analytic Views are similar to Info Objects and Info sets of SAP BW.
Choose the Package name under which you want to create an Analytic View. Right Click on Package → Go to New → Analytic View. When you click on an Analytic View, New Window will open. Enter View name and Description and from drop down list choose View Type and Finish.
When you click Finish, you can see an Analytic View with Data Foundation and Star Join option.
Click on Data Foundation to add Dimension and Fact tables. Click on Star Join to add Attribute Views.
Add Dim and Fact tables to Data Foundation using “+” sign. In the example given below, 3 dim tables have been added: DIM_CUSTOMER, DIM_PRODUCT, DIM_REGION and 1 Fact table FCT_SALES to Details Pane. Joining Dim table to Fact table using Primary Keys stored in Fact table.
Select Attributes from Dim and Fact table to add to Output pane as shown in snapshot shown above. Now change the data type of Facts, from fact table to measures.
Click on Semantic layer, choose facts and click on measures sign as shown below to change datatype to measures and Activate the View.
Once you activate view and click on Data Preview, all attributes and measures will be added under the list of Available objects. Add Attributes to Labels Axis and Measure to Value axis for analysis purpose.
There is an option to choose different types of chart and graphs.
Calculation Views are used to consume other Analytic, Attribute and other Calculation views and base column tables. These are used to perform complex calculations, which are not possible with other type of Views.
Below given are few characteristics of Calculation Views −
Calculation Views are used to consume Analytic, Attribute and other Calculation Views.
Calculation Views are used to consume Analytic, Attribute and other Calculation Views.
They are used to perform complex calculations, which are not possible with other Views.
They are used to perform complex calculations, which are not possible with other Views.
There are two ways to create Calculation Views- SQL Editor or Graphical Editor.
There are two ways to create Calculation Views- SQL Editor or Graphical Editor.
Built-in Union, Join, Projection & Aggregation nodes.
Built-in Union, Join, Projection & Aggregation nodes.
Choose the Package name under which you want to create a Calculation View. Right Click on Package → Go to New → Calculation View. When you click on Calculation View, New Window will open.
Enter View name, Description and choose view type as Calculation View, Subtype Standard or Time (this is special kind of View which adds time dimension). You can use two types of Calculation View − Graphical and SQL Script.
It has default nodes like aggregation, Projection, Join and Union. It is used to consume other Attribute, Analytic and other Calculation views.
It is written in SQL scripts that are built on SQL commands or HANA defined functions.
Cube, in this default node, is Aggregation. You can choose Star join with Cube dimension.
Dimension, in this default node is Projection.
It does not allow base column tables, Attribute Views or Analytic views to add at data foundation. All Dimension tables must be changed to Dimension Calculation views to use in Star Join. All Fact tables can be added and can use default nodes in Calculation View.
The following example shows how we can use Calculation View with Star join −
You have four tables, two Dim tables, and two Fact tables. You have to find list of all employees with their Joining date, Emp Name, empId, Salary and Bonus.
Copy and paste the below script in SQL editor and execute.
Dim Tables − Empdim and Empdate
Create column table Empdim (empId nvarchar(3),Empname nvarchar(100));
Insert into Empdim values('AA1','John');
Insert into Empdim values('BB1','Anand');
Insert into Empdim values('CC1','Jason');
Create column table Empdate (caldate date, CALMONTH nvarchar(4) ,CALYEAR nvarchar(4));
Insert into Empdate values('20100101','04','2010');
Insert into Empdate values('20110101','05','2011');
Insert into Empdate values('20120101','06','2012');
Fact Tables − Empfact1, Empfact2
Create column table Empfact1 (empId nvarchar(3), Empdate date, Sal integer );
Insert into Empfact1 values('AA1','20100101',5000);
Insert into Empfact1 values('BB1','20110101',10000);
Insert into Empfact1 values('CC1','20120101',12000);
Create column table Empfact2 (empId nvarchar(3), deptName nvarchar(20), Bonus integer );
Insert into Empfact2 values ('AA1','SAP', 2000);
Insert into Empfact2 values ('BB1','Oracle', 2500);
Insert into Empfact2 values ('CC1','JAVA', 1500);
Now we have to implement Calculation View with Star Join. First change both Dim tables to Dimension Calculation View.
Create a Calculation View with Star Join. In Graphical pane, add 2 Projections for 2 Fact tables. Add both fact tables to both Projections and add attributes of these Projections to Output pane.
Add a join from default node and join both the fact tables. Add parameters of Fact Join to output pane.
In Star Join, add both- Dimension Calculation views and add Fact Join to Star Join as shown below. Choose parameters in Output pane and active the View.
Once view is activated successfully, right click on view name and click on Data Preview. Add attributes and measures to values and labels axis and do the analysis.
It simplifies the design process. You need not to create Analytical views and Attribute Views and directly Fact tables can be used as Projections.
3NF is possible with Star Join.
Create 2 Attribute Views on 2 Dim tables-Add output and activate both the views.
Create 2 Analytical Views on Fact Tables → Add both Attribute views and Fact1/Fact2 at Data Foundation in Analytic view.
Now Create a Calculation View → Dimension (Projection). Create Projections of both Analytical Views and Join them. Add attributes of this Join to output pane. Now Join to Projection and add output again.
Activate the view successful and go to Data preview for analysis.
Analytic Privileges are used to limit access on HANA Information views. You can assign different types of right to different users on different component of a View in Analytic Privileges.
Sometimes, it is required that data in the same view should not be accessible to other users who do not have any relevant requirement for that data.
Suppose you have an Analytic view EmpDetails that has details about employees of a company- Emp name, Emp Id, Dept, Salary, Date of Joining, Emp logon, etc. Now if you do not want your Report developer to see Salary details or Emp logon details of all employees, you can hide this by using Analytic privileges option.
Analytic Privileges are only applied to attributes in an Information View. We cannot add measures to restrict access in Analytic privileges.
Analytic Privileges are only applied to attributes in an Information View. We cannot add measures to restrict access in Analytic privileges.
Analytic Privileges are used to control read access on SAP HANA Information views.
Analytic Privileges are used to control read access on SAP HANA Information views.
So we can restrict data by Empname, EmpId, Emp logon or by Emp Dept and not by numerical values like salary, bonus.
Right Click on Package name and go to new Analytic Privilege or you can open using HANA Modeler quick launch.
Enter name and Description of Analytic Privilege → Finish. New window will open.
You can click on Next button and add Modeling view in this window before you click on finish. There is also an option to copy an existing Analytic Privilege package.
Once you click on Add button, it will show you all the views under Content tab.
Choose View that you want to add to Analytic Privilege package and click OK. Selected View will be added under reference models.
Now to add attributes from selected view under Analytic Privilege, click on add button with Associated Attributes Restrictions window.
Add objects you want to add to Analytic privileges from select object option and click on OK.
In Assign Restriction option, it allows you to add values you want to hide in Modeling View from specific user. You can add Object value that will not reflect in Data Preview of Modeling View.
We have to activate Analytic Privilege now, by clicking on Green round icon at top. Status message – completed successfully confirms activation successfully under job log and we can use this view now by adding to a role.
Now to add this role to a user, go to security tab → User → Select User on which you want to apply these Analytic privileges.
Search Analytic Privilege you want to apply with the name and click on OK. That view will be added to user role under Analytic Privileges.
To delete Analytic Privileges from specific user, select view under tab and use Red delete option. Use Deploy (arrow mark at top or F8 to apply this to user profile).
SAP HANA Information Composer is a self-service modeling environment for end users to analyze data set. It allows you to import data from workbook format (.xls, .csv) into HANA database and to create Modeling views for analysis.
Information Composer is very different from HANA Modeler and both are designed to target separate set of users. Technically sound people who have strong experience in data modeling use HANA Modeler. A business user, who does not have any technical knowledge, uses Information Composer. It provides simple functionalities with easy to use interface.
Data extraction − Information Composer helps to extract data, clean data, preview data and automate the process of creation of physical table in the HANA database.
Data extraction − Information Composer helps to extract data, clean data, preview data and automate the process of creation of physical table in the HANA database.
Manipulating data − It helps us to combine two objects (Physical tables, Analytical View, attribute view and calculation views) and create information view that can be consumed by SAP BO Tools like SAP Business Objects Analysis, SAP Business Objects Explorer and other tools like MS Excel.
Manipulating data − It helps us to combine two objects (Physical tables, Analytical View, attribute view and calculation views) and create information view that can be consumed by SAP BO Tools like SAP Business Objects Analysis, SAP Business Objects Explorer and other tools like MS Excel.
It provides a centralized IT service in the form of URL, which can be accessed from anywhere.
It provides a centralized IT service in the form of URL, which can be accessed from anywhere.
It allows us to upload large amount of data (up to 5 million cells). Link to access Information Composer −
http://<server>:<port>/IC
Login to SAP HANA Information Composer. You can perform data loading or manipulation using this tool.
To upload data this can be done in two ways −
Uploading .xls, .csv file directly to HANA database
Other way is to copy data to clipboard and copy from there to HANA database.
It allows data to be loaded along with header.
On Left side in Information Composer, you have three options −
Select Source of data → Classify data → Publish
Once data is published to HANA database, you cannot rename the table. In this case, you have to delete the table from Schema in HANA database.
“SAP_IC” schema, where tables like IC_MODELS, IC_SPREADSHEETS exists. One can find details of tables created using IC under these tables.
Another way to upload data in IC is by use of the clipboard. Copy the data to clipboard and upload it with help of Information Composer. Information Composer also allows you to see preview of data or even provide summary of data in temporary storage. It has inbuilt capability of data cleansing that is used to remove any inconsistency in data.
Once data is cleansed, you need to classify data whether it is attributed. IC has inbuilt feature to check the data type of uploaded data.
Final step is to publish the data to physical tables in HANA database. Provide a technical name and description of table and this will be loaded inside IC_Tables Schema.
Two set of users can be defined to use data published from IC.
IC_MODELER is for creating physical tables, uploading data and creating information views.
IC_MODELER is for creating physical tables, uploading data and creating information views.
IC_PUBLIC allows users to view information views created by other users. This role does not allow the user to upload or create any information views using IC.
IC_PUBLIC allows users to view information views created by other users. This role does not allow the user to upload or create any information views using IC.
Server Requirements −
At least 2GB of available RAM is required.
At least 2GB of available RAM is required.
Java 6 (64-bit) must be installed on the server.
Java 6 (64-bit) must be installed on the server.
The Information Composer Server must be physically located next to the HANA server.
The Information Composer Server must be physically located next to the HANA server.
Client Requirements −
Internet Explorer with Silverlight 4 installed.
HANA Export and Import option allows tables, Information models, Landscapes to move to a different or existing system. You do not need to recreate all tables and information models as you can simply export it to new system or import to an existing target system to reduce the effort.
This option can be accessed from File menu at the top or by right clicking on any table or Information model in HANA studio.
Go to file menu → Export → You will see options as shown below −
Delivery unit is a single unit, which can be mapped to multiple packages and can be exported as single entity so that all the packages assigned to Delivery Unit can be treated as single unit.
Users can use this option to export all the packages that make a delivery unit and the relevant objects contained in it to a HANA Server or to local Client location.
The user should create Delivery Unit prior to using it.
This can be done through HANA Modeler → Delivery Unit → Select System and Next → Create → Fill the details like Name, Version, etc. → OK → Add Packages to Delivery unit → Finish
Once the Delivery Unit is created and the packages are assigned to it, user can see the list of packages by using Export option −
Go to File → Export → Delivery Unit →Select the Delivery Unit.
You can see list of all packages assigned to Delivery unit. It gives an option to choose export location −
Export to Server
Export to Client
You can export the Delivery Unit either to HANA Server location or to a Client location as shown.
The user can restrict the export through “Filter by time” which means Information views, which are updated within the mentioned time interval will only be exported.
Select the Delivery Unit and Export Location and then Click Next → Finish. This will export the selected Delivery Unit to the specified location.
This option can be used to export individual objects to a location in the local system. User can select single Information view or group of Views and Packages and select the local Client location for export and Finish.
This is shown in the snapshot below.
This can be used to export the objects along with the data for SAP support purposes. This can be used when requested.
Example − User creates an Information View, which throws an error and he is not able to resolve. In that case, he can use this option to export the view along with data and share it with SAP for debugging purpose.
Export Options under SAP HANA Studio −
Landscape − To export the landscape from one system to other.
Tables − This option can be used to export tables along with its content.
Go to File → Import, You will see all the options as shown below under Import.
This is used to import data from a flat file like .xls or .csv file.
Click on Nex → Choose Target System → Define Import Properties
Select Source file by browsing local system. It also gives an option if you want to keep the header row. It also gives an option to create a new table under existing Schema or if you want to import data from a file to an existing table.
When you click on Next, it gives an option to define Primary Key, change data type of columns, define storage type of table and also, allows you to change the proposed structure of table.
When you click on finish, that table will be populated under list of tables in mentioned Schema. You can do the data preview and can check data definition of the table and it will be same as that of .xls file.
Select Delivery unit by going to File → Import → Delivery unit. You can choose from a server or local client.
You can select “Overwrite inactive versions” which allows you to overwrite any inactive version of objects that exist. If the user selects “Activate objects”, then after the import, all the imported objects will be activated by default. The user need not trigger the activation manually for the imported views.
Click Finish and once completed successfully, it will be populated to target system.
Browse for the Local Client location where the views are exported and select the views to be imported, the user can select individual Views or group of Views and Packages and Click on Finish.
Go to File → Import → Mass Import of Metadata → Next and select the source and target system.
Configure the System for Mass Import and click Finish.
It allows you to choose tables and target schema to import Meta data from SAP Applications.
Go to File → Import → Selective Import of Metadata → Next
Choose Source Connection of type “SAP Applications”. Remember that the Data Store should have been created already of type SAP Applications → Click Next
Select tables you want to import and validate data if required. Click Finish after that.
We know that with the use of Information Modeling feature in SAP HANA, we can create different Information views Attribute Views, Analytic Views, Calculation views. These Views can be consumed by different reporting tools like SAP Business Object, SAP Lumira, Design Studio, Office Analysis and even third party tool like MS Excel.
These reporting tools enable Business Managers, Analysts, Sales Managers and senior management employees to analyze the historic information to create business scenarios and to decide business strategy of the company.
This generates the need for consuming HANA Modeling views by different reporting tools and to generate reports and dashboards, which are easy to understand for end users.
In most of the companies, where SAP is implemented, reporting on HANA is done with BI platforms tools that consume both SQL and MDX queries with help of Relational and OLAP connections. There is wide variety of BI tools like − Web Intelligence, Crystal Reports, Dashboard, Explorer, Office Analysis and many more.
Web Intelligence and Crystal Reports are most common BI tools that are used for reporting. WebI uses a semantic layer called Universe to connect to data source and these Universes are used for reporting in tool. These Universes are designed with the help of Universe design tool UDT or with Information Design tool IDT. IDT supports multisource enabled data source. However, UDT only supports Single source.
Main tools that are used for designing interactive dashboards- Design Studio and Dashboard Designer. Design Studio is future tool for designing dashboard, which consumes HANA views via BI consumer Service BICS connection. Dashboard design (xcelsius) uses IDT to consume schemas in HANA database with a Relational or OLAP connection.
SAP Lumira has an inbuilt feature of directly connecting or loading data from HANA database. HANA views can be directly consumed in Lumira for visualization and creating stories.
Office Analysis uses an OLAP connection to connect to HANA Information views. This OLAP connection can be created in CMC or IDT.
In the picture given above, it shows all BI tools with solid lines, which can be directly connected and integrated with SAP HANA using an OLAP connection. It also depicts tools, which need a relational connection using IDT to connect to HANA are shown with dotted lines.
The idea is basically if you need to access data from a table or a conventional database then your connection should be a relational connection but if your source is an application and data is stored in cube (multidimensional like Info cubes, Information models) then you would use an OLAP connection.
A Relational connection can only be created in IDT/UDT.
An OLAP can be created in both IDT and CMC.
Another thing to note is that a relational connection always produces a SQL statement to be fired from report while an OLAP connection normally creates a MDX statement
In Information design tool (IDT), you can create a relational connection to an SAP HANA view or table using JDBC or ODBC drivers and build a Universe using this connection to provide access to client tools like Dashboards and Web Intelligence as shown in above picture.
You can create a direct connection to SAP HANA using JDBC or ODBC drivers.
In Crystal Reports for Enterprise, you can access SAP HANA data by using an existing relational connection created using the information design tool.
You can also connect to SAP HANA using an OLAP connection created using information design tool or CMC.
Design Studio can access SAP HANA data by using an existing OLAP connection created in Information design tool or CMC same like Office Analysis.
Dashboards can connect to SAP HANA only through a relational Universe. Customers using Dashboards on top of SAP HANA should strongly consider building their new dashboards with Design Studio.
Web Intelligence can connect to SAP HANA only through a Relational Universe.
Lumira can connect directly to SAP HANA Analytic and Calculation views. It can also connect to SAP HANA through SAP BI Platform using a relational Universe.
In Office Analysis edition for OLAP, you can connect to SAP HANA using an OLAP connection defined in the Central Management Console or in Information design tool.
You can create an information space based on an SAP HANA view using JDBC drivers.
We can create an OLAP Connection for all the BI tools, which we want to use on top of HANA views like OLAP for analysis, Crystal Report for enterprise, Design Studio. Relational connection through IDT is used to connect Web Intelligence and Dashboards to HANA database.
These connection can be created using IDT as well CMC and both of the connections are saved in BO Repository.
Login to CMC with the user name and password.
From the dropdown list of connections, choose an OLAP connection. It will also show already created connections in CMC. To create a new connection, go to green icon and click on this.
Enter the name of an OLAP connection and description. Multiple persons, to connect to HANA views, in different BI Platform tools, can use this connection.
Provider − SAP HANA
Server − Enter HANA Server name
Instance − Instance number
It also gives an option to connect to a single Cube (You can also choose to connect to single Analytic or Calculation view) or to the full HANA system.
Click on Connect and choose modeling view by entering user name and password.
Authentication Types − Three types of Authentication are possible while creating an OLAP connection in CMC.
Predefined − It will not ask user name and password again while using this connection.
Predefined − It will not ask user name and password again while using this connection.
Prompt − Every time it will ask user name and password
Prompt − Every time it will ask user name and password
SSO − User specific
SSO − User specific
Enter user − user name and password for HANA system and save and new connection will be added to existing list of connections.
Enter user − user name and password for HANA system and save and new connection will be added to existing list of connections.
Now open BI Launchpad to open all BI platform tools for reporting like Office Analysis for OLAP and it will ask to choose a connection. By default, it will show you the Information View if you have specified it while creating this connection otherwise click on Next and go to folders → Choose Views (Analytic or Calculation Views).
SAP Lumira connectivity with HANA system
Open SAP Lumira from Start Program, Click on file menu → New → Add new dataset → Connect to SAP HANA → Next
Difference between connect to SAP HANA and download from SAP HANA is that it will download data from Hana system to BO repository and refreshing of data will not occur with changes in HANA system. Enter HANA server name and Instance number. Enter user name and password → click on Connect.
It will show all views. You can search with the view name → Choose View → Next. It will show all measures and dimensions. You can choose from these attributes if you want → click on create option.
There are four tabs inside SAP Lumira −
Prepare − You can see the data and do any custom calculation.
Prepare − You can see the data and do any custom calculation.
Visualize − You can add Graphs and Charts. Click on X axis and Y axis + sign to add attributes.
Visualize − You can add Graphs and Charts. Click on X axis and Y axis + sign to add attributes.
Compose − This option can be used to create sequence of Visualization (story) → click on Board to add numbers of boards → create → it will show all the visualizations on left side. Drag first Visualization then add page then add second visualization.
Compose − This option can be used to create sequence of Visualization (story) → click on Board to add numbers of boards → create → it will show all the visualizations on left side. Drag first Visualization then add page then add second visualization.
Share − If it is built on SAP HANA, we can only publish to SAP Lumira server. Otherwise you can also publish story from SAP Lumira to SAP Community Network SCN or BI Platform.
Share − If it is built on SAP HANA, we can only publish to SAP Lumira server. Otherwise you can also publish story from SAP Lumira to SAP Community Network SCN or BI Platform.
Save the file to use it later → Go to File-Save → choose Local → Save
Creating a Relational Connection in IDT to use with HANA views in WebI and Dashboard −
Open Information Design Tool → by going to BI Platform Client tools. Click on New → Project Enter Project Name → Finish.
Right-click on Project name → Go to New → Choose Relational Connection → Enter Connection/resource name → Next → choose SAP from list to connect to HANA system → SAP HANA → Select JDBC/ODBC drivers → click on Next → Enter HANA system details → Click on Next and Finish.
You can also test this connection by clicking on Test Connection option.
Test Connection → Successful. Next step is to publish this connection to Repository to make it available for use.
Right Click on connection name → click on Publish connection to Repository → Enter BO Repository name and password → Click on Connect → Next →Finish → Yes.
It will create a new relational connection with .cns extension.
.cns − connection type represents secured Repository connection that should be used to create Data foundation.
.cnx − represents local unsecured connection. If you use this connection while creating and publishing a Universe, it will not allow you to publish that to repository.
Choose .cns connection type → Right Click on this → click on New Data foundation → Enter Name of Data foundation → Next → Single source/multi source → click on Next → Finish.
It will show all the tables in HANA database with Schema name in the middle pane.
Import all tables from HANA database to master pane to create a Universe. Join Dim and Fact tables with primary keys in Dim tables to create a Schema.
Double Click on the Joins and detect Cardinality → Detect → OK → Save All at the top. Now we have to create a new Business layer on the data foundation that will be consumed by BI Application tools.
Right Click on .dfx and choose new Business Layer → Enter Name → Finish →. It will show all the objects automatically, under master pane →. Change Dimension to Measures (Type-Measure change Projection as required) → Save All.
Right-click on .bfx file → click on Publish → To Repository → click on Next → Finish → Universe Published Successfully.
Now open WebI Report from BI Launchpad or Webi rich client from BI Platform client tools → New → select Universe → TEST_SAP_HANA → OK.
All Objects will be added to Query Panel. You can choose attributes and measures from left pane and add them to Result Objects. The Run query will run the SQL query and the output will be generated in the form of Report in WebI as shown below.
Microsoft Excel is considered the most common BI reporting and analysis tool by many organizations. Business Managers and Analysts can connect it to HANA database to draw Pivot tables and charts for analysis.
Open Excel and go to Data tab → from other sources → click on Data connection wizard → Other/ Advanced and click on Next → Data link properties will open.
Choose SAP HANA MDX Provider from this list to connect to any MDX data source → Enter HANA system details (server name, instance, user name and password) → click on Test Connection → Connection succeeded → OK.
It will give you the list of all packages in drop down list that are available in HANA system. You can choose an Information view → click Next → Select Pivot table/others → OK.
All attributes from Information view will be added to MS Excel. You can choose different attributes and measures to report as shown and you can choose different charts like pie charts and bar charts from design option at the top.
Security means protecting company’s critical data from unauthorized access and use, and to ensure that Compliance and standards are met as per the company policy. SAP HANA enables customer to implement different security policies and procedures and to meet compliance requirements of the company.
SAP HANA supports multiple databases in a single HANA system and this is known as multitenant database containers. HANA system can also contain more than one multitenant database containers. A multiple container system always has exactly one system database and any number of multitenant database containers. AN SAP HANA system that is installed in this environment is identified by a single system ID (SID). Database containers in HANA system are identified by a SID and database name. SAP HANA client, known as HANA studio, connects to specific databases.
SAP HANA provides all security related features such as Authentication, Authorization, Encryption and Auditing, and some add on features, which are not supported in other multitenant databases.
Below given is a list of security related features, provided by SAP HANA −
User and Role Management
Authentication and SSO
Authorization
Encryption of data communication in Network
Encryption of data in Persistence Layer
Additional Features in multitenant HANA database −
Database Isolation − It involves preventing cross tenant attacks through operating system mechanism
Database Isolation − It involves preventing cross tenant attacks through operating system mechanism
Configuration Change blacklist − It involves preventing certain system properties from being changed by tenant database administrators
Configuration Change blacklist − It involves preventing certain system properties from being changed by tenant database administrators
Restricted Features − It involves disabling certain database features that provides direct access to file system, the network or other resources.
Restricted Features − It involves disabling certain database features that provides direct access to file system, the network or other resources.
SAP HANA user and role management configuration depends on the architecture of your HANA system.
If SAP HANA is integrated with BI platform tools and acts as reporting database, then the end-user and role are managed in application server.
If SAP HANA is integrated with BI platform tools and acts as reporting database, then the end-user and role are managed in application server.
If the end-user directly connects to the SAP HANA database, then user and role in database layer of HANA system is required for both end users and administrators.
If the end-user directly connects to the SAP HANA database, then user and role in database layer of HANA system is required for both end users and administrators.
Every user wants to work with HANA database must have a database user with necessary privileges. User accessing HANA system can either be a technical user or an end user depending on the access requirement. After successful logon to system, user’s authorization to perform the required operation is verified. Executing that operation depends on privileges that user has been granted. These privileges can be granted using roles in HANA Security. HANA Studio is one of powerful tool to manage user and roles for HANA database system.
User types vary according to security policies and different privileges assigned on user profile. User type can be a technical database user or end user needs access on HANA system for reporting purpose or for data manipulation.
Standard users are users who can create objects in their own Schemas and have read access in system Information models. Read access is provided by PUBLIC role which is assigned to every standard users.
Restricted users are those users who access HANA system with some applications and they do not have SQL privileges on HANA system. When these users are created, they do not have any access initially.
If we compare restricted users with Standard users −
Restricted users cannot create objects in HANA database or their own Schemas.
Restricted users cannot create objects in HANA database or their own Schemas.
They do not have access to view any data in database as they don’t have generic Public role added to profile like standard users.
They do not have access to view any data in database as they don’t have generic Public role added to profile like standard users.
They can connect to HANA database only using HTTP/HTTPS.
They can connect to HANA database only using HTTP/HTTPS.
Technical database users are used only for administrative purpose such as creating new objects in database, assigning privileges to other users, on packages, applications etc.
Depending on business needs and configuration of HANA system, there are different user activities that can be performed using user administration tool like HANA studio.
Most common activities include −
Create Users
Grant roles to users
Define and Create Roles
Deleting Users
Resetting user passwords
Reactivating users after too many failed logon attempts
Deactivating users when it is required
Only database users with the system privilege ROLE ADMIN are allowed to create users and roles in HANA studio. To create users and roles in HANA studio, go to HANA Administrator Console. You will see security tab in System view −
When you expand security tab, it gives option of User and Roles. To create a new user right click on User and go to New User. New window will open where you define User and User parameters.
Enter User name (mandate) and in Authentication field enter password. Password is applied, while saving password for a new user. You can also choose to create a restricted user.
The specified role name must not be identical to the name of an existing user or role. The password rules include a minimal password length and a definition of which character types (lower, upper, digit, special characters) have to be part of the password.
Different Authorization methods can be configured like SAML, X509 certificates, SAP Logon ticket, etc. Users in the database can be authenticated by varying mechanisms −
Internal authentication mechanism using a password.
External mechanisms such as Kerberos, SAML, SAP Logon Ticket, SAP Assertion Ticket or X.509.
A user can be authenticated by more than one mechanism at a time. However, only one password and one principal name for Kerberos can be valid at any one time. One authentication mechanism has to be specified to allow the user to connect and work with the database instance.
It also gives an option to define validity of user, you can mention validity interval by selecting the dates. Validity specification is an optional user parameter.
Some users that are, by default, delivered with the SAP HANA database are − SYS, SYSTEM, _SYS_REPO, _SYS_STATISTICS.
Once this is done, the next step is to define privileges for user profile. There are different types of privileges that can be added to a user profile.
This is used to add inbuilt SAP.HANA roles to user profile or to add custom roles created under Roles tab. Custom roles allow you to define roles as per access requirement and you can add these roles directly to user profile. This removes need to remember and add objects to a user profile every time for different access types.
PUBLIC − This is Generic role and is assigned to all database users by default. This role contains read only access to system views and execute privileges for some procedures. These roles cannot be revoked.
It contains all privileges required for using the information modeler in the SAP HANA studio.
There are different types of System privileges that can be added to a user profile. To add a system privileges to a user profile, click on + sign.
System privileges are used for Backup/Restore, User Administration, Instance start and stop, etc.
It contains the similar privileges as that in MODELING role, but with the addition that this role is allowed to grant these privileges to other users. It also contains the repository privileges to work with imported objects.
This is a type of privilege, required for adding Data from objects to user profile.
Given below are common supported System Privileges −
It authorizes the debugging of a procedure call, called by a different user. Additionally, the DEBUG privilege for the corresponding procedure is needed.
Controls the execution of the following auditing-related commands − CREATE AUDIT POLICY, DROP AUDIT POLICY and ALTER AUDIT POLICY and the changes of the auditing configuration. Also allows access to AUDIT_LOG system view.
It authorizes the execution of the following command − ALTER SYSTEM CLEAR AUDIT LOG. Also allows access to AUDIT_LOG system view.
It authorizes BACKUP and RECOVERY commands for defining and initiating backup and recovery procedures.
It authorizes the BACKUP command to initiate a backup process.
It authorizes users to have unfiltered read-only access to all system views. Normally, the content of these views is filtered based on the privileges of the accessing user.
It authorizes the creation of database schemas using the CREATE SCHEMA command. By default, each user owns one schema, with this privilege the user is allowed to create additional schemas.
It authorizes the creation of Structured Privileges (Analytical Privileges). Only the owner of an Analytical Privilege can further grant or revoke that privilege to other users or roles.
It authorizes the credential commands − CREATE/ALTER/DROP CREDENTIAL.
It authorizes reading all data in the system views. It also enables execution of any Data Definition Language (DDL) commands in the SAP HANA database
A user having this privilege cannot select or change data stored tables for which they do not have access privileges, but they can drop tables or modify table definitions.
It authorizes all commands related to databases in a multi-database, such as CREATE, DROP, ALTER, RENAME, BACKUP, RECOVERY.
It authorizes export activity in the database via the EXPORT TABLE command.
Note that beside this privilege the user requires the SELECT privilege on the source tables to be exported.
It authorizes the import activity in the database using the IMPORT commands.
Note that beside this privilege the user requires the INSERT privilege on the target tables to be imported.
It authorizes changing of system settings.
It authorizes the SET SYSTEM LICENSE command install a new license.
It authorizes the ALTER SYSTEM LOGGING [ON|OFF] commands to enable or disable the log flush mechanism.
It authorizes the ALTER SYSTEM commands for EVENTs.
It authorizes the ALTER SYSTEM commands concerning SQL PLAN CACHE and ALTER SYSTEM UPDATE STATISTICS commands, which influence the behavior of the query optimizer.
This privilege authorizes commands concerning system resources. For example, ALTER SYSTEM RECLAIM DATAVOLUME and ALTER SYSTEM RESET MONITORING VIEW. It also authorizes many of the commands available in the Management Console.
This privilege authorizes the creation and deletion of roles using the CREATE ROLE and DROP ROLE commands. It also authorizes the granting and revocation of roles using the GRANT and REVOKE commands.
Activated roles, meaning roles whose creator is the pre-defined user _SYS_REPO, can neither be granted to other roles or users nor dropped directly. Not even users having ROLE ADMIN privilege are able to do so. Please check documentation concerning activated objects.
It authorizes the execution of a savepoint process using the ALTER SYSTEM SAVEPOINT command.
Components of the SAP HANA database can create new system privileges. These privileges use the component-name as first identifier of the system privilege and the component-privilege-name as the second identifier.
Object privileges are also known as SQL privileges. These privileges are used to allow access on objects like Select, Insert, Update and Delete of tables, Views or Schemas.
Given below are possible types of Object Privileges −
Object privilege on database objects that exist only in runtime
Object privilege on database objects that exist only in runtime
Object privilege on activated objects created in the repository, like calculation views
Object privilege on activated objects created in the repository, like calculation views
Object privilege on schema containing activated objects created in the repository,
Object privilege on schema containing activated objects created in the repository,
Object/SQL Privileges are collection of all DDL and DML privileges on database objects.
Object/SQL Privileges are collection of all DDL and DML privileges on database objects.
Given below are common supported Object Privileges −
There are multiple database objects in HANA database, so not all the privileges are applicable to all kinds of database objects.
Object Privileges and their applicability on database objects −
Sometimes, it is required that data in the same view should not be accessible to other users who does not have any relevant requirement for that data.
Analytic privileges are used to limit the access on HANA Information Views at object level. We can apply row and column level security in Analytic Privileges.
Analytic Privileges are used for −
Allocation of row and column level security for specific value range.
Allocation of row and column level security for modeling views.
In the SAP HANA repository, you can set package authorizations for a specific user or for a role. Package privileges are used to allow access to data models- Analytic or Calculation views or on to Repository objects. All privileges that are assigned to a repository package are assigned to all sub packages too. You can also mention if assigned user authorizations can be passed to other users.
Steps to add a package privileges to User profile −
Click on Package privilege tab in HANA studio under User creation → Choose + to add one or more packages. Use Ctrl key to select multiple packages.
Click on Package privilege tab in HANA studio under User creation → Choose + to add one or more packages. Use Ctrl key to select multiple packages.
In the Select Repository Package dialog, use all or part of the package name to locate the repository package that you want to authorize access to.
In the Select Repository Package dialog, use all or part of the package name to locate the repository package that you want to authorize access to.
Select one or more repository packages that you want to authorize access to, the selected packages appear in the Package Privileges tab.
Select one or more repository packages that you want to authorize access to, the selected packages appear in the Package Privileges tab.
Given below are grant privileges, which are used on repository packages to authorize user to modify the objects −
REPO.READ − Read access to the selected package and design-time objects (both native and imported)
REPO.READ − Read access to the selected package and design-time objects (both native and imported)
REPO.EDIT_NATIVE_OBJECTS − Authorization to modify objects in packages.
REPO.EDIT_NATIVE_OBJECTS − Authorization to modify objects in packages.
Grantable to Others − If you choose ‘Yes’ for this, this allows assigned user authorization to pass to the other users.
Grantable to Others − If you choose ‘Yes’ for this, this allows assigned user authorization to pass to the other users.
Application privileges in a user profile are used to define authorization for access to HANA XS application. This can be assigned to an individual user or to the group of users. Application privileges can also be used to provide different level of access to the same application like to provide advanced functions for database Administrators and read-only access to normal users.
To define Application specific privileges in a user profile or to add group of users, below privileges should be used −
Application-privileges file (.xsprivileges)
Application-access file (.xsaccess)
Role-definition file (<RoleName>.hdbrole)
All SAP HANA users that have access on HANA database are verified with different Authentications method. SAP HANA system supports various types of authentication method and all these login methods are configured at time of profile creation.
Below is the list of authentication methods supported by SAP HANA −
User name/Password
Kerberos
SAML 2.0
SAP Logon tickets
X.509
This method requires a HANA user to enter user name and password to login to database. This user profile is created under User management in HANA Studio → Security Tab.
Password should be as per password policy i.e. Password length, complexity, lower and upper case letters, etc.
You can change the password policy as per your organization’s security standards. Please note that password policy cannot be deactivated.
All users who connect to HANA database system using an external authentication method should also have a database user. It is required to map external login to internal database user.
This method enables users to authenticate HANA system directly using JDBC/ODBC drivers through network or by using front end applications in SAP Business Objects.
It also allows HTTP access in HANA Extended Service using HANA XS engine. It uses SPENGO mechanism for Kerberos authentication.
SAML stands for Security Assertion Markup Language and can be used to authenticate users accessing HANA system directly from ODBC/JDBC clients. It can also be used to authenticate users in HANA system coming via HTTP through HANA XS engine.
SAML is used only for authentication purpose and not for authorization.
SAP Logon/assertion tickets can be used to authenticate users in HANA system. These tickets are issued to users when they login into SAP system, which is configured to issue such tickets like SAP Portal, etc. User specified in SAP logon tickets should be created in HANA system, as it does not provide support for mapping users.
X.509 certificates can also be used to login to HANA system via HTTP access request from HANA XS engine. Users are authenticated by certificated that are signed from trusted Certificate Authority, which is stored in HANA XS system.
User in trusted certificate should exist in HANA system as there is no support for user mapping.
Single sign on can be configured in HANA system, which allows users to login to HANA system from an initial authentication on the client. User logins at client applications using different authentication methods and SSO allows user to access HANA system directly.
SSO can be configured on below configuration methods −
SAML
Kerberos
X.509 client certificates for HTTP access from HANA XS engine
SAP Logon/Assertion tickets
Authorization is checked when a user tries to connect to HANA database and perform some database operations. When a user connects to HANA database using client tools via JDBC/ODBC or Via HTTP to perform some operations on database objects, corresponding action is determined by the access that is granted to the user.
Privileges granted to a user are determined by Object privileges assigned on user profile or role that has been granted to user. Authorization is a combination of both accesses. When a user tries to perform some operation on HANA database, system performs an authorization check. When all required privileges are found, system stops this check and grants the requested access.
There are different types of privileges, which are used in SAP HANA as mentioned under User role and Management −
They are applicable to system and database authorization for users and control system activities. They are used for administrative tasks such as creating Schemas, data backups, creating users and roles and so on. System privileges are also used to perform Repository operations.
They are applicable to database operations and apply to database objects like tables, Schemas, etc. They are used to manage database objects such as tables and views. Different actions like Select, Execute, Alter, Drop, Delete can be defined based on database objects.
They are also used to control remote data objects, which are connected through SMART data access to SAP HANA.
They are applicable to data inside all the packages that are created in HANA repository. They are used to control modeling views that are created inside packages like Attribute View, Analytic View, and Calculation View. They apply row and column level security to attributes that are defined in modeling views in HANA packages.
They are applicable to allow access to and ability to use packages that are created in repository of HANA database. Package contains different Modeling views like Attribute, Analytic and Calculation views and also Analytic Privileges defined in HANA repository database.
They are applicable to HANA XS application that access HANA database via HTTP request. They are used to control access on applications created with HANA XS engine.
Application Privileges can be applied to users/roles directly using HANA studio but it is preferred that they should be applied to roles created in repository at design time.
_SYS_REPO is the user owns all the objects in HANA repository. This user should be authorized externally for the objects on which repository objects are modeled in HANA system. _SYS_REPO is owner of all objects so it can only be used to grant access on these objects, no other user can login as _SYS_REPO user.
GRANT SELECT ON SCHEMA "<SCHEMA_NAME>" TO _SYS_REPO WITH GRANT OPTION
SAP HANA License management and keys are required to use HANA database. You can install or delete HANA License keys using HANA studio.
SAP HANA system supports two types of License keys −
Temporary License Key − Temporary License keys are automatically installed when you install the HANA database. These keys are valid only for 90 days and you should request permanent license keys from SAP market place before expiry of this 90 days period after installation.
Temporary License Key − Temporary License keys are automatically installed when you install the HANA database. These keys are valid only for 90 days and you should request permanent license keys from SAP market place before expiry of this 90 days period after installation.
Permanent License Key − Permanent License keys are valid only till the predefine expiration date. License keys specify amount of memory licensed to target HANA installation. They can installed from SAP Market place under Keys and Requests tab. When a permanent License key is expired, a temporary license key is issued, which is valid for only 28 days. During this period, you have to install a permanent License key again.
Permanent License Key − Permanent License keys are valid only till the predefine expiration date. License keys specify amount of memory licensed to target HANA installation. They can installed from SAP Market place under Keys and Requests tab. When a permanent License key is expired, a temporary license key is issued, which is valid for only 28 days. During this period, you have to install a permanent License key again.
There are two types of permanent License keys for HANA system −
Unenforced − If unenforced license key is installed and consumption of HANA system exceeds the license amount of memory, operation of SAP HANA is not affected in this case.
Unenforced − If unenforced license key is installed and consumption of HANA system exceeds the license amount of memory, operation of SAP HANA is not affected in this case.
Enforced − If Enforced license key is installed and consumption of HANA system exceeds the license amount of memory, HANA system gets locked. If this situation occurs, HANA system has to be restarted or a new license key should be requested and installed.
Enforced − If Enforced license key is installed and consumption of HANA system exceeds the license amount of memory, HANA system gets locked. If this situation occurs, HANA system has to be restarted or a new license key should be requested and installed.
There is different License scenarios that can be used in HANA system depending on the landscape of the system (Standalone, HANA Cloud, BW on HANA, etc.) and not all of these models are based on memory of HANA system installation.
Right Click on HANA system → Properties → License
It tells about License type, Start Date and Expiration Date, Memory Allocation and the information (Hardware Key, System Id) that is required to request a new license through SAP Market Place.
Install License key → Browse → Enter Path, is used to install a new License key and delete option is used to delete any old expiration key.
All Licenses tab under License tells about Product name, description, Hardware key, First installation time, etc.
SAP HANA audit policy tells the actions to be audited and also the condition under which the action must be performed to be relevant for auditing. Audit Policy defines what activities have been performed in HANA system and who has performed those activities at what time.
SAP HANA database auditing feature allows monitoring action performed in HANA system. SAP HANA audit policy must be activated on HANA system to use it. When an action is performed, the policy triggers an audit event to write to audit trail. You can also delete audit entries in Audit trail.
In a distributed environment, where you have multiple database, Audit policy can be enabled on each individual system. For the system database, audit policy is defined in nameserver.ini file and for tenant database, it is defined in global.ini file.
To define Audit policy in HANA system, you should have system privilege − Audit Admin.
Go to Security option in HANA system → Auditing
Under Global Settings → set Auditing status as enabled.
You can also choose Audit trail targets. The following audit trail targets are possible −
Syslog (default) − Logging system of Linux Operating System.
Syslog (default) − Logging system of Linux Operating System.
Database Table − Internal database table, user who has Audit admin or Audit operator system privilege he can only run select operation on this table.
Database Table − Internal database table, user who has Audit admin or Audit operator system privilege he can only run select operation on this table.
CSV text − This type of audit trail is only used for test purpose in a non-production environment.
CSV text − This type of audit trail is only used for test purpose in a non-production environment.
You can also create a new Audit policy in the Audit Policies area → choose Create New Policy. Enter Policy name and actions to be audited.
Save the new policy using the Deploy button. A new policy is enabled automatically, when an action condition is met, an audit entry is created in Audit trail table. You can disable a policy by changing status to disable or you can also delete the policy.
SAP HANA Replication allows migration of data from source systems to SAP HANA database. Simple way to move data from existing SAP system to HANA is by using various data replication techniques.
System replication can be set up on the console via command line or by using HANA studio. The primary ECC or transaction systems can stay online during this process. We have three types of data replication methods in HANA system −
SAP LT Replication method
ETL tool SAP Business Object Data Service (BODS) method
Direct Extractor connection method (DXC)
SAP Landscape Transformation Replication is a trigger based data replication method in HANA system. It is a perfect solution for replicating real time data or schedule based replication from SAP and non-SAP sources. It has SAP LT Replication server, which takes care of all trigger requests. Replication server can be installed as standalone server or can run on any SAP system with SAP NW 7.02 or above.
There is a Trusted RFC connection between HANA DB and ECC transaction system, which enables trigger based data replication in HANA system environment.
SLT Replication method allows data replication from multiple source systems to one HANA system and also from one source system to multiple HANA systems.
SLT Replication method allows data replication from multiple source systems to one HANA system and also from one source system to multiple HANA systems.
SAP LT uses trigger based approach. It has no measureable performance impact in source system.
SAP LT uses trigger based approach. It has no measureable performance impact in source system.
It also provides data transformation and filtering capability before loading to HANA database.
It also provides data transformation and filtering capability before loading to HANA database.
It allows real-time data replication, replicating only relevant data into HANA from SAP and non-SAP source systems.
It allows real-time data replication, replicating only relevant data into HANA from SAP and non-SAP source systems.
It is fully integrated with HANA System and HANA studio.
It is fully integrated with HANA System and HANA studio.
On your source SAP system AA1 you want to setup a trusted RFC towards target system BB1. When it is done, it would mean that when you are logged onto AA1 and your user has enough authorization in BB1, you can use the RFC connection and logon to BB1 without having to re-enter user and password.
Using RFC trusted/trusting relationship between two SAP systems, RFC from a trusted system to a trusting system, password is no required for logging on to the trusting system.
Open SAP ECC system using SAP logon. Enter transaction number sm59 → this is transaction number to create a new Trusted RFC connection → Click on 3rd icon to open a new connection wizard → click on Create and new window will open.
RFC Destination ECCHANA (enter name of RFC destination) Connection Type − 3 (for ABAP system)
Enter Target host − ECC system name, IP and enter System number.
Go to Logon & Security tab, Enter Language, Client, ECC system user name and password.
Click on the Save option at the top.
Click on Test Connection and it will successfully test the connection.
Run transaction − ltr (to configure RFC connection) → New browser will open → enter ECC system user name and password and logon.
Click on New → New Window will open → Enter configuration name → Click Next → Enter RFC Destination (connection name created earlier), Use search option, choose name and click next.
In Specify Target system, Enter HANA system admin user name & password, host name, Instance number and click next. Enter No of Data transfer jobs like 007(it cannot be 000) → Next → Create Configuration.
Now go to HANA Studio to use this connection −
Go to HANA Studio → Click on Data Provisioning → choose HANA system
Select source system (name of trusted RFC connection) and target schema name where you want to load tables from ECC system. Select tables you want to move to HANA database → ADD → Finish.
Selected tables will move to chosen schema under HANA database.
SAP HANA ETL based replication uses SAP Data Services to migrate data from SAP or non-SAP source system to target HANA database. BODS system is an ETL tool used to extract, transform and load data from source system to target system.
It enables to read the business data at Application layer. You need to define data flows in Data Services, scheduling a replication job and defining source and target system in data store in Data Services designer.
Login to Data Services Designer (choose Repository) → Create Data store
For SAP ECC system, choose database as SAP Applications, enter ECC server name, user name and password for ECC system, Advanced tab choose details as instance number, client number, etc. and apply.
This data store will come under local object library, if you expand this there is no table inside it.
Right click on Table → Import by name → Enter ECC table to import from ECC system (MARA is default table in ECC system) → Import → Now expand Table → MARA → Right Click View Data. If data is displayed, Data store connection is fine.
Now, to choose target system as HANA database, create a new data store. Create Data store → Name of data store SAP_HANA_TEST → Data store type (database) → Database type SAP HANA → Database version HANA 1.x.
Enter HANA server name, user name and password for HANA system and OK.
This data store will be added to Local Object Library. You can add table if you want to move data from source table to some specific table in HANA database. Note that target table should be of similar datatype as source table.
Create a new Project → Enter Project Name → Right Click on Project name → New Batch Job → Enter job name.
From right side tab, choose work flow → Enter work flow name → Double click to add it under batch job → Enter data flow → Enter data flow name → Double click to add it under batch job in Project area Save all option at top.
Drag table from First Data Store ECC (MARA) to work area. Select it and right click → Add new → Template table to create new table with similar data types in HANA DB → Enter table name, Data store ECC_HANA_TEST2 → Owner name (schema name) → OK
Drag table to front and connect both the table → save all. Now go to batch job → Right Click → Execute → Yes → OK
Once you execute the Replication job, you will get a confirmation that job has been completed successfully.
Go to HANA studio → Expand Schema → Tables → Verify data. This is manual execution of a batch job.
You can also schedule a batch job by going to Data Services Management console. Login to Data Services Management Console.
Choose the repository from left side → Navigate to 'Batch Job Configuration' tab, where you will see the list of jobs → Against the job you want to schedule → click on add schedule → Enter the 'schedule name' and set the parameters like (time, date, reoccurring etc.) as appropriate and click on 'Apply'.
This is also known as Sybase Replication in HANA system. The main components of this replication method are the Sybase Replication Agent, which is part of the SAP source application system, Replication agent and the Sybase Replication Server that is to be implemented in SAP HANA system.
Initial Load in Sybase Replication method is initiated by Load Controller and triggered by the administrator, in SAP HANA. It informs R3 Load to transfer initial load to HANA database. The R3 load on source system exports data for selected tables in source system and transfer this data to R3 load components in HANA system. R3 load on target system imports data into SAP HANA database.
SAP Host agent manages the authentication between the source system and target system, which is part of the source system. The Sybase Replication agent detects any data changes at time of initial load and ensures every single change is completed. When th ere is a change, update, and delete in entries of a table in source system, a table log is created. This table log moves data from source system to HANA database.
The delta replication captures the data changes in source system in real time once the initial load and replication is completed. All further changes in source system are captured and replicated from source system to HANA database using above-mentioned method.
This method was part of initial offering for SAP HANA replication, but not positioned/supported anymore due to licensing issues and complexity and also SLT provides the same features.
Note − This method only supports SAP ERP system as data source and DB2 as database.
Direct Extractor Connection data replication reuses existing extraction, transformation, and load mechanism built into SAP Business Suite systems via a simple HTTP(S) connection to SAP HANA. It is a batch-driven data replication technique. It is considered as method for extraction, transformation, and load with limited capabilities for data extraction.
DXC is a batch driven process and data extraction using DXC at certain interval is enough in many cases. You can set an interval when batch job executes example: every 20 minutes and in most of cases it is sufficient to extract data using these batch jobs at certain time intervals.
This method requires no additional server or application in the SAP HANA system landscape.
This method requires no additional server or application in the SAP HANA system landscape.
DXC method reduces complexity of data modeling in SAP HANA as data sends to HANA after applying all business extractor logics in Source System.
DXC method reduces complexity of data modeling in SAP HANA as data sends to HANA after applying all business extractor logics in Source System.
It speeds up the time lines for SAP HANA implementation project
It speeds up the time lines for SAP HANA implementation project
It provides semantically rich data from SAP Business Suite to SAP HANA
It provides semantically rich data from SAP Business Suite to SAP HANA
It reuses existing proprietary extraction, transformation, and load mechanism built into SAP business Suite systems over a simple HTTP(S) connection to SAP HANA.
It reuses existing proprietary extraction, transformation, and load mechanism built into SAP business Suite systems over a simple HTTP(S) connection to SAP HANA.
Data Source must have a predefined mechanism for extraction, transformation and load and if not we need to define one.
Data Source must have a predefined mechanism for extraction, transformation and load and if not we need to define one.
It requires a Business Suite System based on Net Weaver 7.0 or higher with at least below SP: Release 700 SAPKW70021 (SP stack 19, from Nov 2008).
It requires a Business Suite System based on Net Weaver 7.0 or higher with at least below SP: Release 700 SAPKW70021 (SP stack 19, from Nov 2008).
Enabling XS Engine service in Configuration tab in HANA Studio − Go to Administrator tab in HANA studio of system. Go to Configuration → xsengine.ini and set instance value to 1.
Enabling ICM Web Dispatcher service in HANA Studio − Go to Configuration → webdispatcher.ini and set instance value to 1.
It enables ICM Web Dispatcher service in HANA system. Web dispatcher uses ICM method for data read and loading in HANA system.
Setup SAP HANA Direct Extractor Connection − Download the DXC delivery unit into SAP HANA. You can import the unit in the location /usr/sap/HDB/SYS/global/hdb/content.
Import the unit using Import Dialog in SAP HANA Content Node → Configure XS Application server to utilize the DXC → Change the application_container value to libxsdxc
Creating a HTTP connection in SAP BW − Now we need to create http connection in SAP BW using transaction code SM59.
Input Parameters − Enter Name of RFC Connection, HANA Host Name and <Instance Number>
In Log on Security Tab, enter the DXC user created in HANA studio using basic Authentication method −
Setting up BW Parameters for HANA − Need to Setup the Following Parameters in BW Using transaction SE 38. Parameters List −
PSA_TO_HDB_DESTINATION − we need to mention where we need to move the Incoming data (Connection Name created using SM 59)
PSA_TO_HDB_DESTINATION − we need to mention where we need to move the Incoming data (Connection Name created using SM 59)
PSA_TO_HDB_SCHEMA − To which Schema the replicated data need to assign
PSA_TO_HDB_SCHEMA − To which Schema the replicated data need to assign
PSA_TO_HDB − GLOBAL To Replicate All data source to HANA. SYSTEM – Specified clients to Use DXC. DATASOURCE – Only Specified Data Source are used for
PSA_TO_HDB − GLOBAL To Replicate All data source to HANA. SYSTEM – Specified clients to Use DXC. DATASOURCE – Only Specified Data Source are used for
PSA_TO_HDB_DATASOURCETABLE − Need to Give the Table name having the List of data sources which are used for DXC.
PSA_TO_HDB_DATASOURCETABLE − Need to Give the Table name having the List of data sources which are used for DXC.
Install data source in ECC using RSA5.
Replicate the metadata using specified application component (data source version Need to 7.0, if we have 3.5 version data source we need to migrate that. Active the data Source in SAP BW. Once data source is activated in SAP BW it will create the following Table in Defined schema −
/BIC/A<data source>00 – IMDSO Active Table
/BIC/A<data source>00 – IMDSO Active Table
/BIC/A<data source>40 –IMDSO Activation Queue
/BIC/A<data source>40 –IMDSO Activation Queue
/BIC/A<data source>70 – Record Mode Handling Table
/BIC/A<data source>70 – Record Mode Handling Table
/BIC/A<data source>80 – Request and Packet ID information Table
/BIC/A<data source>80 – Request and Packet ID information Table
/BIC/A<data source>A0 – Request Timestamp Table
/BIC/A<data source>A0 – Request Timestamp Table
RSODSO_IMOLOG - IMDSO related table. Stores information about all data sources related to DXC.
RSODSO_IMOLOG - IMDSO related table. Stores information about all data sources related to DXC.
Now data is successfully loaded into Table /BIC/A0FI_AA_2000 once it is activated.
Open SAP HANA Studio → Create Schema under Catalog tab. <Start here>
Prepare the data and save it to csv format. Now create file with “ctl” extension with following syntax −
---------------------------------------
import data into table Schema."Table name"
from 'file.csv'
records delimited by '\n'
fields delimited by ','
Optionally enclosed by '"'
error log 'table.err'
-----------------------------------------
Transfer this “ctl” file to the FTP and execute this file to import the data −
import from ‘table.ctl’
Check data in table by going to HANA Studio → Catalog → Schema → Tables → View Content
MDX Provider is used to connect MS Excel to SAP HANA database system. It provides driver to connect HANA system to Excel and is further, used for data modelling. You can use Microsoft Office Excel 2010/2013 for connectivity with HANA for both 32 bit and 64 bit Windows.
SAP HANA supports both query languages − SQL and MDX. Both languages can be used: JDBC and ODBC for SQL and ODBO is used for MDX processing. Excel Pivot tables use MDX as query language to read data from SAP HANA system. MDX is defined as part of ODBO (OLE DB for OLAP) specification from Microsoft and is used for data selections, calculations and layout. MDX supports multidimensional data model and support reporting and Analysis requirement.
MDX provider enables the consumption of Information views defined in HANA studio by SAP and non-SAP reporting tools. Existing physical tables and schemas presents the data foundation for Information models.
Once you choose SAP HANA MDX provider from the list of data source you want to connect, pass HANA system details like host name, instance number, user name and password.
Once the connection is successful, you can choose Package name → HANA Modeling views to generate Pivot tables.
MDX is tightly integrated into HANA database. Connection and Session management of HANA database handles statements that are executed by HANA. When these statements are executed, they are parsed by MDX interface and a calculation model is generated for each MDX statement. This calculation model creates an execution plan that generates standard results for MDX. These results are directly consumed by OLAP clients.
To make MDX connection to HANA database, HANA client tools are required. You can download this client tool from SAP market place. Once installation of HANA client is done, you will see the option of SAP HANA MDX provider in the list of data source in MS Excel.
SAP HANA alert monitoring is used to monitor the status of system resources and services that are running in the HANA system. Alert monitoring is used to handle critical alerts like CPU usage, disk full, FS reaching threshold, etc. The monitoring component of HANA system continuously collects information about health, usage and performance of all the components of HANA database. It raises an alert when any of the component breaches the set threshold value.
The priority of alert raised in HANA system tells the criticality of problem and it depends on the check that is performed on the component. Example − If CPU usage is 80%, a low priority alert will be raised. However, if it reaches 96%, system will raise a high priority alert.
The System Monitor is the most common way to monitor HANA system and to verify the availability of all your SAP HANA system components. System monitor is used to check all key component and services of a HANA system.
You can also drill down into details of an individual system in Administration Editor. It tells about Data Disk, Log disk, Trace Disk, alerts on resource usage with priority.
Alert tab in Administrator editor is used to check the current and all alerts in HANA system.
It also tells about the time when an alert is raised, description of the alert, priority of the alert, etc.
SAP HANA monitoring dashboard tells the key aspects of system health and configuration −
High and Medium priority alerts.
Memory and CPU usage
Data backups
SAP HANA database persistence layer is responsible to manage logs for all the transactions to provide standard data back up and system restore function.
It ensures that database can be restored to the most recent committed state after a restart or after a system crash and transactions are executed completely or completely undone. SAP HANA Persistent Layer is part of Index server and it has data and transaction log volumes for HANA system and in-memory data is regularly saved to these volumes. There are services in HANA system that has their own persistence. It also provides save points and logs for all the database transactions from the last save point.
Main memory is volatile therefore data is lost during a restart or power outage.
Main memory is volatile therefore data is lost during a restart or power outage.
Data needs to be stored in persisted medium.
Data needs to be stored in persisted medium.
Backup & Restore is available.
Backup & Restore is available.
It ensures that the database is restored to the most recent committed state after a restart and that transaction are either completely executed or completely undone.
It ensures that the database is restored to the most recent committed state after a restart and that transaction are either completely executed or completely undone.
Database can always be restored to its most recent state, to ensure these changes to data in the database are regularly copied to disk. Log files containing data changes and certain transaction events are also saved regularly to disk. Data and logs of a system are stored in Log volumes.
Data volumes stores SQL data and undo log information and also SAP HANA information modeling data. This information is stored in data pages, which are called Blocks. These blocks are written to data volumes at regular time interval, which is known as save point.
Log volumes store the information about data changes. Changes that are made between two log points are written to Log volumes and called log entries. They are saved to log buffer when transaction is committed.
In SAP HANA database, changed data is automatically saved from memory to disk. These regular intervals are called savepoints and by default they are set to occur every five minutes. Persistence Layer in SAP HANA database performs these savepoint at regular interval. During this operation changed data is written to disk and redo logs are also saved to disk as well.
The data belonging to a Savepoint tells consistent state of the data on disk and remains there until the next savepoint operation has completed. Redo log entries are written to the log volumes for all changes to persistent data. In the event of a database restart, data from the last completed savepoint can be read from the data volumes, and redo log entries written to the log volumes.
Frequency of savepoint can be configured by global.ini file. Savepoints can be initiated by other operations like database shut down or system restart. You can also run savepoint by executing the below command −
To save data and redo logs to log volumes, you should ensure that there is enough disk space available to capture these, otherwise the system will issue a disk full event and database will stop working.
During the HANA system installation, following default directories are created as the storage location for data and log volumes −
/usr/sap/<SID>/SYS/global/hdb/data
/usr/sap/<SID>/SYS/global/hdb/log
These directories are defined in global.ini file and can be changed at later stage.
Note that Savepoints do not affect the performance of transactions executed in HANA system. During a savepoint operation, transactions continue to run as normal. With HANA system running on proper hardware, impact of savepoints on the performance of system is negligible.
SAP HANA backup and recovery is used to perform HANA system backups and recovery of system in case of any database failure.
It tells the status of currently running data backup and last successful data backup.
Backup now option can be used to run data backup wizard.
It tells about the Backup interval settings, file based data backup settings and log based data backup setting.
Backint settings give an option to use third party tool for data and log back up with configuration of backing agent.
Configure the connection to a third-party backup tool by specifying a parameter file for the Backint agent.
File based data backup setting tells the folder where you want to save the data backup on HANA system. You can change your backup folder.
You can also limit the size of data backup files. If system data backup exceeds this set file size, it will split across the multiple files.
Log backup settings tell the destination folder where you want to save log backup on external server. You can choose a destination type for log backup
File − ensures that sufficient space in system to store backups
Backint − is special named pipe exists on file system but require no disk space.
You can choose backup interval from drop down. It tells the longest amount of time that can pass before a new log backup is written. Backup Interval: It can be in seconds, minutes or hours.
Enable Automatic log backup option: It helps you to keep log area vacant. If you disable this log area will continue to fill and that can result database to hang.
Open Backup Wizard − to run the backup of system.
Backup wizard is used to specify backup settings. It tells the Backup type, destination Type, Backup Destination folder, Backup prefix, size of backup, etc.
When you click on next → Review Backup settings → Finish
It runs the system backups and tells the time to complete backup for the each server.
To recover SAP HANA database, the database needs to be shut down. Hence, during recovery, end users or SAP applications cannot access the database.
Recovery of SAP HANA database is required in the following situations −
A disk in the data area is unusable or disk in the log area is unusable.
A disk in the data area is unusable or disk in the log area is unusable.
As a consequence of a logical error, the database needs to be reset to its state at a particular point in time.
As a consequence of a logical error, the database needs to be reset to its state at a particular point in time.
You want to create a copy of the database.
You want to create a copy of the database.
Choose HANA system → Right click → Back and Recovery → Recover System
Most Recent State − Used for recovering the database to the time as close as possible to the current time. For this recovery, the data backup and log backup have to be available since last data backup and log area are required to perform the above type recovery.
Point in Time − Used for recovering the database to the specific point in time. For this recovery, the data backup and log backup have to be available since last data backup and log area are required to perform the above type recovery
Specific Data Backup − Used for recovering the database to a specified data backup. Specific data backup is required for the above type of recovery option.
Specific Log Position − This recovery type is an advanced option that can be used in exceptional cases where a previous recovery failed.
Note − To run recovery wizard you should have administrator privileges on HANA system.
SAP HANA provides mechanism for business continuity and disaster recovery for system faults and software errors. High availability in HANA system defines set of practices that helps to achieve business continuity in case of disaster like power failures in data centers, natural disasters like fire, flood, etc. or any hardware failures.
SAP HANA high availability provides fault tolerance and ability of system to resume system operations after an outage with minimum business loss.
The following illustration shows the phases of high availability in HANA system −
First phase is being prepared for the fault. A fault can be detected automatically or by an administrative action. Data is backed up and stand by systems take over the operations. A recovery process is put in action includes repair of faulty system and original system to be restored to previous configuration.
To achieve high availability in HANA system, key is the inclusion of extra components, which are not necessary to function and use in case of failure of other components. It includes hardware redundancy, network redundancy and data center redundancy. SAP HANA provides several levels of hardware and software redundancies as below −
SAP HANA appliance vendors offer multiple layers of redundant hardware, software and network components, such as redundant power supplies and fans, error-correcting memories, fully redundant network switches and routers, and uninterrupted power supply (UPS). Disk storage system guarantees writing even in the presence of power failure and use striping and mirroring features to provide redundancy for automatic recovery from disk failures.
SAP HANA is based on SUSE Linux Enterprise 11 for SAP and includes security pre-configurations.
SAP HANA system software includes a watchdog function, which automatically restarts configured services (index server, name server, and so on), in case of detected stoppage (killed or crashed).
SAP HANA provides persistence of transaction logs, savepoints and snapshots to support system restart and recovery from failures, with minimal delay and without loss of data.
SAP HANA system involves separate standby hosts that are used for failover, in case of failure of the primary system. This improves the availability of HANA system by reducing the recovery time from an outage.
The SAP HANA system logs all the transactions that change application data or the database catalog in log entries and stores them in log area. It uses these log entries in log area to roll back or repeat SQL statements. The log files are available in HANA system and can be accessed via HANA studio on Diagnosis files page under Administrator editor.
During a log backup process, only the actual data of the log segments is written from the log area to service-specific log backup files or to a third-party backup tool.
After a system failure, you may need to redo log entries from log backups to restore the database to the desired state.
If a database service with persistence stops, it is important to ensure that it is restarted, otherwise recovery will be possible only to a point before service is stopped.
The log backup timeout determines the interval at which the log segments are backed up if a commit has taken place in this interval. You can configure the log backup timeout using the Backup Console in SAP HANA studio −
You can also configure the log_backup_timeout_s interval in the global.ini configuration file.
The log backup to the “File” and backup mode “NORMAL” are the default settings for the automatic log backup function after installation of SAP HANA system. Automatic log backup only works if at least one complete data backup has been performed.
Once the first complete data backup has been performed, the automatic log backup function is active. SAP HANA studio can be used to enable/disable the automatic log backup function. It is recommended to keep automatic log backup enabled otherwise log area will continue to fill. A full log area can result a database freeze in HANA system.
You can also change the enable_auto_log_backup parameter in the persistence section of the global.ini configuration file.
SQL stands for Structured Query Language.
It is a standardized language for communicating with a database. SQL is used to retrieve the data, store or manipulate the data in the database.
SQL statements perform the following functions −
Data definition and manipulation
System management
Session management
Transaction management
Schema definition and manipulation
The set of SQL extensions, which allow developers to push data into database, is called SQL scripts.
DML statements are used for managing data within schema objects. Some examples −
SELECT − retrieve data from the database
SELECT − retrieve data from the database
INSERT − insert data into a table
INSERT − insert data into a table
UPDATE − updates existing data within a table
UPDATE − updates existing data within a table
DDL statements are used to define the database structure or schema. Some examples −
CREATE − to create objects in the database
CREATE − to create objects in the database
ALTER − alters the structure of the database
ALTER − alters the structure of the database
DROP − delete objects from the database
DROP − delete objects from the database
Some examples of DCL statements are −
GRANT − gives user's access privileges to database
GRANT − gives user's access privileges to database
REVOKE − withdraw access privileges given with the GRANT command
REVOKE − withdraw access privileges given with the GRANT command
When we create Information Views in SAP HANA Modeler, we are creating it on top of some OLTP applications. All these in back end run on SQL. Database understands only this language.
To do a testing if our report will meet the business requirement we have to run SQL statement in database if Output is according to the requirement.
HANA Calculation views can be created in two ways - Graphical or using SQL script. When we create more complex Calculation views, then we might have to use direct SQL scripts.
Select the HANA system and click on SQL console option in system view. You can also open SQL console by right click on Catalog tab or any on any Schema name.
SAP HANA can act both as Relational as well as OLAP database. When we use BW on HANA, then we create cubes in BW and HANA, which act as relational database and always produce a SQL Statement. However, when we directly access HANA views using OLAP connection, then it will act as OLAP database and MDX will be generated.
You can create row or Column store tables in SAP HANA using create table option. A table can be created by executing a data definition create table statement or using graphical option in HANA studio.
When you create a table, you also need to define attributes inside it.
SQL statement to create a table in HANA Studio SQL Console −
Create column Table TEST (
ID INTEGER,
NAME VARCHAR(10),
PRIMARY KEY (ID)
);
Creating a table in HANA studio using GUI option −
When you create a table, you need to define the names of columns and SQL data types. The Dimension field tells the length of value and the Key option to define it as primary key.
SAP HANA supports the following data types in a table −
SAP HANA supports 7 categories of SQL data types and it depends on the type of data you have to store in a column.
Numeric
Character/ String
Boolean
Date Time
Binary
Large Objects
Multi-Valued
The following table gives the list of data types in each category −
These data types are used to store date and time in a table in HANA database.
DATE − data type consists of year, month and day information to represent a date value in a column. Default format for a Date data type is YYYY-MM-DD.
DATE − data type consists of year, month and day information to represent a date value in a column. Default format for a Date data type is YYYY-MM-DD.
TIME − data type consists of hours, minutes, and seconds value in a table in HANA database. Default format for Time data type is HH: MI: SS.
TIME − data type consists of hours, minutes, and seconds value in a table in HANA database. Default format for Time data type is HH: MI: SS.
SECOND DATE − data type consists of year, month, day, hour, minute, second value in a table in HANA database. Default format for SECONDDATE data type is YYYY-MM-DD HH:MM:SS.
SECOND DATE − data type consists of year, month, day, hour, minute, second value in a table in HANA database. Default format for SECONDDATE data type is YYYY-MM-DD HH:MM:SS.
TIMESTAMP − data type consists of date and time information in a table in HANA database. Default format for TIMESTAMP data type is YYYY-MM-DD HH:MM:SS:FFn, where FFn represents fraction of second.
TIMESTAMP − data type consists of date and time information in a table in HANA database. Default format for TIMESTAMP data type is YYYY-MM-DD HH:MM:SS:FFn, where FFn represents fraction of second.
TinyINT − stores 8 bit unsigned integer. Min value: 0 and max value: 255
TinyINT − stores 8 bit unsigned integer. Min value: 0 and max value: 255
SMALLINT − stores 16 bit signed integer. Min value: -32,768 and max value: 32,767
SMALLINT − stores 16 bit signed integer. Min value: -32,768 and max value: 32,767
Integer − stores 32 bit signed integer. Min value: -2,147,483,648 and max value: 2,147,483,648
Integer − stores 32 bit signed integer. Min value: -2,147,483,648 and max value: 2,147,483,648
BIGINT − stores 64 bit signed integer. Min value: -9,223,372,036,854,775,808 and max value: 9,223,372,036,854,775,808
BIGINT − stores 64 bit signed integer. Min value: -9,223,372,036,854,775,808 and max value: 9,223,372,036,854,775,808
SMALL − Decimal and Decimal: Min value: -10^38 +1 and max value: 10^38 -1
SMALL − Decimal and Decimal: Min value: -10^38 +1 and max value: 10^38 -1
REAL − Min Value:-3.40E + 38 and max value: 3.40E + 38
REAL − Min Value:-3.40E + 38 and max value: 3.40E + 38
DOUBLE − stores 64 bit floating point number. Min value: -1.7976931348623157E308 and max value: 1.7976931348623157E308
DOUBLE − stores 64 bit floating point number. Min value: -1.7976931348623157E308 and max value: 1.7976931348623157E308
Boolean data types stores Boolean value, which are TRUE, FALSE
Varchar − maximum of 8000 characters.
Varchar − maximum of 8000 characters.
Nvarchar − maximum length of 4000 characters
Nvarchar − maximum length of 4000 characters
ALPHANUM − stores alphanumeric characters. Value for an integer is between 1 to 127.
ALPHANUM − stores alphanumeric characters. Value for an integer is between 1 to 127.
SHORTTEXT − stores variable length character string which supports text search features and string search features.
SHORTTEXT − stores variable length character string which supports text search features and string search features.
Binary types are used to store bytes of binary data.
VARBINARY − stores binary data in bytes. Max integer length is between 1 and 5000.
LARGEOBJECTS are used to store a large amount of data such as text documents and images.
NCLOB − stores large UNICODE character object.
NCLOB − stores large UNICODE character object.
BLOB − stores large amount of Binary data.
BLOB − stores large amount of Binary data.
CLOB − stores large amount of ASCII character data.
CLOB − stores large amount of ASCII character data.
TEXT − it enables text search features. This data type can be defined for only column tables and not for row store tables.
TEXT − it enables text search features. This data type can be defined for only column tables and not for row store tables.
BINTEXT − supports text search features but it is possible to insert binary data.
BINTEXT − supports text search features but it is possible to insert binary data.
Multivalued data types are used to store collection of values with same data type.
Arrays store collections of value with the same data type. They can also contain null values.
An operator is a special character used primarily in SQL statement's with WHERE clause to perform operation, such as comparisons and arithmetic operations. They are used to pass conditions in a SQL query.
Operator types given below can be used in SQL statements in HANA −
Arithmetic Operators
Comparison/Relational Operators
Logical Operators
Set Operators
Arithmetic operators are used to perform simple calculation functions like addition, subtraction, multiplication, division and percentage.
Comparison operators are used to compare the values in SQL statement.
Logical operators are used to pass multiple conditions in SQL statement or are used to manipulate the results of conditions.
Set operators are used to combine results of two queries into a single result. Data type should be same for both the tables.
UNION − It combines the results of two or more Select statements. However it will eliminate duplicate rows.
UNION − It combines the results of two or more Select statements. However it will eliminate duplicate rows.
UNION ALL − This operator is similar to Union but it also shows the duplicate rows.
UNION ALL − This operator is similar to Union but it also shows the duplicate rows.
INTERSECT − Intersect operation is used to combine the two SELECT statements, and it returns the records, which are common from both SELECT statements. In case of Intersect, the number of columns and datatype must be same in both the tables.
INTERSECT − Intersect operation is used to combine the two SELECT statements, and it returns the records, which are common from both SELECT statements. In case of Intersect, the number of columns and datatype must be same in both the tables.
MINUS − Minus operation combines result of two SELECT statements and return only those results, which belong to first set of result and eliminate the rows in second statement from the output of first.
MINUS − Minus operation combines result of two SELECT statements and return only those results, which belong to first set of result and eliminate the rows in second statement from the output of first.
There are various SQL functions provided by SAP HANA database −
Numeric Functions
String Functions
Fulltext Functions
Datetime Functions
Aggregate Functions
Data Type Conversion Functions
Window Functions
Series Data Functions
Miscellaneous Functions
These are inbuilt numeric functions in SQL and use in scripting. It takes numeric values or strings with numeric characters and return numeric values.
ABS − It returns the absolute value of a numeric argument.
ABS − It returns the absolute value of a numeric argument.
Example − SELECT ABS (-1) "abs" FROM TEST;
abs
1
ACOS, ASIN, ATAN, ATAN2 (These functions return trigonometric value of the argument)
BINTOHEX − It converts a Binary value to a hexadecimal value.
BINTOHEX − It converts a Binary value to a hexadecimal value.
BITAND − It performs an AND operation on bits of passed argument.
BITAND − It performs an AND operation on bits of passed argument.
BITCOUNT − It performs the count of number of set bits in an argument.
BITCOUNT − It performs the count of number of set bits in an argument.
BITNOT − It performs a bitwise NOT operation on the bits of argument.
BITNOT − It performs a bitwise NOT operation on the bits of argument.
BITOR − It perform an OR operation on bits of passed argument.
BITOR − It perform an OR operation on bits of passed argument.
BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position.
BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position.
BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position.
BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position.
BITXOR − It performs XOR operation on bits of passed argument.
BITXOR − It performs XOR operation on bits of passed argument.
CEIL − It returns the first integer that is greater or equal to the passed value.
CEIL − It returns the first integer that is greater or equal to the passed value.
COS, COSH, COT ((These functions return trigonometric value of the argument)
COS, COSH, COT ((These functions return trigonometric value of the argument)
EXP − It returns the result of the base of natural logarithms e raised to the power of passed value.
EXP − It returns the result of the base of natural logarithms e raised to the power of passed value.
FLOOR − It returns the largest integer not greater than the numeric argument.
FLOOR − It returns the largest integer not greater than the numeric argument.
HEXTOBIN − It converts a hexadecimal value to a binary value.
HEXTOBIN − It converts a hexadecimal value to a binary value.
LN − It returns the natural logarithm of the argument.
LN − It returns the natural logarithm of the argument.
LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive.
LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive.
Various other numeric functions can also be used − MOD, POWER, RAND, ROUND, SIGN, SIN, SINH, SQRT, TAN, TANH, UMINUS
Various SQL string functions can be used in HANA with SQL scripting. Most common string functions are −
ASCII − It returns integer ASCII value of passed string.
ASCII − It returns integer ASCII value of passed string.
CHAR − It returns the character associated with passed ASCII value.
CHAR − It returns the character associated with passed ASCII value.
CONCAT − It is Concatenation operator and returns the combined passed strings.
CONCAT − It is Concatenation operator and returns the combined passed strings.
LCASE − It converts all character of a string to Lower case.
LCASE − It converts all character of a string to Lower case.
LEFT − It returns the first characters of a passed string as per mentioned value.
LEFT − It returns the first characters of a passed string as per mentioned value.
LENGTH − It returns the number of characters in passed string.
LENGTH − It returns the number of characters in passed string.
LOCATE − It returns the position of substring within passed string.
LOCATE − It returns the position of substring within passed string.
LOWER − It converts all characters in string to lowercase.
LOWER − It converts all characters in string to lowercase.
NCHAR − It returns the Unicode character with passed integer value.
NCHAR − It returns the Unicode character with passed integer value.
REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string.
REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string.
RIGHT − It returns the rightmost passed value characters of mentioned string.
RIGHT − It returns the rightmost passed value characters of mentioned string.
UPPER − It converts all characters in passed string to uppercase.
UPPER − It converts all characters in passed string to uppercase.
UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase.
UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase.
Other string functions that can be used are − LPAD, LTRIM, RTRIM, STRTOBIN, SUBSTR_AFTER, SUBSTR_BEFORE, SUBSTRING, TRIM, UNICODE, RPAD, BINTOSTR
There are various Date Time functions that can be used in HANA in SQL scripts. Most common Date Time functions are −
CURRENT_DATE − It returns the current local system date.
CURRENT_DATE − It returns the current local system date.
CURRENT_TIME − It returns the current local system time.
CURRENT_TIME − It returns the current local system time.
CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF).
CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF).
CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date.
CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date.
CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time.
CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time.
CURRENT_UTCTIMESTAMP
CURRENT_UTCTIMESTAMP
DAYOFMONTH − It returns the integer value of day in passed date in argument.
DAYOFMONTH − It returns the integer value of day in passed date in argument.
HOUR − It returns integer value of hour in passed time in argument.
HOUR − It returns integer value of hour in passed time in argument.
YEAR − It returns the year value of passed date.
YEAR − It returns the year value of passed date.
Other Date Time functions are − DAYOFYEAR, DAYNAME, DAYS_BETWEEN, EXTRACT, NANO100_BETWEEN, NEXT_DAY, NOW, QUARTER, SECOND, SECONDS_BETWEEN, UTCTOLOCAL, WEEK, WEEKDAY, WORKDAYS_BETWEEN, ISOWEEK, LAST_DAY, LOCALTOUTC, MINUTE, MONTH, MONTHNAME, ADD_DAYS, ADD_MONTHS, ADD_SECONDS, ADD_WORKDAYS
These functions are used to convert one data type to other or to perform a check if conversion is possible or not.
Most common data type conversion functions used in HANA in SQL scripts −
CAST − It returns the value of an expression converted to a supplied data type.
CAST − It returns the value of an expression converted to a supplied data type.
TO_ALPHANUM − It converts a passed value to an ALPHANUM data type
TO_ALPHANUM − It converts a passed value to an ALPHANUM data type
TO_REAL − It converts a value to a REAL data type.
TO_REAL − It converts a value to a REAL data type.
TO_TIME − It converts a passed time string to the TIME data type.
TO_TIME − It converts a passed time string to the TIME data type.
TO_CLOB − It converts a value to a CLOB data type.
TO_CLOB − It converts a value to a CLOB data type.
Other similar Data Type conversion functions are − TO_BIGINT, TO_BINARY, TO_BLOB, TO_DATE, TO_DATS, TO_DECIMAL, TO_DOUBLE, TO_FIXEDCHAR, TO_INT, TO_INTEGER, TO_NCLOB, TO_NVARCHAR, TO_TIMESTAMP, TO_TINYINT, TO_VARCHAR, TO_SECONDDATE, TO_SMALLDECIMAL, TO_SMALLINT
There are also various Windows and other miscellaneous functions that can be used in HANA SQL scripts.
Current_Schema − It returns a string containing the current schema name.
Current_Schema − It returns a string containing the current schema name.
Session_User − It returns the user name of current session
Session_User − It returns the user name of current session
An Expression is used to evaluate a clause to return values. There are different SQL expressions that can be used in HANA −
Case Expressions
Function Expressions
Aggregate Expressions
Subqueries in Expressions
This is used to pass multiple conditions in a SQL expression. It allows the use of IF-ELSE-THEN logic without using procedures in SQL statements.
SELECT COUNT( CASE WHEN sal < 2000 THEN 1 ELSE NULL END ) count1,
COUNT( CASE WHEN sal BETWEEN 2001 AND 4000 THEN 1 ELSE NULL END ) count2,
COUNT( CASE WHEN sal > 4000 THEN 1 ELSE NULL END ) count3 FROM emp;
This statement will return count1, count2, count3 with integer value as per passed condition.
Function expressions involve SQL inbuilt functions to be used in Expressions.
Aggregate functions are used to perform complex calculations like Sum, Percentage, Min, Max, Count, Mode, Median, etc. Aggregate Expression uses Aggregate functions to calculate single value from multiple values.
Aggregate Functions − Sum, Count, Minimum, Maximum. These are applied on measure values (facts) and It is always associated with a dimension.
Common aggregate functions include −
Average ()
Count ()
Maximum ()
Median ()
Minimum ()
Mode ()
Sum ()
A subquery as an expression is a Select statement. When it is used in an expression, it returns a zero or a single value.
A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
A procedure allows you to group the SQL statement into a single block. Stored Procedures are used to achieve certain result across applications. The set of SQL statements and the logic that is used to perform some specific task are stored in SQL Stored Procedures. These stored procedures are executed by applications to perform that task.
Stored Procedures can return data in the form of output parameters (integer or character) or a cursor variable. It can also result in set of Select statements, which are used by other Stored Procedures.
Stored Procedures are also used for performance optimization as it contains series of SQL statements and results from one set of statement determines next set of statements to be executed. Stored procedures prevent users to see the complexity and details of tables in a database. As Stored procedures contain certain business logic, so users need to execute or call the procedure name.
No need to keep reissuing the individual statements but can refer to the database procedure.
Create procedure prc_name (in inp integer, out opt "EFASION"."ARTICLE_LOOKUP")
as
begin
opt = select * from "EFASION"."ARTICLE_LOOKUP" where article_id = :inp ;
end;
A sequence is a set of integers 1, 2, 3, that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value, and sequences provide an easy way to generate them.
The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQL to take care.
Try out the following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because it is auto-incremented by MySQL.
mysql> CREATE TABLE INSECT
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO INSECT (id,name,date,origin) VALUES
-> (NULL,'housefly','2001-09-10','kitchen'),
-> (NULL,'millipede','2001-09-10','driveway'),
-> (NULL,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM INSECT ORDER BY id;
+----+-------------+------------+------------+
| id | name | date | origin |
+----+-------------+------------+------------+
| 1 | housefly | 2001-09-10 | kitchen |
| 2 | millipede | 2001-09-10 | driveway |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)
LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise, PERL and PHP scripts provide exclusive functions to retrieve auto-incremented value of last record.
Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle −
$dbh->do ("INSERT INTO INSECT (name,date,origin)
VALUES('moth','2001-09-14','windowsill')");
my $seq = $dbh->{mysql_insertid};
After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling mysql_insert_id( ) −
mysql_query ("INSERT INTO INSECT (name,date,origin)
VALUES('moth','2001-09-14','windowsill')", $conn_id);
$seq = mysql_insert_id ($conn_id);
There may be a case when you have deleted many records from a table and you want to re-sequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having join, with other table.
If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique −
mysql> ALTER TABLE INSECT DROP id;
mysql> ALTER TABLE insect
-> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
-> ADD PRIMARY KEY (id);
By default, MySQL will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQL will start sequence from 100.
mysql> CREATE TABLE INSECT
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE.
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is associated.
Triggers can be written for the following purposes −
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
SQL Synonyms is an alias for a table or a Schema object in a database. They are used to protect client applications from the changes made to name or location of an object.
Synonyms permit applications to function irrespective of user who owns the table and which database holds the table or object.
Create Synonym statement is used create a Synonym for a table, view, package, procedure, objects, etc.
There is a table Customer of efashion, located on a Server1. To access this from Server2, a client application would have to use name as Server1.efashion.Customer. Now we change the location of Customer table the client application would have to be modified to reflect the change.
To address these we can create a synonym of Customer table Cust_Table on Server2 for the table on Server1. So now client application has to use the single-part name Cust_Table to reference this table. Now, if the location of this table changes, you will have to modify the synonym to point to the new location of the table.
As there is no ALTER SYNONYM statement, you have to drop the synonym Cust_Table and then re-create the synonym with the same name and point the synonym to the new location of Customer table.
Public Synonyms are owned by PUBLIC schema in a database. Public synonyms can be referenced by all users in the database. They are created by the application owner for the tables and other objects such as procedures and packages so the users of the application can see the objects.
CREATE PUBLIC SYNONYM Cust_table for efashion.Customer;
To create a PUBLIC Synonym, you have to use keyword PUBLIC as shown.
Private Synonyms are used in a database schema to hide the true name of a table, procedure, view or any other database object.
Private synonyms can be referenced only by the schema that owns the table or object.
CREATE SYNONYM Cust_table FOR efashion.Customer;
Synonyms can be dropped using DROP Synonym command. If you are dropping a public Synonym, you have to use the keyword public in the drop statement.
DROP PUBLIC Synonym Cust_table;
DROP Synonym Cust_table;
SQL explain plans are used to generate detail explanation of SQL statements. They are used to evaluate execution plan that SAP HANA database follows to execute the SQL statements.
The results of explain plan are stored into EXPLAIN_PLAN_TABLE for evaluation. To use Explain Plan, passed SQL query must be a data manipulation language (DML).
SELECT − retrieve data from the a database
SELECT − retrieve data from the a database
INSERT − insert data into a table
INSERT − insert data into a table
UPDATE − updates existing data within a table
UPDATE − updates existing data within a table
SQL Explain Plans cannot be used with DDL and DCL SQL statements.
EXPLAIN PLAN_TABLE in database consists of multiple columns. Few common column names − OPERATOR_NAME, OPERATOR_ID, PARENT_OPERATOR_ID, LEVEL and POSITION, etc.
COLUMN SEARCH value tells the starting position of column engine operators.
ROW SEARCH value tells the starting position of row engine operators.
EXPLAIN PLAN SET STATEMENT_NAME = ‘statement_name’ FOR <SQL DML statement>
SELECT Operator_Name, Operator_ID
FROM explain_plan_table
WHERE statement_name = 'statement_name';
DELETE FROM explain_plan_table WHERE statement_name = 'TPC-H Q10';
SQL Data Profiling task is used to understand and analyze data from multiple data sources. It is used to remove incorrect, incomplete data and prevent data quality problems before they are loaded in Data warehouse.
Here are the benefits of SQL Data Profiling tasks −
It helps is analyzing source data more effectively.
It helps is analyzing source data more effectively.
It helps in understanding the source data better.
It helps in understanding the source data better.
It remove incorrect, incomplete data and improve data quality before it is loaded into Data warehouse.
It remove incorrect, incomplete data and improve data quality before it is loaded into Data warehouse.
It is used with Extraction, Transformation and Loading task.
It is used with Extraction, Transformation and Loading task.
The Data Profiling task checks profiles that helps to understand a data source and identify problems in the data that has to be fixed.
You can use the Data Profiling task inside an Integration Services package to profile data that is stored in SQL Server and to identify potential problems with data quality.
Note − Data Profiling Task works only with SQL Server data sources and does not support any other file based or third party data sources.
To run a package contains Data Profiling task, user account must have read/write permissions with CREATE TABLE permissions on the tempdb database.
Data Profile Viewer is used to review the profiler output. The Data Profile Viewer also supports drilldown capability to help you understand data quality issues that are identified in the profile output. This drill down capability sends live queries to the original data source.
It involves execution of a package that contains Data Profiling task to compute the profiles. The task saves the output in XML format to a file or a package variable.
To view the data profiles, send the output to a file and then use the Data Profile Viewer. This viewer is a stand-alone utility that displays the profile output in both summary and detail format with optional drilldown capability.
The Data Profiling task has these convenient configuration options −
While configuring a profile request, the task accepts ‘*’ wildcard in place of a column name. This simplifies the configuration and makes it easier to discover the characteristics of unfamiliar data. When the task runs, the task profiles every column that has an appropriate data type.
You can select Quick Profile to configure the task quickly. A Quick Profile profiles a table or view by using all the default profiles and settings.
The Data Profiling Task can compute eight different data profiles. Five of these profiles can check individual columns and the remaining three analyze- multiple columns or relationships between columns.
The Data Profiling task outputs the selected profiles into XML format that is structured like DataProfile.xsd schema.
You can save a local copy of the schema and view the local copy of the schema in Microsoft Visual Studio or another schema editor, in an XML editor or in a text editor such as Notepad.
Set of SQL statements for HANA database which allows developer to pass complex logic into database is called SQL Script. SQL Script is known as collections of SQL extensions. These extension are Data Extensions, Function Extensions, and Procedure Extension.
SQL Script supports stored Functions and Procedures and that allows pushing complex parts of Application logic to database.
Main benefit of using SQL Script is to allow the execution of complex calculations inside SAP HANA database. Using SQL Scripts in place of single query enables Functions to return multiple values. Complex SQL functions can be further decomposed into smaller functions. SQL Script provides control logic that is not available in single SQL statement.
SQL Scripts are used to achieve performance optimization in HANA by executing scripts at DB layer −
By Executing SQL scripts at database layer, it eliminates need to transfer large amount of data from database to application.
By Executing SQL scripts at database layer, it eliminates need to transfer large amount of data from database to application.
Calculations are executed at database layer to get benefits of HANA database like column operations, parallel processing of queries, etc.
Calculations are executed at database layer to get benefits of HANA database like column operations, parallel processing of queries, etc.
While using SQL scripts in Information Modeler, below given are applied to Procedures −
Input parameters can be of scalar or table type.
Output parameters must be of table types.
Table types required for the signature are generated automatically.
SQL script are used to create script based Calculation views. Type SQL statements against existing raw tables or column store. Define output structure, activation of view creates table type as per structure.
Launch SAP HANA studio. Expand the content node → Select a package where you want to create the new Calculation view. Right Click → New Calculation View End of the navigation path → Provide name and description.
Select calculation view type → from Type dropdown list, select SQL Script → Set Parameter Case Sensitive to True or False based on how you require the naming convention for the output parameters of the calculation view → Choose Finish.
Select default schema − Select the Semantics node → Choose the View Properties tab → In the Default Schema dropdown list, select the default schema.
Choose SQL Script node in the Semantics node → Define the output structure. In the output pane, choose Create Target. Add the required output parameters and specify its length and type.
To add multiple columns that are part of existing information views or catalog tables or table functions to the output structure of script-based calculation views −
In the Output pane, choose Start of the navigation path New Next navigation step Add Columns from End of the navigation path → Name of the object that contains the columns you want to add to the output → Select one or more objects from the dropdown list → Choose Next.
In the Source pane, choose the columns that you want to add to the output → To add selective columns to the output, then select those columns and choose Add. To add all columns of an object to the output, then select the object and choose Add → Finish.
Activate the script-based calculation view − In the SAP HANA Modeler perspective − Save and Activate - to activate the current view and redeploy the affected objects if an active version of the affected object exists. Otherwise, only the current view is activated.
Save and activate all − to activate the current view along with the required and affected objects.
In the SAP HANA Development perspective − In Project Explorer view, select the required object. In the context menu, select Start of the navigation path Team Next navigation step Activate End of the navigation path.
SQL Scripting in HANA Information Modeler is used to create complex Calculation Views, which are not possible to create using GUI option.
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": 3295,
"s": 3107,
"text": "SAP HANA is a combination of HANA Database, Data Modeling, HANA Administration and Data Provisioning in one single suite. In SAP HANA, HANA stands for High-Performance Analytic Appliance."
},
{
"code": null,
"e": 3545,
"s": 3295,
"text": "According to former SAP executive, Dr. Vishal Sikka, HANA stands for Hasso’s New Architecture. HANA developed interest by mid-2011 and various fortune 500 companies started considering it as an option to maintain Business Warehouse needs after that."
},
{
"code": null,
"e": 3593,
"s": 3545,
"text": "The main features of SAP HANA are given below −"
},
{
"code": null,
"e": 3697,
"s": 3593,
"text": "SAP HANA is a combination of software and hardware innovation to process huge amount of real time data."
},
{
"code": null,
"e": 3801,
"s": 3697,
"text": "SAP HANA is a combination of software and hardware innovation to process huge amount of real time data."
},
{
"code": null,
"e": 3869,
"s": 3801,
"text": "Based on multi core architecture in distributed system environment."
},
{
"code": null,
"e": 3937,
"s": 3869,
"text": "Based on multi core architecture in distributed system environment."
},
{
"code": null,
"e": 3995,
"s": 3937,
"text": "Based on row and column type of data-storage in database."
},
{
"code": null,
"e": 4053,
"s": 3995,
"text": "Based on row and column type of data-storage in database."
},
{
"code": null,
"e": 4161,
"s": 4053,
"text": "Used extensively in Memory Computing Engine (IMCE) to process and analyze massive amount of real time data."
},
{
"code": null,
"e": 4269,
"s": 4161,
"text": "Used extensively in Memory Computing Engine (IMCE) to process and analyze massive amount of real time data."
},
{
"code": null,
"e": 4422,
"s": 4269,
"text": "It reduces cost of ownership, increases application performance, enables new applications to run on real time environment that were not possible before."
},
{
"code": null,
"e": 4575,
"s": 4422,
"text": "It reduces cost of ownership, increases application performance, enables new applications to run on real time environment that were not possible before."
},
{
"code": null,
"e": 4683,
"s": 4575,
"text": "It is written in C++, supports and runs on only one Operating System Suse Linux Enterprise Server 11 SP1/2."
},
{
"code": null,
"e": 4791,
"s": 4683,
"text": "It is written in C++, supports and runs on only one Operating System Suse Linux Enterprise Server 11 SP1/2."
},
{
"code": null,
"e": 4979,
"s": 4791,
"text": "Today, most successful companies respond quickly to market changes and new opportunities. A key to this is the effective and efficient use of data and information by analyst and managers."
},
{
"code": null,
"e": 5028,
"s": 4979,
"text": "HANA overcomes the limitations mentioned below −"
},
{
"code": null,
"e": 5165,
"s": 5028,
"text": "Due to increase in “Data Volume”, it is a challenge for the companies to provide access to real time data for analysis and business use."
},
{
"code": null,
"e": 5302,
"s": 5165,
"text": "Due to increase in “Data Volume”, it is a challenge for the companies to provide access to real time data for analysis and business use."
},
{
"code": null,
"e": 5395,
"s": 5302,
"text": "It involves high maintenance cost for IT companies to store and maintain large data volumes."
},
{
"code": null,
"e": 5488,
"s": 5395,
"text": "It involves high maintenance cost for IT companies to store and maintain large data volumes."
},
{
"code": null,
"e": 5574,
"s": 5488,
"text": "Due to unavailability of real time data, analysis and processing results are delayed."
},
{
"code": null,
"e": 5660,
"s": 5574,
"text": "Due to unavailability of real time data, analysis and processing results are delayed."
},
{
"code": null,
"e": 5823,
"s": 5660,
"text": "SAP has partnered with leading IT hardware vendors like IBM, Dell, Cisco etc. and combined it with SAP licensed services and technology to sell SAP HANA platform."
},
{
"code": null,
"e": 5963,
"s": 5823,
"text": "There are, total, 11 vendors that manufacture HANA Appliances and provide onsite support for installation and configuration of HANA system."
},
{
"code": null,
"e": 5989,
"s": 5963,
"text": "Top few Vendors include −"
},
{
"code": null,
"e": 5993,
"s": 5989,
"text": "IBM"
},
{
"code": null,
"e": 5998,
"s": 5993,
"text": "Dell"
},
{
"code": null,
"e": 6001,
"s": 5998,
"text": "HP"
},
{
"code": null,
"e": 6007,
"s": 6001,
"text": "Cisco"
},
{
"code": null,
"e": 6015,
"s": 6007,
"text": "Fujitsu"
},
{
"code": null,
"e": 6030,
"s": 6015,
"text": "Lenovo (China)"
},
{
"code": null,
"e": 6034,
"s": 6030,
"text": "NEC"
},
{
"code": null,
"e": 6041,
"s": 6034,
"text": "Huawei"
},
{
"code": null,
"e": 6273,
"s": 6041,
"text": "According to statistics provided by SAP, IBM is one of major vendor of SAP HANA hardware appliances and has a market share of 50-52% but according to another market survey conducted by HANA clients, IBM has a market hold up to 70%."
},
{
"code": null,
"e": 6385,
"s": 6273,
"text": "HANA Hardware vendors provide preconfigured appliances for hardware, Operating System and SAP software product."
},
{
"code": null,
"e": 6710,
"s": 6385,
"text": "Vendor finalizes the installation by an onsite setup and configuration of HANA components. This onsite visit includes deployment of HANA system in Data Center, Connectivity to Organization Network, SAP system ID adaption, updates from Solution Manager, SAP Router Connectivity, SSL Enablement and other system configuration."
},
{
"code": null,
"e": 6913,
"s": 6710,
"text": "Customer/Client starts with connectivity of Data Source system and BI clients. HANA Studio Installation is completed on local system and HANA system is added to perform Data modeling and administration."
},
{
"code": null,
"e": 7247,
"s": 6913,
"text": "An In-Memory database means all the data from source system is stored in a RAM memory. In a conventional Database system, all data is stored in hard disk. SAP HANA In-Memory Database wastes no time in loading the data from hard disk to RAM. It provides faster access of data to multicore CPUs for information processing and analysis."
},
{
"code": null,
"e": 7302,
"s": 7247,
"text": "The main features of SAP HANA in-memory database are −"
},
{
"code": null,
"e": 7341,
"s": 7302,
"text": "SAP HANA is Hybrid In-memory database."
},
{
"code": null,
"e": 7380,
"s": 7341,
"text": "SAP HANA is Hybrid In-memory database."
},
{
"code": null,
"e": 7453,
"s": 7380,
"text": "It combines row based, column based and Object Oriented base technology."
},
{
"code": null,
"e": 7526,
"s": 7453,
"text": "It combines row based, column based and Object Oriented base technology."
},
{
"code": null,
"e": 7587,
"s": 7526,
"text": "It uses parallel processing with multicore CPU Architecture."
},
{
"code": null,
"e": 7648,
"s": 7587,
"text": "It uses parallel processing with multicore CPU Architecture."
},
{
"code": null,
"e": 7764,
"s": 7648,
"text": "Conventional Database reads memory data in 5 milliseconds. SAP HANA In-Memory database reads data in 5 nanoseconds."
},
{
"code": null,
"e": 7880,
"s": 7764,
"text": "Conventional Database reads memory data in 5 milliseconds. SAP HANA In-Memory database reads data in 5 nanoseconds."
},
{
"code": null,
"e": 8000,
"s": 7880,
"text": "It means, memory reads in HANA database are 1 million times faster than a conventional database hard disk memory reads."
},
{
"code": null,
"e": 8242,
"s": 8000,
"text": "Analysts want to see current data immediately in real time and do not want to wait for data until it is loaded to SAP BW system. SAP HANA In-Memory processing allows loading of real time data with use of various data provisioning techniques."
},
{
"code": null,
"e": 8456,
"s": 8242,
"text": "HANA database takes advantage of in-memory processing to deliver the fastest data-retrieval speeds, which is enticing to companies struggling with high-scale online transactions or timely forecasting and planning."
},
{
"code": null,
"e": 8670,
"s": 8456,
"text": "HANA database takes advantage of in-memory processing to deliver the fastest data-retrieval speeds, which is enticing to companies struggling with high-scale online transactions or timely forecasting and planning."
},
{
"code": null,
"e": 8899,
"s": 8670,
"text": "Disk-based storage is still the enterprise standard and price of RAM has been declining steadily, so memory-intensive architectures will eventually replace slow, mechanical spinning disks and will lower the cost of data storage."
},
{
"code": null,
"e": 9128,
"s": 8899,
"text": "Disk-based storage is still the enterprise standard and price of RAM has been declining steadily, so memory-intensive architectures will eventually replace slow, mechanical spinning disks and will lower the cost of data storage."
},
{
"code": null,
"e": 9248,
"s": 9128,
"text": "In-Memory Column-based storage provides data compression up to 11 times, thus, reducing the storage space of huge data."
},
{
"code": null,
"e": 9368,
"s": 9248,
"text": "In-Memory Column-based storage provides data compression up to 11 times, thus, reducing the storage space of huge data."
},
{
"code": null,
"e": 9555,
"s": 9368,
"text": "This speed advantages offered by RAM storage system are further enhanced by the use of multi-core CPUs, multiple CPUs per node and multiple nodes per server in a distributed environment."
},
{
"code": null,
"e": 9742,
"s": 9555,
"text": "This speed advantages offered by RAM storage system are further enhanced by the use of multi-core CPUs, multiple CPUs per node and multiple nodes per server in a distributed environment."
},
{
"code": null,
"e": 9921,
"s": 9742,
"text": "SAP HANA studio is an Eclipse-based tool. SAP HANA studio is both, the central development environment and the main administration tool for HANA system. Additional features are −"
},
{
"code": null,
"e": 9999,
"s": 9921,
"text": "It is a client tool, which can be used to access local or remote HANA system."
},
{
"code": null,
"e": 10077,
"s": 9999,
"text": "It is a client tool, which can be used to access local or remote HANA system."
},
{
"code": null,
"e": 10195,
"s": 10077,
"text": "It provides an environment for HANA Administration, HANA Information Modeling and Data Provisioning in HANA database."
},
{
"code": null,
"e": 10313,
"s": 10195,
"text": "It provides an environment for HANA Administration, HANA Information Modeling and Data Provisioning in HANA database."
},
{
"code": null,
"e": 10366,
"s": 10313,
"text": "SAP HANA Studio can be used on following platforms −"
},
{
"code": null,
"e": 10448,
"s": 10366,
"text": "Microsoft Windows 32 and 64 bit versions of: Windows XP, Windows Vista, Windows 7"
},
{
"code": null,
"e": 10530,
"s": 10448,
"text": "Microsoft Windows 32 and 64 bit versions of: Windows XP, Windows Vista, Windows 7"
},
{
"code": null,
"e": 10578,
"s": 10530,
"text": "SUSE Linux Enterprise Server SLES11: x86 64 bit"
},
{
"code": null,
"e": 10626,
"s": 10578,
"text": "SUSE Linux Enterprise Server SLES11: x86 64 bit"
},
{
"code": null,
"e": 10670,
"s": 10626,
"text": "Mac OS, HANA studio client is not available"
},
{
"code": null,
"e": 10714,
"s": 10670,
"text": "Mac OS, HANA studio client is not available"
},
{
"code": null,
"e": 10988,
"s": 10714,
"text": "Depending on HANA Studio installation, not all features may be available. At the time of Studio installation, specify the features you want to install as per the role. To work on most recent version of HANA studio, Software Life Cycle Manager can be used for client update."
},
{
"code": null,
"e": 11136,
"s": 10988,
"text": "SAP HANA Studio provides perspectives to work on the following HANA features. You can choose Perspective in HANA Studio from the following option −"
},
{
"code": null,
"e": 11184,
"s": 11136,
"text": "HANA Studio → Window → Open Perspective → Other"
},
{
"code": null,
"e": 11381,
"s": 11184,
"text": "Toolset for various administration tasks, excluding transportable design-time repository objects. General troubleshooting tools like tracing, the catalog browser and SQL Console are also included."
},
{
"code": null,
"e": 11568,
"s": 11381,
"text": "It provides Toolset for content development. It addresses, in particular, the DataMarts and ABAP on SAP HANA scenarios, which do not include SAP HANA native application development (XS)."
},
{
"code": null,
"e": 11771,
"s": 11568,
"text": "SAP HANA system contains a small Web server, which can be used to host small applications. It provides Toolset for developing SAP HANA native applications like application code written in Java and HTML."
},
{
"code": null,
"e": 11811,
"s": 11771,
"text": "By default, all features are installed."
},
{
"code": null,
"e": 11933,
"s": 11811,
"text": "To Perform HANA Database Administration and monitoring features, SAP HANA Administration Console Perspective can be used."
},
{
"code": null,
"e": 11988,
"s": 11933,
"text": "Administrator Editor can be accessed in several ways −"
},
{
"code": null,
"e": 12057,
"s": 11988,
"text": "From System View Toolbar − Choose Open Administration default button"
},
{
"code": null,
"e": 12126,
"s": 12057,
"text": "From System View Toolbar − Choose Open Administration default button"
},
{
"code": null,
"e": 12191,
"s": 12126,
"text": "In System View − Double Click on HANA System or Open Perspective"
},
{
"code": null,
"e": 12256,
"s": 12191,
"text": "In System View − Double Click on HANA System or Open Perspective"
},
{
"code": null,
"e": 12548,
"s": 12256,
"text": "In Administration View: HANA studio provides multiple tabs to check configuration and health of the HANA system. Overview Tab tells General Information like, Operational Status, start time of first and last started service, version, build date and time, Platform, hardware manufacturer, etc."
},
{
"code": null,
"e": 12756,
"s": 12548,
"text": "Single or multiple systems can be added to HANA studio for administration and information modeling purpose. To add new HANA system, host name, instance number and database user name and password is required."
},
{
"code": null,
"e": 12804,
"s": 12756,
"text": "Port 3615 should be open to connect to Database"
},
{
"code": null,
"e": 12830,
"s": 12804,
"text": "Port 31015 Instance No 10"
},
{
"code": null,
"e": 12856,
"s": 12830,
"text": "Port 30015 Instance No 00"
},
{
"code": null,
"e": 12887,
"s": 12856,
"text": "SSh port should also be opened"
},
{
"code": null,
"e": 12943,
"s": 12887,
"text": "To add a system to HANA studio, follow the given steps."
},
{
"code": null,
"e": 13075,
"s": 12943,
"text": "Right Click in Navigator space and click on Add System. Enter HANA system details, i.e. Host name & Instance number and click next."
},
{
"code": null,
"e": 13177,
"s": 13075,
"text": "Enter Database user name and password to connect to SAP HANA database. Click on Next and then Finish."
},
{
"code": null,
"e": 13347,
"s": 13177,
"text": "Once you click on Finish, HANA system will be added to System View for administration and modeling purpose. Each HANA system has two main sub-nodes, Catalog and Content."
},
{
"code": null,
"e": 13482,
"s": 13347,
"text": "It contains all available Schemas i.e. all data structures, tables and data, Column views, Procedures that can be used in Content tab."
},
{
"code": null,
"e": 13710,
"s": 13482,
"text": "The Content tab contains design time repository, which holds all information of data models created with the HANA Modeler. These models are organized in Packages. The content node provides different views on same physical data."
},
{
"code": null,
"e": 13989,
"s": 13710,
"text": "System Monitor in HANA studio provides an overview of all your HANA system at a glance. From System Monitor, you can drill down into details of an individual system in Administration Editor. It tells about Data Disk, Log disk, Trace Disk, Alerts on resource usage with priority."
},
{
"code": null,
"e": 14048,
"s": 13989,
"text": "The following Information is available in System Monitor −"
},
{
"code": null,
"e": 14274,
"s": 14048,
"text": "SAP HANA Information Modeler; also known as HANA Data Modeler is heart of HANA System. It enables to create modeling views at the top of database tables and implement business logic to create a meaningful report for analysis."
},
{
"code": null,
"e": 14404,
"s": 14274,
"text": "Provides multiple views of transactional data stored in physical tables of HANA database for analysis and business logic purpose."
},
{
"code": null,
"e": 14534,
"s": 14404,
"text": "Provides multiple views of transactional data stored in physical tables of HANA database for analysis and business logic purpose."
},
{
"code": null,
"e": 14600,
"s": 14534,
"text": "Informational modeler only works for column based storage tables."
},
{
"code": null,
"e": 14666,
"s": 14600,
"text": "Informational modeler only works for column based storage tables."
},
{
"code": null,
"e": 14812,
"s": 14666,
"text": "Information Modeling Views are consumed by Java or HTML based applications or SAP tools like SAP Lumira or Analysis Office for reporting purpose."
},
{
"code": null,
"e": 14958,
"s": 14812,
"text": "Information Modeling Views are consumed by Java or HTML based applications or SAP tools like SAP Lumira or Analysis Office for reporting purpose."
},
{
"code": null,
"e": 15050,
"s": 14958,
"text": "Also possible to use third party tools like MS Excel to connect to HANA and create reports."
},
{
"code": null,
"e": 15142,
"s": 15050,
"text": "Also possible to use third party tools like MS Excel to connect to HANA and create reports."
},
{
"code": null,
"e": 15198,
"s": 15142,
"text": "SAP HANA Modeling Views exploit real power of SAP HANA."
},
{
"code": null,
"e": 15254,
"s": 15198,
"text": "SAP HANA Modeling Views exploit real power of SAP HANA."
},
{
"code": null,
"e": 15311,
"s": 15254,
"text": "There are three types of Information Views, defined as −"
},
{
"code": null,
"e": 15326,
"s": 15311,
"text": "Attribute View"
},
{
"code": null,
"e": 15340,
"s": 15326,
"text": "Analytic View"
},
{
"code": null,
"e": 15357,
"s": 15340,
"text": "Calculation View"
},
{
"code": null,
"e": 15608,
"s": 15357,
"text": "SAP HANA Modeler Views can only be created on the top of Column based tables. Storing data in Column tables is not a new thing. Earlier it was assumed that storing data in Columnar based structure takes more memory size and not performance Optimized."
},
{
"code": null,
"e": 15767,
"s": 15608,
"text": "With evolution of SAP HANA, HANA used column based data storage in Information views and presented the real benefits of columnar tables over Row based tables."
},
{
"code": null,
"e": 15980,
"s": 15767,
"text": "In a Column store table, Data is stored vertically. So, similar data types come together as shown in the example above. It provides faster memory read and write operations with help of In-Memory Computing Engine."
},
{
"code": null,
"e": 16217,
"s": 15980,
"text": "In a conventional database, data is stored in Row based structure i.e. horizontally. SAP HANA stores data in both row and Column based structure. This provides Performance optimization, flexibility and data compression in HANA database."
},
{
"code": null,
"e": 16279,
"s": 16217,
"text": "Storing Data in Columnar based table has following benefits −"
},
{
"code": null,
"e": 16296,
"s": 16279,
"text": "Data Compression"
},
{
"code": null,
"e": 16313,
"s": 16296,
"text": "Data Compression"
},
{
"code": null,
"e": 16398,
"s": 16313,
"text": "Faster read and write access to tables as compared to conventional Row based storage"
},
{
"code": null,
"e": 16483,
"s": 16398,
"text": "Faster read and write access to tables as compared to conventional Row based storage"
},
{
"code": null,
"e": 16517,
"s": 16483,
"text": "Flexibility & parallel processing"
},
{
"code": null,
"e": 16551,
"s": 16517,
"text": "Flexibility & parallel processing"
},
{
"code": null,
"e": 16605,
"s": 16551,
"text": "Perform Aggregations and Calculations at higher speed"
},
{
"code": null,
"e": 16659,
"s": 16605,
"text": "Perform Aggregations and Calculations at higher speed"
},
{
"code": null,
"e": 16810,
"s": 16659,
"text": "There are various methods and algorithms how data can be stored in Column based structure- Dictionary Compressed, Run Length Compressed and many more."
},
{
"code": null,
"e": 16960,
"s": 16810,
"text": "In Dictionary Compressed, cells are stored in form of numbers in tables and numeral cells are always performance optimized as compared to characters."
},
{
"code": null,
"e": 17094,
"s": 16960,
"text": "In Run length compressed, it saves the multiplier with cell value in numerical format and multiplier shows repetitive value in table."
},
{
"code": null,
"e": 17318,
"s": 17094,
"text": "It is always advisable to use Column based storage, if SQL statement has to perform aggregate functions and calculations. Column based tables always perform better when running aggregate functions like Sum, Count, Max, Min."
},
{
"code": null,
"e": 17442,
"s": 17318,
"text": "Row based storage is preferred when output has to return complete row. The example given below makes it easy to understand."
},
{
"code": null,
"e": 17732,
"s": 17442,
"text": "In the above example, while running an Aggregate function (Sum) in sales column with Where clause, it will only use Date and Sales column while running SQL query so if it is column based storage table then it will be performance optimized, faster as data is required only from two columns."
},
{
"code": null,
"e": 17871,
"s": 17732,
"text": "While running a simple Select query, full row has to be printed in output so it is advisable to store table as Row based in this scenario."
},
{
"code": null,
"e": 18110,
"s": 17871,
"text": "Attributes are non-measurable elements in a database table. They represent master data and similar to characteristics of BW. Attribute Views are dimensions in a database or are used to join dimensions or other attribute views in modeling."
},
{
"code": null,
"e": 18135,
"s": 18110,
"text": "Important features are −"
},
{
"code": null,
"e": 18195,
"s": 18135,
"text": "Attribute views are used in Analytic and Calculation views."
},
{
"code": null,
"e": 18233,
"s": 18195,
"text": "Attribute view represent master data."
},
{
"code": null,
"e": 18307,
"s": 18233,
"text": "Used to filter size of dimension tables in Analytic and Calculation View."
},
{
"code": null,
"e": 18563,
"s": 18307,
"text": "Analytic Views use power of SAP HANA to perform calculations and aggregation functions on the tables in database. It has at least one fact table that has measures and primary keys of dimension tables and surrounded by dimension tables contain master data."
},
{
"code": null,
"e": 18588,
"s": 18563,
"text": "Important features are −"
},
{
"code": null,
"e": 18648,
"s": 18588,
"text": "Analytic views are designed to perform Star schema queries."
},
{
"code": null,
"e": 18708,
"s": 18648,
"text": "Analytic views are designed to perform Star schema queries."
},
{
"code": null,
"e": 18844,
"s": 18708,
"text": "Analytic views contain at least one fact table and multiple dimension tables with master data and perform calculations and aggregations"
},
{
"code": null,
"e": 18980,
"s": 18844,
"text": "Analytic views contain at least one fact table and multiple dimension tables with master data and perform calculations and aggregations"
},
{
"code": null,
"e": 19039,
"s": 18980,
"text": "They are similar to Info Cubes and Info objects in SAP BW."
},
{
"code": null,
"e": 19098,
"s": 19039,
"text": "They are similar to Info Cubes and Info objects in SAP BW."
},
{
"code": null,
"e": 19240,
"s": 19098,
"text": "Analytic views can be created on top of Attribute views and Fact tables and performs calculations like number of unit sold, total price, etc."
},
{
"code": null,
"e": 19382,
"s": 19240,
"text": "Analytic views can be created on top of Attribute views and Fact tables and performs calculations like number of unit sold, total price, etc."
},
{
"code": null,
"e": 19644,
"s": 19382,
"text": "Calculation Views are used on top of Analytic and Attribute views to perform complex calculations, which are not possible with Analytic Views. Calculation view is a combination of base column tables, Attribute views and Analytic views to provide business logic."
},
{
"code": null,
"e": 19669,
"s": 19644,
"text": "Important features are −"
},
{
"code": null,
"e": 19768,
"s": 19669,
"text": "Calculation Views are defined either graphical using HANA Modeling feature or scripted in the SQL."
},
{
"code": null,
"e": 19867,
"s": 19768,
"text": "Calculation Views are defined either graphical using HANA Modeling feature or scripted in the SQL."
},
{
"code": null,
"e": 20005,
"s": 19867,
"text": "It is created to perform complex calculations, which are not possible with other views- Attribute and Analytic views of SAP HANA modeler."
},
{
"code": null,
"e": 20143,
"s": 20005,
"text": "It is created to perform complex calculations, which are not possible with other views- Attribute and Analytic views of SAP HANA modeler."
},
{
"code": null,
"e": 20290,
"s": 20143,
"text": "One or more Attribute views and Analytic views are consumed with help of inbuilt functions like Projects, Union, Join, Rank in a Calculation View."
},
{
"code": null,
"e": 20437,
"s": 20290,
"text": "One or more Attribute views and Analytic views are consumed with help of inbuilt functions like Projects, Union, Join, Rank in a Calculation View."
},
{
"code": null,
"e": 20676,
"s": 20437,
"text": "SAP HANA was initially, developed in Java and C++ and designed to run only Operating System Suse Linux Enterprise Server 11. SAP HANA system consists of multiple components that are responsible to emphasize computing power of HANA system."
},
{
"code": null,
"e": 20811,
"s": 20676,
"text": "Most important component of SAP HANA system is Index Server, which contains SQL/MDX processor to handle query statements for database."
},
{
"code": null,
"e": 20946,
"s": 20811,
"text": "Most important component of SAP HANA system is Index Server, which contains SQL/MDX processor to handle query statements for database."
},
{
"code": null,
"e": 21125,
"s": 20946,
"text": "HANA system contains Name Server, Preprocessor Server, Statistics Server and XS engine, which is used to communicate and host small web applications and various other components."
},
{
"code": null,
"e": 21304,
"s": 21125,
"text": "HANA system contains Name Server, Preprocessor Server, Statistics Server and XS engine, which is used to communicate and host small web applications and various other components."
},
{
"code": null,
"e": 21581,
"s": 21304,
"text": "Index Server is heart of SAP HANA database system. It contains actual data and engines for processing that data. When SQL or MDX is fired for SAP HANA system, an Index Server takes care of all these requests and processes them. All HANA processing takes place in Index Server."
},
{
"code": null,
"e": 21862,
"s": 21581,
"text": "Index Server contains Data engines to handle all SQL/MDX statements that come to HANA database system. It also has Persistence Layer that is responsible for durability of HANA system and ensures HANA system is restored to most recent state when there is restart of system failure."
},
{
"code": null,
"e": 21998,
"s": 21862,
"text": "Index Server also has Session and Transaction Manager, which manage transactions and keep track of all running and closed transactions."
},
{
"code": null,
"e": 22197,
"s": 21998,
"text": "It is responsible for processing SQL/MDX transactions with data engines responsible to run queries. It segments all query requests and direct them to correct engine for the performance Optimization."
},
{
"code": null,
"e": 22397,
"s": 22197,
"text": "It also ensures that all SQL/MDX requests are authorized and also provide error handling for efficient processing of these statements. It contains several engines and processors for query execution −"
},
{
"code": null,
"e": 22611,
"s": 22397,
"text": "MDX (Multi Dimension Expression) is query language for OLAP systems like SQL is used for Relational database. MDX Engine is responsible to handle queries and manipulates multidimensional data stored in OLAP cubes."
},
{
"code": null,
"e": 22825,
"s": 22611,
"text": "MDX (Multi Dimension Expression) is query language for OLAP systems like SQL is used for Relational database. MDX Engine is responsible to handle queries and manipulates multidimensional data stored in OLAP cubes."
},
{
"code": null,
"e": 22909,
"s": 22825,
"text": "Planning Engine is responsible to run planning operations within SAP HANA database."
},
{
"code": null,
"e": 22993,
"s": 22909,
"text": "Planning Engine is responsible to run planning operations within SAP HANA database."
},
{
"code": null,
"e": 23129,
"s": 22993,
"text": "Calculation Engine converts data into Calculation models to create logical execution plan to support parallel processing of statements."
},
{
"code": null,
"e": 23265,
"s": 23129,
"text": "Calculation Engine converts data into Calculation models to create logical execution plan to support parallel processing of statements."
},
{
"code": null,
"e": 23391,
"s": 23265,
"text": "Stored Procedure processor executes procedure calls for optimized processing; it converts OLAP cubes to HANA optimized cubes."
},
{
"code": null,
"e": 23517,
"s": 23391,
"text": "Stored Procedure processor executes procedure calls for optimized processing; it converts OLAP cubes to HANA optimized cubes."
},
{
"code": null,
"e": 23630,
"s": 23517,
"text": "It is responsible to coordinate all database transactions and keep track of all running and closed transactions."
},
{
"code": null,
"e": 23749,
"s": 23630,
"text": "When a transaction is executed or failed, Transaction manager notifies relevant data engine to take necessary actions."
},
{
"code": null,
"e": 23900,
"s": 23749,
"text": "Session management component is responsible to initialize and manage sessions and connections for SAP HANA system using predefined session parameters."
},
{
"code": null,
"e": 24059,
"s": 23900,
"text": "It is responsible for durability and atomicity of transactions in HANA system. Persistence layer provides built in disaster recovery system for HANA database."
},
{
"code": null,
"e": 24214,
"s": 24059,
"text": "It ensures database is restored to most recent state and ensures that all the transactions are completed or undone in case of a system failure or restart."
},
{
"code": null,
"e": 24492,
"s": 24214,
"text": "It is also responsible to manage data and transaction logs and also contain data backup, log backup and configuration back of HANA system. Backups are stored as save points in the Data Volumes via a Save Point coordinator, which is normally set to take back every 5-10 minutes."
},
{
"code": null,
"e": 24563,
"s": 24492,
"text": "Preprocessor Server in SAP HANA system is used for text data analysis."
},
{
"code": null,
"e": 24711,
"s": 24563,
"text": "Index Server uses preprocessor server for analyzing text data and extracting the information from text data when text search capabilities are used."
},
{
"code": null,
"e": 25009,
"s": 24711,
"text": "NAME server contains System Landscape information of HANA system. In distributed environment, there are multiple nodes with each node has multiple CPU’s, Name server holds topology of HANA system and has information about all the running components and information is spread on all the components."
},
{
"code": null,
"e": 25055,
"s": 25009,
"text": "Topology of SAP HANA system is recorded here."
},
{
"code": null,
"e": 25101,
"s": 25055,
"text": "Topology of SAP HANA system is recorded here."
},
{
"code": null,
"e": 25208,
"s": 25101,
"text": "It decreases the time in re-indexing as it holds which data is on which server in distributed environment."
},
{
"code": null,
"e": 25315,
"s": 25208,
"text": "It decreases the time in re-indexing as it holds which data is on which server in distributed environment."
},
{
"code": null,
"e": 25569,
"s": 25315,
"text": "This server checks and analyzes the health of all components in HANA system. Statistical Server is responsible for collecting the data related to system resources, their allocation and consumption of the resources and overall performance of HANA system."
},
{
"code": null,
"e": 25714,
"s": 25569,
"text": "It also provides historical data related to system performance for analyses purpose, to check and fix performance related issues in HANA system."
},
{
"code": null,
"e": 25921,
"s": 25714,
"text": "XS engine helps external Java and HTML based applications to access HANA system with help of XS client. As SAP HANA system contains a web server which can be used to host small JAVA/HTML based applications."
},
{
"code": null,
"e": 26042,
"s": 25921,
"text": "XS Engine transforms the persistence model stored in database into consumption model for clients exposed via HTTP/HTTPS."
},
{
"code": null,
"e": 26289,
"s": 26042,
"text": "SAP Host agent should be installed on all the machines that are part of SAP HANA system Landscape. SAP Host agent is used by Software Update Manager SUM for installing automatic updates to all components of HANA system in distributed environment."
},
{
"code": null,
"e": 26486,
"s": 26289,
"text": "LM structure of SAP HANA system contains information about current installation details. This information is used by Software Update Manager to install automatic updates on HANA system components."
},
{
"code": null,
"e": 26701,
"s": 26486,
"text": "This diagnostic agent provides all data to SAP Solution Manager to monitor SAP HANA system. This agent provides all the information about HANA database, which include database current state and general information."
},
{
"code": null,
"e": 26802,
"s": 26701,
"text": "It provides configuration details of HANA system when SAP SOLMAN is integrated with SAP HANA system."
},
{
"code": null,
"e": 26969,
"s": 26802,
"text": "SAP HANA studio repository helps HANA developers to update current version of HANA studio to latest versions. Studio Repository holds the code which does this update."
},
{
"code": null,
"e": 27124,
"s": 26969,
"text": "SAP Market Place is used to install updates for SAP systems. Software Update Manager for HANA system helps is update of HANA system from SAP Market place."
},
{
"code": null,
"e": 27298,
"s": 27124,
"text": "It is used for software downloads, customer messages, SAP Notes and requesting license keys for HANA system. It is also used to distribute HANA studio to end user’s systems."
},
{
"code": null,
"e": 27649,
"s": 27298,
"text": "SAP HANA Modeler option is used to create Information views on the top of schemas → tables in HANA database. These views are consumed by JAVA/HTML based applications or SAP Applications like SAP Lumira, Office Analysis or third party software like MS Excel for reporting purpose to meet business logic and to perform analysis and extract information."
},
{
"code": null,
"e": 27804,
"s": 27649,
"text": "HANA Modeling is done on the top of tables available in Catalog tab under Schema in HANA studio and all views are saved under Content table under Package."
},
{
"code": null,
"e": 27902,
"s": 27804,
"text": "You can create new Package under Content tab in HANA studio using right click on Content and New."
},
{
"code": null,
"e": 28032,
"s": 27902,
"text": "All Modeling Views created inside one package comes under the same package in HANA studio and categorized according to View Type."
},
{
"code": null,
"e": 28266,
"s": 28032,
"text": "Each View has different structure for Dimension and Fact tables. Dim tables are defined with master data and Fact table has Primary Key for dimension tables and measures like Number of Unit sold, Average delay time, Total Price, etc."
},
{
"code": null,
"e": 28409,
"s": 28266,
"text": "Fact Table contains Primary Keys for Dimension table and measures. They are joined with Dimension tables in HANA Views to meet business logic."
},
{
"code": null,
"e": 28490,
"s": 28409,
"text": "Example of Measures − Number of unit sold, Total Price, Average Delay time, etc."
},
{
"code": null,
"e": 28683,
"s": 28490,
"text": "Dimension Table contains master data and is joined with one or more fact tables to make some business logic. Dimension tables are used to create schemas with fact tables and can be normalized."
},
{
"code": null,
"e": 28736,
"s": 28683,
"text": "Example of Dimension Table − Customer, Product, etc."
},
{
"code": null,
"e": 28886,
"s": 28736,
"text": "Suppose a company sells products to customers. Every sale is a fact that happens within the company and the fact table is used to record these facts."
},
{
"code": null,
"e": 29120,
"s": 28886,
"text": "For example, row 3 in the fact table records the fact that customer 1 (Brian) bought one item on day 4. And, in a complete example, we would also have a product table and a time table so that we know what she bought and exactly when."
},
{
"code": null,
"e": 29375,
"s": 29120,
"text": "The fact table lists events that happen in our company (or at least the events that we want to analyze- No of Unit Sold, Margin, and Sales Revenue). The Dimension tables list the factors (Customer, Time, and Product) by which we want to analyze the data."
},
{
"code": null,
"e": 29531,
"s": 29375,
"text": "Schemas are logical description of tables in Data Warehouse. Schemas are created by joining multiple fact and Dimension tables to meet some business logic."
},
{
"code": null,
"e": 29734,
"s": 29531,
"text": "Database uses relational model to store data. However, Data Warehouse use Schemas that join dimensions and fact tables to meet business logic. There are three types of Schemas used in a Data Warehouse −"
},
{
"code": null,
"e": 29746,
"s": 29734,
"text": "Star Schema"
},
{
"code": null,
"e": 29764,
"s": 29746,
"text": "Snowflakes Schema"
},
{
"code": null,
"e": 29778,
"s": 29764,
"text": "Galaxy Schema"
},
{
"code": null,
"e": 29928,
"s": 29778,
"text": "In Star Schema, Each Dimension is joined to one single Fact table. Each Dimension is represented by only one dimension and is not further normalized."
},
{
"code": null,
"e": 30005,
"s": 29928,
"text": "Dimension Table contains set of attribute that are used to analyze the data."
},
{
"code": null,
"e": 30173,
"s": 30005,
"text": "Example − In example given below, we have a Fact table FactSales that has Primary keys for all the Dim tables and measures units_sold and dollars_ sold to do analysis."
},
{
"code": null,
"e": 30246,
"s": 30173,
"text": "We have four Dimension tables − DimTime, DimItem, DimBranch, DimLocation"
},
{
"code": null,
"e": 30383,
"s": 30246,
"text": "Each Dimension table is connected to Fact table as Fact table has Primary Key for each Dimension Tables that is used to join two tables."
},
{
"code": null,
"e": 30484,
"s": 30383,
"text": "Facts/Measures in Fact Table are used for analysis purpose along with attribute in Dimension tables."
},
{
"code": null,
"e": 30707,
"s": 30484,
"text": "In Snowflakes schema, some of Dimension tables are further, normalized and Dim tables are connected to single Fact Table. Normalization is used to organize attributes and tables of database to minimize the data redundancy."
},
{
"code": null,
"e": 30863,
"s": 30707,
"text": "Normalization involves breaking a table into less redundant smaller tables without losing any information and smaller tables are joined to Dimension table."
},
{
"code": null,
"e": 31071,
"s": 30863,
"text": "In the above example, DimItem and DimLocation Dimension tables are normalized without losing any information. This is called Snowflakes schema where dimension tables are further normalized to smaller tables."
},
{
"code": null,
"e": 31237,
"s": 31071,
"text": "In Galaxy Schema, there are multiple Fact tables and Dimension tables. Each Fact table stores primary keys of few Dimension tables and measures/facts to do analysis."
},
{
"code": null,
"e": 31461,
"s": 31237,
"text": "In the above example, there are two Fact tables FactSales, FactShipping and multiple Dimension tables joined to Fact tables. Each Fact table contains Primary Key for joined Dim tables and measures/Facts to perform analysis."
},
{
"code": null,
"e": 31612,
"s": 31461,
"text": "Tables in HANA database can be accessed from HANA Studio in Catalogue tab under Schemas. New tables can be created using the two methods given below −"
},
{
"code": null,
"e": 31629,
"s": 31612,
"text": "Using SQL editor"
},
{
"code": null,
"e": 31646,
"s": 31629,
"text": "Using GUI option"
},
{
"code": null,
"e": 31822,
"s": 31646,
"text": "SQL Console can be opened by selecting Schema name, in which, new table has to be created using System View SQL Editor option or by Right click on Schema name as shown below −"
},
{
"code": null,
"e": 31986,
"s": 31822,
"text": "Once SQL Editor is opened, Schema name can be confirmed from the name written on the top of SQL Editor. New table can be created using SQL Create Table statement −"
},
{
"code": null,
"e": 32073,
"s": 31986,
"text": "Create column Table Test1 (\n ID INTEGER,\n NAME VARCHAR(10),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 32181,
"s": 32073,
"text": "In this SQL statement, we have created a Column table “Test1”, defined data types of table and Primary Key."
},
{
"code": null,
"e": 32379,
"s": 32181,
"text": "Once you write Create table SQL query, click on Execute option on top of SQL editor right side. Once the statement is executed, we will get a confirmation message as shown in snapshot given below −"
},
{
"code": null,
"e": 32465,
"s": 32379,
"text": "Statement 'Create column Table Test1 (ID INTEGER,NAME VARCHAR(10), PRIMARY KEY (ID))'"
},
{
"code": null,
"e": 32561,
"s": 32465,
"text": "successfully executed in 13 ms 761 μs (server processing time: 12 ms 979 μs) − Rows Affected: 0"
},
{
"code": null,
"e": 32820,
"s": 32561,
"text": "Execution statement also tells about the time taken to execute the statement. Once statement is successfully executed, right click on Table tab under Schema name in System View and refresh. New Table will be reflected in the list of tables under Schema name."
},
{
"code": null,
"e": 32894,
"s": 32820,
"text": "Insert statement is used to enter the data in the Table using SQL editor."
},
{
"code": null,
"e": 32967,
"s": 32894,
"text": "Insert into TEST1 Values (1,'ABCD')\nInsert into TEST1 Values (2,'EFGH');"
},
{
"code": null,
"e": 32985,
"s": 32967,
"text": "Click on Execute."
},
{
"code": null,
"e": 33133,
"s": 32985,
"text": "You can right click on Table name and use Open Data Definition to see data type of the table. Open Data Preview/Open Content to see table contents."
},
{
"code": null,
"e": 33219,
"s": 33133,
"text": "Another way to create a table in HANA database is by using GUI option in HANA Studio."
},
{
"code": null,
"e": 33319,
"s": 33219,
"text": "Right Click on Table tab under Schema → Select ‘New Table’ option as shown in snapshot given below."
},
{
"code": null,
"e": 33497,
"s": 33319,
"text": "Once you click on New Table → It will open a window to enter the Table name, Choose Schema name from drop down, Define Table type from drop down list: Column Store or Row Store."
},
{
"code": null,
"e": 33699,
"s": 33497,
"text": "Define data type as shown below. Columns can be added by clicking on + sign, Primary Key can be chosen by clicking on cell under Primary key in front of Column name, Not Null will be active by default."
},
{
"code": null,
"e": 33741,
"s": 33699,
"text": "Once columns are added, click on Execute."
},
{
"code": null,
"e": 33970,
"s": 33741,
"text": "Once you Execute (F8), Right Click on Table Tab → Refresh. New Table will be reflected in the list of tables under chosen Schema. Below Insert Option can be used to insert data in table. Select statement to see content of table."
},
{
"code": null,
"e": 34118,
"s": 33970,
"text": "You can right click on Table name and use Open Data Definition to see data type of the table. Open Data Preview/Open Content to see table contents."
},
{
"code": null,
"e": 34329,
"s": 34118,
"text": "To use tables from one Schema to create views we should provide access on the Schema to the default user who runs all the Views in HANA Modeling. This can be done by going to SQL editor and running this query −"
},
{
"code": null,
"e": 34399,
"s": 34329,
"text": "GRANT SELECT ON SCHEMA \"<SCHEMA_NAME>\" TO _SYS_REPO WITH GRANT OPTION"
},
{
"code": null,
"e": 34505,
"s": 34399,
"text": "SAP HANA Packages are shown under Content tab in HANA studio. All HANA modeling is saved inside Packages."
},
{
"code": null,
"e": 34580,
"s": 34505,
"text": "You can create a new Package by Right Click on Content Tab → New → Package"
},
{
"code": null,
"e": 34821,
"s": 34580,
"text": "You can also create a Sub Package under a Package by right clicking on the Package name. When we right click on the Package we get 7 Options: We can create HANA Views Attribute Views, Analytical Views, and Calculation Views under a Package."
},
{
"code": null,
"e": 34919,
"s": 34821,
"text": "You can also create Decision Table, Define Analytic Privilege and create Procedures in a Package."
},
{
"code": null,
"e": 35086,
"s": 34919,
"text": "When you right click on Package and click on New, you can also create sub packages in a Package. You have to enter Package Name, Description while creating a Package."
},
{
"code": null,
"e": 35384,
"s": 35086,
"text": "Attribute Views in SAP HANA Modeling are created on the top of Dimension tables. They are used to join Dimension tables or other Attribute Views. You can also copy a new Attribute View from already existing Attribute Views inside other Packages but that doesn’t let you change the View Attributes."
},
{
"code": null,
"e": 35468,
"s": 35384,
"text": "Attribute Views in HANA are used to join Dimension tables or other Attribute Views."
},
{
"code": null,
"e": 35552,
"s": 35468,
"text": "Attribute Views in HANA are used to join Dimension tables or other Attribute Views."
},
{
"code": null,
"e": 35647,
"s": 35552,
"text": "Attribute Views are used in Analytical and Calculation Views for analysis to pass master data."
},
{
"code": null,
"e": 35742,
"s": 35647,
"text": "Attribute Views are used in Analytical and Calculation Views for analysis to pass master data."
},
{
"code": null,
"e": 35809,
"s": 35742,
"text": "They are similar to Characteristics in BM and contain master data."
},
{
"code": null,
"e": 35876,
"s": 35809,
"text": "They are similar to Characteristics in BM and contain master data."
},
{
"code": null,
"e": 36081,
"s": 35876,
"text": "Attribute Views are used for performance optimization in large size Dimension tables, you can limit the number of attributes in an Attribute View which are further used for Reporting and analysis purpose."
},
{
"code": null,
"e": 36286,
"s": 36081,
"text": "Attribute Views are used for performance optimization in large size Dimension tables, you can limit the number of attributes in an Attribute View which are further used for Reporting and analysis purpose."
},
{
"code": null,
"e": 36354,
"s": 36286,
"text": "Attribute Views are used to model master data to give some context."
},
{
"code": null,
"e": 36422,
"s": 36354,
"text": "Attribute Views are used to model master data to give some context."
},
{
"code": null,
"e": 36548,
"s": 36422,
"text": "Choose the Package name under which you want to create an Attribute View. Right Click on Package → Go to New → Attribute View"
},
{
"code": null,
"e": 36788,
"s": 36548,
"text": "When you click on Attribute View, New Window will open. Enter Attribute View name and description. From the drop down list, choose View Type and sub type. In sub type, there are three types of Attribute views − Standard, Time, and Derived."
},
{
"code": null,
"e": 37004,
"s": 36788,
"text": "Time subtype Attribute View is a special type of Attribute view that adds a Time Dimension to Data Foundation. When you enter the Attribute name, Type and Subtype and click on Finish, it will open three work panes −"
},
{
"code": null,
"e": 37063,
"s": 37004,
"text": "Scenario pane that has Data Foundation and Semantic Layer."
},
{
"code": null,
"e": 37122,
"s": 37063,
"text": "Scenario pane that has Data Foundation and Semantic Layer."
},
{
"code": null,
"e": 37216,
"s": 37122,
"text": "Details Pane shows attribute of all tables added to Data Foundation and joining between them."
},
{
"code": null,
"e": 37310,
"s": 37216,
"text": "Details Pane shows attribute of all tables added to Data Foundation and joining between them."
},
{
"code": null,
"e": 37392,
"s": 37310,
"text": "Output pane where we can add attributes from Detail pane to filter in the report."
},
{
"code": null,
"e": 37474,
"s": 37392,
"text": "Output pane where we can add attributes from Detail pane to filter in the report."
},
{
"code": null,
"e": 37685,
"s": 37474,
"text": "You can add Objects to Data Foundation, by clicking on ‘+’ sign written next to Data Foundation. You can add multiple Dimension tables and Attribute Views in the Scenario Pane and join them using a Primary Key."
},
{
"code": null,
"e": 37970,
"s": 37685,
"text": "When you click on Add Object in Data Foundation, you will get a search bar from where you can add Dimension tables and Attribute views to Scenario Pane. Once Tables or Attribute Views are added to Data Foundation, they can be joined using a Primary Key in Details Pane as shown below."
},
{
"code": null,
"e": 38190,
"s": 37970,
"text": "Once joining is done, choose multiple attributes in details pane, right click and Add to Output. All columns will be added to Output pane. Now Click on Activate option and you will get a confirmation message in job log."
},
{
"code": null,
"e": 38261,
"s": 38190,
"text": "Now you can right click on the Attribute View and go for Data Preview."
},
{
"code": null,
"e": 38437,
"s": 38261,
"text": "Note − When a View is not activated, it has diamond mark on it. However, once you activate it, that diamond disappears that confirms that View has been activated successfully."
},
{
"code": null,
"e": 38561,
"s": 38437,
"text": "Once you click on Data Preview, it will show all the attributes that has been added to Output pane under Available Objects."
},
{
"code": null,
"e": 38683,
"s": 38561,
"text": "These Objects can be added to Labels and Value axis by right click and adding or by dragging the objects as shown below −"
},
{
"code": null,
"e": 38966,
"s": 38683,
"text": "Analytic View is in the form of Star schema, wherein we join one Fact table to multiple Dimension tables. Analytic views use real power of SAP HANA to perform complex calculations and aggregate functions by joining tables in form of star schema and by executing Star schema queries."
},
{
"code": null,
"e": 39023,
"s": 38966,
"text": "Following are the properties of SAP HANA Analytic View −"
},
{
"code": null,
"e": 39135,
"s": 39023,
"text": "Analytic Views are used to perform complex calculations and Aggregate functions like Sum, Count, Min, Max, Etc."
},
{
"code": null,
"e": 39247,
"s": 39135,
"text": "Analytic Views are used to perform complex calculations and Aggregate functions like Sum, Count, Min, Max, Etc."
},
{
"code": null,
"e": 39304,
"s": 39247,
"text": "Analytic Views are designed to run Start schema queries."
},
{
"code": null,
"e": 39361,
"s": 39304,
"text": "Analytic Views are designed to run Start schema queries."
},
{
"code": null,
"e": 39505,
"s": 39361,
"text": "Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains primary key for each Dim table and measures."
},
{
"code": null,
"e": 39649,
"s": 39505,
"text": "Each Analytic View has one Fact table surrounded by multiple dimension tables. Fact table contains primary key for each Dim table and measures."
},
{
"code": null,
"e": 39717,
"s": 39649,
"text": "Analytic Views are similar to Info Objects and Info sets of SAP BW."
},
{
"code": null,
"e": 39785,
"s": 39717,
"text": "Analytic Views are similar to Info Objects and Info sets of SAP BW."
},
{
"code": null,
"e": 40053,
"s": 39785,
"text": "Choose the Package name under which you want to create an Analytic View. Right Click on Package → Go to New → Analytic View. When you click on an Analytic View, New Window will open. Enter View name and Description and from drop down list choose View Type and Finish."
},
{
"code": null,
"e": 40148,
"s": 40053,
"text": "When you click Finish, you can see an Analytic View with Data Foundation and Star Join option."
},
{
"code": null,
"e": 40250,
"s": 40148,
"text": "Click on Data Foundation to add Dimension and Fact tables. Click on Star Join to add Attribute Views."
},
{
"code": null,
"e": 40522,
"s": 40250,
"text": "Add Dim and Fact tables to Data Foundation using “+” sign. In the example given below, 3 dim tables have been added: DIM_CUSTOMER, DIM_PRODUCT, DIM_REGION and 1 Fact table FCT_SALES to Details Pane. Joining Dim table to Fact table using Primary Keys stored in Fact table."
},
{
"code": null,
"e": 40684,
"s": 40522,
"text": "Select Attributes from Dim and Fact table to add to Output pane as shown in snapshot shown above. Now change the data type of Facts, from fact table to measures."
},
{
"code": null,
"e": 40818,
"s": 40684,
"text": "Click on Semantic layer, choose facts and click on measures sign as shown below to change datatype to measures and Activate the View."
},
{
"code": null,
"e": 41025,
"s": 40818,
"text": "Once you activate view and click on Data Preview, all attributes and measures will be added under the list of Available objects. Add Attributes to Labels Axis and Measure to Value axis for analysis purpose."
},
{
"code": null,
"e": 41091,
"s": 41025,
"text": "There is an option to choose different types of chart and graphs."
},
{
"code": null,
"e": 41304,
"s": 41091,
"text": "Calculation Views are used to consume other Analytic, Attribute and other Calculation views and base column tables. These are used to perform complex calculations, which are not possible with other type of Views."
},
{
"code": null,
"e": 41363,
"s": 41304,
"text": "Below given are few characteristics of Calculation Views −"
},
{
"code": null,
"e": 41450,
"s": 41363,
"text": "Calculation Views are used to consume Analytic, Attribute and other Calculation Views."
},
{
"code": null,
"e": 41537,
"s": 41450,
"text": "Calculation Views are used to consume Analytic, Attribute and other Calculation Views."
},
{
"code": null,
"e": 41625,
"s": 41537,
"text": "They are used to perform complex calculations, which are not possible with other Views."
},
{
"code": null,
"e": 41713,
"s": 41625,
"text": "They are used to perform complex calculations, which are not possible with other Views."
},
{
"code": null,
"e": 41793,
"s": 41713,
"text": "There are two ways to create Calculation Views- SQL Editor or Graphical Editor."
},
{
"code": null,
"e": 41873,
"s": 41793,
"text": "There are two ways to create Calculation Views- SQL Editor or Graphical Editor."
},
{
"code": null,
"e": 41927,
"s": 41873,
"text": "Built-in Union, Join, Projection & Aggregation nodes."
},
{
"code": null,
"e": 41981,
"s": 41927,
"text": "Built-in Union, Join, Projection & Aggregation nodes."
},
{
"code": null,
"e": 42169,
"s": 41981,
"text": "Choose the Package name under which you want to create a Calculation View. Right Click on Package → Go to New → Calculation View. When you click on Calculation View, New Window will open."
},
{
"code": null,
"e": 42393,
"s": 42169,
"text": "Enter View name, Description and choose view type as Calculation View, Subtype Standard or Time (this is special kind of View which adds time dimension). You can use two types of Calculation View − Graphical and SQL Script."
},
{
"code": null,
"e": 42537,
"s": 42393,
"text": "It has default nodes like aggregation, Projection, Join and Union. It is used to consume other Attribute, Analytic and other Calculation views."
},
{
"code": null,
"e": 42624,
"s": 42537,
"text": "It is written in SQL scripts that are built on SQL commands or HANA defined functions."
},
{
"code": null,
"e": 42714,
"s": 42624,
"text": "Cube, in this default node, is Aggregation. You can choose Star join with Cube dimension."
},
{
"code": null,
"e": 42761,
"s": 42714,
"text": "Dimension, in this default node is Projection."
},
{
"code": null,
"e": 43025,
"s": 42761,
"text": "It does not allow base column tables, Attribute Views or Analytic views to add at data foundation. All Dimension tables must be changed to Dimension Calculation views to use in Star Join. All Fact tables can be added and can use default nodes in Calculation View."
},
{
"code": null,
"e": 43102,
"s": 43025,
"text": "The following example shows how we can use Calculation View with Star join −"
},
{
"code": null,
"e": 43260,
"s": 43102,
"text": "You have four tables, two Dim tables, and two Fact tables. You have to find list of all employees with their Joining date, Emp Name, empId, Salary and Bonus."
},
{
"code": null,
"e": 43319,
"s": 43260,
"text": "Copy and paste the below script in SQL editor and execute."
},
{
"code": null,
"e": 43351,
"s": 43319,
"text": "Dim Tables − Empdim and Empdate"
},
{
"code": null,
"e": 43546,
"s": 43351,
"text": "Create column table Empdim (empId nvarchar(3),Empname nvarchar(100));\nInsert into Empdim values('AA1','John');\nInsert into Empdim values('BB1','Anand');\nInsert into Empdim values('CC1','Jason');"
},
{
"code": null,
"e": 43789,
"s": 43546,
"text": "Create column table Empdate (caldate date, CALMONTH nvarchar(4) ,CALYEAR nvarchar(4));\nInsert into Empdate values('20100101','04','2010');\nInsert into Empdate values('20110101','05','2011');\nInsert into Empdate values('20120101','06','2012');"
},
{
"code": null,
"e": 43822,
"s": 43789,
"text": "Fact Tables − Empfact1, Empfact2"
},
{
"code": null,
"e": 44058,
"s": 43822,
"text": "Create column table Empfact1 (empId nvarchar(3), Empdate date, Sal integer );\nInsert into Empfact1 values('AA1','20100101',5000);\nInsert into Empfact1 values('BB1','20110101',10000);\nInsert into Empfact1 values('CC1','20120101',12000);"
},
{
"code": null,
"e": 44298,
"s": 44058,
"text": "Create column table Empfact2 (empId nvarchar(3), deptName nvarchar(20), Bonus integer );\nInsert into Empfact2 values ('AA1','SAP', 2000);\nInsert into Empfact2 values ('BB1','Oracle', 2500);\nInsert into Empfact2 values ('CC1','JAVA', 1500);"
},
{
"code": null,
"e": 44416,
"s": 44298,
"text": "Now we have to implement Calculation View with Star Join. First change both Dim tables to Dimension Calculation View."
},
{
"code": null,
"e": 44611,
"s": 44416,
"text": "Create a Calculation View with Star Join. In Graphical pane, add 2 Projections for 2 Fact tables. Add both fact tables to both Projections and add attributes of these Projections to Output pane."
},
{
"code": null,
"e": 44715,
"s": 44611,
"text": "Add a join from default node and join both the fact tables. Add parameters of Fact Join to output pane."
},
{
"code": null,
"e": 44868,
"s": 44715,
"text": "In Star Join, add both- Dimension Calculation views and add Fact Join to Star Join as shown below. Choose parameters in Output pane and active the View."
},
{
"code": null,
"e": 45032,
"s": 44868,
"text": "Once view is activated successfully, right click on view name and click on Data Preview. Add attributes and measures to values and labels axis and do the analysis."
},
{
"code": null,
"e": 45179,
"s": 45032,
"text": "It simplifies the design process. You need not to create Analytical views and Attribute Views and directly Fact tables can be used as Projections."
},
{
"code": null,
"e": 45211,
"s": 45179,
"text": "3NF is possible with Star Join."
},
{
"code": null,
"e": 45292,
"s": 45211,
"text": "Create 2 Attribute Views on 2 Dim tables-Add output and activate both the views."
},
{
"code": null,
"e": 45413,
"s": 45292,
"text": "Create 2 Analytical Views on Fact Tables → Add both Attribute views and Fact1/Fact2 at Data Foundation in Analytic view."
},
{
"code": null,
"e": 45617,
"s": 45413,
"text": "Now Create a Calculation View → Dimension (Projection). Create Projections of both Analytical Views and Join them. Add attributes of this Join to output pane. Now Join to Projection and add output again."
},
{
"code": null,
"e": 45683,
"s": 45617,
"text": "Activate the view successful and go to Data preview for analysis."
},
{
"code": null,
"e": 45871,
"s": 45683,
"text": "Analytic Privileges are used to limit access on HANA Information views. You can assign different types of right to different users on different component of a View in Analytic Privileges."
},
{
"code": null,
"e": 46020,
"s": 45871,
"text": "Sometimes, it is required that data in the same view should not be accessible to other users who do not have any relevant requirement for that data."
},
{
"code": null,
"e": 46338,
"s": 46020,
"text": "Suppose you have an Analytic view EmpDetails that has details about employees of a company- Emp name, Emp Id, Dept, Salary, Date of Joining, Emp logon, etc. Now if you do not want your Report developer to see Salary details or Emp logon details of all employees, you can hide this by using Analytic privileges option."
},
{
"code": null,
"e": 46479,
"s": 46338,
"text": "Analytic Privileges are only applied to attributes in an Information View. We cannot add measures to restrict access in Analytic privileges."
},
{
"code": null,
"e": 46620,
"s": 46479,
"text": "Analytic Privileges are only applied to attributes in an Information View. We cannot add measures to restrict access in Analytic privileges."
},
{
"code": null,
"e": 46703,
"s": 46620,
"text": "Analytic Privileges are used to control read access on SAP HANA Information views."
},
{
"code": null,
"e": 46786,
"s": 46703,
"text": "Analytic Privileges are used to control read access on SAP HANA Information views."
},
{
"code": null,
"e": 46902,
"s": 46786,
"text": "So we can restrict data by Empname, EmpId, Emp logon or by Emp Dept and not by numerical values like salary, bonus."
},
{
"code": null,
"e": 47012,
"s": 46902,
"text": "Right Click on Package name and go to new Analytic Privilege or you can open using HANA Modeler quick launch."
},
{
"code": null,
"e": 47093,
"s": 47012,
"text": "Enter name and Description of Analytic Privilege → Finish. New window will open."
},
{
"code": null,
"e": 47259,
"s": 47093,
"text": "You can click on Next button and add Modeling view in this window before you click on finish. There is also an option to copy an existing Analytic Privilege package."
},
{
"code": null,
"e": 47339,
"s": 47259,
"text": "Once you click on Add button, it will show you all the views under Content tab."
},
{
"code": null,
"e": 47468,
"s": 47339,
"text": "Choose View that you want to add to Analytic Privilege package and click OK. Selected View will be added under reference models."
},
{
"code": null,
"e": 47603,
"s": 47468,
"text": "Now to add attributes from selected view under Analytic Privilege, click on add button with Associated Attributes Restrictions window."
},
{
"code": null,
"e": 47697,
"s": 47603,
"text": "Add objects you want to add to Analytic privileges from select object option and click on OK."
},
{
"code": null,
"e": 47890,
"s": 47697,
"text": "In Assign Restriction option, it allows you to add values you want to hide in Modeling View from specific user. You can add Object value that will not reflect in Data Preview of Modeling View."
},
{
"code": null,
"e": 48111,
"s": 47890,
"text": "We have to activate Analytic Privilege now, by clicking on Green round icon at top. Status message – completed successfully confirms activation successfully under job log and we can use this view now by adding to a role."
},
{
"code": null,
"e": 48237,
"s": 48111,
"text": "Now to add this role to a user, go to security tab → User → Select User on which you want to apply these Analytic privileges."
},
{
"code": null,
"e": 48376,
"s": 48237,
"text": "Search Analytic Privilege you want to apply with the name and click on OK. That view will be added to user role under Analytic Privileges."
},
{
"code": null,
"e": 48543,
"s": 48376,
"text": "To delete Analytic Privileges from specific user, select view under tab and use Red delete option. Use Deploy (arrow mark at top or F8 to apply this to user profile)."
},
{
"code": null,
"e": 48772,
"s": 48543,
"text": "SAP HANA Information Composer is a self-service modeling environment for end users to analyze data set. It allows you to import data from workbook format (.xls, .csv) into HANA database and to create Modeling views for analysis."
},
{
"code": null,
"e": 49121,
"s": 48772,
"text": "Information Composer is very different from HANA Modeler and both are designed to target separate set of users. Technically sound people who have strong experience in data modeling use HANA Modeler. A business user, who does not have any technical knowledge, uses Information Composer. It provides simple functionalities with easy to use interface."
},
{
"code": null,
"e": 49285,
"s": 49121,
"text": "Data extraction − Information Composer helps to extract data, clean data, preview data and automate the process of creation of physical table in the HANA database."
},
{
"code": null,
"e": 49449,
"s": 49285,
"text": "Data extraction − Information Composer helps to extract data, clean data, preview data and automate the process of creation of physical table in the HANA database."
},
{
"code": null,
"e": 49739,
"s": 49449,
"text": "Manipulating data − It helps us to combine two objects (Physical tables, Analytical View, attribute view and calculation views) and create information view that can be consumed by SAP BO Tools like SAP Business Objects Analysis, SAP Business Objects Explorer and other tools like MS Excel."
},
{
"code": null,
"e": 50029,
"s": 49739,
"text": "Manipulating data − It helps us to combine two objects (Physical tables, Analytical View, attribute view and calculation views) and create information view that can be consumed by SAP BO Tools like SAP Business Objects Analysis, SAP Business Objects Explorer and other tools like MS Excel."
},
{
"code": null,
"e": 50123,
"s": 50029,
"text": "It provides a centralized IT service in the form of URL, which can be accessed from anywhere."
},
{
"code": null,
"e": 50217,
"s": 50123,
"text": "It provides a centralized IT service in the form of URL, which can be accessed from anywhere."
},
{
"code": null,
"e": 50324,
"s": 50217,
"text": "It allows us to upload large amount of data (up to 5 million cells). Link to access Information Composer −"
},
{
"code": null,
"e": 50350,
"s": 50324,
"text": "http://<server>:<port>/IC"
},
{
"code": null,
"e": 50452,
"s": 50350,
"text": "Login to SAP HANA Information Composer. You can perform data loading or manipulation using this tool."
},
{
"code": null,
"e": 50498,
"s": 50452,
"text": "To upload data this can be done in two ways −"
},
{
"code": null,
"e": 50550,
"s": 50498,
"text": "Uploading .xls, .csv file directly to HANA database"
},
{
"code": null,
"e": 50627,
"s": 50550,
"text": "Other way is to copy data to clipboard and copy from there to HANA database."
},
{
"code": null,
"e": 50674,
"s": 50627,
"text": "It allows data to be loaded along with header."
},
{
"code": null,
"e": 50737,
"s": 50674,
"text": "On Left side in Information Composer, you have three options −"
},
{
"code": null,
"e": 50785,
"s": 50737,
"text": "Select Source of data → Classify data → Publish"
},
{
"code": null,
"e": 50928,
"s": 50785,
"text": "Once data is published to HANA database, you cannot rename the table. In this case, you have to delete the table from Schema in HANA database."
},
{
"code": null,
"e": 51066,
"s": 50928,
"text": "“SAP_IC” schema, where tables like IC_MODELS, IC_SPREADSHEETS exists. One can find details of tables created using IC under these tables."
},
{
"code": null,
"e": 51411,
"s": 51066,
"text": "Another way to upload data in IC is by use of the clipboard. Copy the data to clipboard and upload it with help of Information Composer. Information Composer also allows you to see preview of data or even provide summary of data in temporary storage. It has inbuilt capability of data cleansing that is used to remove any inconsistency in data."
},
{
"code": null,
"e": 51550,
"s": 51411,
"text": "Once data is cleansed, you need to classify data whether it is attributed. IC has inbuilt feature to check the data type of uploaded data."
},
{
"code": null,
"e": 51720,
"s": 51550,
"text": "Final step is to publish the data to physical tables in HANA database. Provide a technical name and description of table and this will be loaded inside IC_Tables Schema."
},
{
"code": null,
"e": 51783,
"s": 51720,
"text": "Two set of users can be defined to use data published from IC."
},
{
"code": null,
"e": 51874,
"s": 51783,
"text": "IC_MODELER is for creating physical tables, uploading data and creating information views."
},
{
"code": null,
"e": 51965,
"s": 51874,
"text": "IC_MODELER is for creating physical tables, uploading data and creating information views."
},
{
"code": null,
"e": 52124,
"s": 51965,
"text": "IC_PUBLIC allows users to view information views created by other users. This role does not allow the user to upload or create any information views using IC."
},
{
"code": null,
"e": 52283,
"s": 52124,
"text": "IC_PUBLIC allows users to view information views created by other users. This role does not allow the user to upload or create any information views using IC."
},
{
"code": null,
"e": 52305,
"s": 52283,
"text": "Server Requirements −"
},
{
"code": null,
"e": 52348,
"s": 52305,
"text": "At least 2GB of available RAM is required."
},
{
"code": null,
"e": 52391,
"s": 52348,
"text": "At least 2GB of available RAM is required."
},
{
"code": null,
"e": 52440,
"s": 52391,
"text": "Java 6 (64-bit) must be installed on the server."
},
{
"code": null,
"e": 52489,
"s": 52440,
"text": "Java 6 (64-bit) must be installed on the server."
},
{
"code": null,
"e": 52573,
"s": 52489,
"text": "The Information Composer Server must be physically located next to the HANA server."
},
{
"code": null,
"e": 52657,
"s": 52573,
"text": "The Information Composer Server must be physically located next to the HANA server."
},
{
"code": null,
"e": 52679,
"s": 52657,
"text": "Client Requirements −"
},
{
"code": null,
"e": 52727,
"s": 52679,
"text": "Internet Explorer with Silverlight 4 installed."
},
{
"code": null,
"e": 53011,
"s": 52727,
"text": "HANA Export and Import option allows tables, Information models, Landscapes to move to a different or existing system. You do not need to recreate all tables and information models as you can simply export it to new system or import to an existing target system to reduce the effort."
},
{
"code": null,
"e": 53136,
"s": 53011,
"text": "This option can be accessed from File menu at the top or by right clicking on any table or Information model in HANA studio."
},
{
"code": null,
"e": 53201,
"s": 53136,
"text": "Go to file menu → Export → You will see options as shown below −"
},
{
"code": null,
"e": 53393,
"s": 53201,
"text": "Delivery unit is a single unit, which can be mapped to multiple packages and can be exported as single entity so that all the packages assigned to Delivery Unit can be treated as single unit."
},
{
"code": null,
"e": 53559,
"s": 53393,
"text": "Users can use this option to export all the packages that make a delivery unit and the relevant objects contained in it to a HANA Server or to local Client location."
},
{
"code": null,
"e": 53615,
"s": 53559,
"text": "The user should create Delivery Unit prior to using it."
},
{
"code": null,
"e": 53793,
"s": 53615,
"text": "This can be done through HANA Modeler → Delivery Unit → Select System and Next → Create → Fill the details like Name, Version, etc. → OK → Add Packages to Delivery unit → Finish"
},
{
"code": null,
"e": 53923,
"s": 53793,
"text": "Once the Delivery Unit is created and the packages are assigned to it, user can see the list of packages by using Export option −"
},
{
"code": null,
"e": 53986,
"s": 53923,
"text": "Go to File → Export → Delivery Unit →Select the Delivery Unit."
},
{
"code": null,
"e": 54093,
"s": 53986,
"text": "You can see list of all packages assigned to Delivery unit. It gives an option to choose export location −"
},
{
"code": null,
"e": 54110,
"s": 54093,
"text": "Export to Server"
},
{
"code": null,
"e": 54127,
"s": 54110,
"text": "Export to Client"
},
{
"code": null,
"e": 54225,
"s": 54127,
"text": "You can export the Delivery Unit either to HANA Server location or to a Client location as shown."
},
{
"code": null,
"e": 54390,
"s": 54225,
"text": "The user can restrict the export through “Filter by time” which means Information views, which are updated within the mentioned time interval will only be exported."
},
{
"code": null,
"e": 54536,
"s": 54390,
"text": "Select the Delivery Unit and Export Location and then Click Next → Finish. This will export the selected Delivery Unit to the specified location."
},
{
"code": null,
"e": 54755,
"s": 54536,
"text": "This option can be used to export individual objects to a location in the local system. User can select single Information view or group of Views and Packages and select the local Client location for export and Finish."
},
{
"code": null,
"e": 54792,
"s": 54755,
"text": "This is shown in the snapshot below."
},
{
"code": null,
"e": 54910,
"s": 54792,
"text": "This can be used to export the objects along with the data for SAP support purposes. This can be used when requested."
},
{
"code": null,
"e": 55124,
"s": 54910,
"text": "Example − User creates an Information View, which throws an error and he is not able to resolve. In that case, he can use this option to export the view along with data and share it with SAP for debugging purpose."
},
{
"code": null,
"e": 55163,
"s": 55124,
"text": "Export Options under SAP HANA Studio −"
},
{
"code": null,
"e": 55225,
"s": 55163,
"text": "Landscape − To export the landscape from one system to other."
},
{
"code": null,
"e": 55299,
"s": 55225,
"text": "Tables − This option can be used to export tables along with its content."
},
{
"code": null,
"e": 55378,
"s": 55299,
"text": "Go to File → Import, You will see all the options as shown below under Import."
},
{
"code": null,
"e": 55447,
"s": 55378,
"text": "This is used to import data from a flat file like .xls or .csv file."
},
{
"code": null,
"e": 55510,
"s": 55447,
"text": "Click on Nex → Choose Target System → Define Import Properties"
},
{
"code": null,
"e": 55747,
"s": 55510,
"text": "Select Source file by browsing local system. It also gives an option if you want to keep the header row. It also gives an option to create a new table under existing Schema or if you want to import data from a file to an existing table."
},
{
"code": null,
"e": 55935,
"s": 55747,
"text": "When you click on Next, it gives an option to define Primary Key, change data type of columns, define storage type of table and also, allows you to change the proposed structure of table."
},
{
"code": null,
"e": 56145,
"s": 55935,
"text": "When you click on finish, that table will be populated under list of tables in mentioned Schema. You can do the data preview and can check data definition of the table and it will be same as that of .xls file."
},
{
"code": null,
"e": 56255,
"s": 56145,
"text": "Select Delivery unit by going to File → Import → Delivery unit. You can choose from a server or local client."
},
{
"code": null,
"e": 56566,
"s": 56255,
"text": "You can select “Overwrite inactive versions” which allows you to overwrite any inactive version of objects that exist. If the user selects “Activate objects”, then after the import, all the imported objects will be activated by default. The user need not trigger the activation manually for the imported views."
},
{
"code": null,
"e": 56651,
"s": 56566,
"text": "Click Finish and once completed successfully, it will be populated to target system."
},
{
"code": null,
"e": 56843,
"s": 56651,
"text": "Browse for the Local Client location where the views are exported and select the views to be imported, the user can select individual Views or group of Views and Packages and Click on Finish."
},
{
"code": null,
"e": 56937,
"s": 56843,
"text": "Go to File → Import → Mass Import of Metadata → Next and select the source and target system."
},
{
"code": null,
"e": 56992,
"s": 56937,
"text": "Configure the System for Mass Import and click Finish."
},
{
"code": null,
"e": 57084,
"s": 56992,
"text": "It allows you to choose tables and target schema to import Meta data from SAP Applications."
},
{
"code": null,
"e": 57142,
"s": 57084,
"text": "Go to File → Import → Selective Import of Metadata → Next"
},
{
"code": null,
"e": 57295,
"s": 57142,
"text": "Choose Source Connection of type “SAP Applications”. Remember that the Data Store should have been created already of type SAP Applications → Click Next"
},
{
"code": null,
"e": 57384,
"s": 57295,
"text": "Select tables you want to import and validate data if required. Click Finish after that."
},
{
"code": null,
"e": 57716,
"s": 57384,
"text": "We know that with the use of Information Modeling feature in SAP HANA, we can create different Information views Attribute Views, Analytic Views, Calculation views. These Views can be consumed by different reporting tools like SAP Business Object, SAP Lumira, Design Studio, Office Analysis and even third party tool like MS Excel."
},
{
"code": null,
"e": 57934,
"s": 57716,
"text": "These reporting tools enable Business Managers, Analysts, Sales Managers and senior management employees to analyze the historic information to create business scenarios and to decide business strategy of the company."
},
{
"code": null,
"e": 58105,
"s": 57934,
"text": "This generates the need for consuming HANA Modeling views by different reporting tools and to generate reports and dashboards, which are easy to understand for end users."
},
{
"code": null,
"e": 58419,
"s": 58105,
"text": "In most of the companies, where SAP is implemented, reporting on HANA is done with BI platforms tools that consume both SQL and MDX queries with help of Relational and OLAP connections. There is wide variety of BI tools like − Web Intelligence, Crystal Reports, Dashboard, Explorer, Office Analysis and many more."
},
{
"code": null,
"e": 58827,
"s": 58419,
"text": "Web Intelligence and Crystal Reports are most common BI tools that are used for reporting. WebI uses a semantic layer called Universe to connect to data source and these Universes are used for reporting in tool. These Universes are designed with the help of Universe design tool UDT or with Information Design tool IDT. IDT supports multisource enabled data source. However, UDT only supports Single source."
},
{
"code": null,
"e": 59160,
"s": 58827,
"text": "Main tools that are used for designing interactive dashboards- Design Studio and Dashboard Designer. Design Studio is future tool for designing dashboard, which consumes HANA views via BI consumer Service BICS connection. Dashboard design (xcelsius) uses IDT to consume schemas in HANA database with a Relational or OLAP connection."
},
{
"code": null,
"e": 59339,
"s": 59160,
"text": "SAP Lumira has an inbuilt feature of directly connecting or loading data from HANA database. HANA views can be directly consumed in Lumira for visualization and creating stories."
},
{
"code": null,
"e": 59468,
"s": 59339,
"text": "Office Analysis uses an OLAP connection to connect to HANA Information views. This OLAP connection can be created in CMC or IDT."
},
{
"code": null,
"e": 59739,
"s": 59468,
"text": "In the picture given above, it shows all BI tools with solid lines, which can be directly connected and integrated with SAP HANA using an OLAP connection. It also depicts tools, which need a relational connection using IDT to connect to HANA are shown with dotted lines."
},
{
"code": null,
"e": 60041,
"s": 59739,
"text": "The idea is basically if you need to access data from a table or a conventional database then your connection should be a relational connection but if your source is an application and data is stored in cube (multidimensional like Info cubes, Information models) then you would use an OLAP connection."
},
{
"code": null,
"e": 60097,
"s": 60041,
"text": "A Relational connection can only be created in IDT/UDT."
},
{
"code": null,
"e": 60141,
"s": 60097,
"text": "An OLAP can be created in both IDT and CMC."
},
{
"code": null,
"e": 60309,
"s": 60141,
"text": "Another thing to note is that a relational connection always produces a SQL statement to be fired from report while an OLAP connection normally creates a MDX statement"
},
{
"code": null,
"e": 60579,
"s": 60309,
"text": "In Information design tool (IDT), you can create a relational connection to an SAP HANA view or table using JDBC or ODBC drivers and build a Universe using this connection to provide access to client tools like Dashboards and Web Intelligence as shown in above picture."
},
{
"code": null,
"e": 60654,
"s": 60579,
"text": "You can create a direct connection to SAP HANA using JDBC or ODBC drivers."
},
{
"code": null,
"e": 60804,
"s": 60654,
"text": "In Crystal Reports for Enterprise, you can access SAP HANA data by using an existing relational connection created using the information design tool."
},
{
"code": null,
"e": 60908,
"s": 60804,
"text": "You can also connect to SAP HANA using an OLAP connection created using information design tool or CMC."
},
{
"code": null,
"e": 61053,
"s": 60908,
"text": "Design Studio can access SAP HANA data by using an existing OLAP connection created in Information design tool or CMC same like Office Analysis."
},
{
"code": null,
"e": 61245,
"s": 61053,
"text": "Dashboards can connect to SAP HANA only through a relational Universe. Customers using Dashboards on top of SAP HANA should strongly consider building their new dashboards with Design Studio."
},
{
"code": null,
"e": 61322,
"s": 61245,
"text": "Web Intelligence can connect to SAP HANA only through a Relational Universe."
},
{
"code": null,
"e": 61479,
"s": 61322,
"text": "Lumira can connect directly to SAP HANA Analytic and Calculation views. It can also connect to SAP HANA through SAP BI Platform using a relational Universe."
},
{
"code": null,
"e": 61642,
"s": 61479,
"text": "In Office Analysis edition for OLAP, you can connect to SAP HANA using an OLAP connection defined in the Central Management Console or in Information design tool."
},
{
"code": null,
"e": 61724,
"s": 61642,
"text": "You can create an information space based on an SAP HANA view using JDBC drivers."
},
{
"code": null,
"e": 61994,
"s": 61724,
"text": "We can create an OLAP Connection for all the BI tools, which we want to use on top of HANA views like OLAP for analysis, Crystal Report for enterprise, Design Studio. Relational connection through IDT is used to connect Web Intelligence and Dashboards to HANA database."
},
{
"code": null,
"e": 62104,
"s": 61994,
"text": "These connection can be created using IDT as well CMC and both of the connections are saved in BO Repository."
},
{
"code": null,
"e": 62150,
"s": 62104,
"text": "Login to CMC with the user name and password."
},
{
"code": null,
"e": 62334,
"s": 62150,
"text": "From the dropdown list of connections, choose an OLAP connection. It will also show already created connections in CMC. To create a new connection, go to green icon and click on this."
},
{
"code": null,
"e": 62489,
"s": 62334,
"text": "Enter the name of an OLAP connection and description. Multiple persons, to connect to HANA views, in different BI Platform tools, can use this connection."
},
{
"code": null,
"e": 62509,
"s": 62489,
"text": "Provider − SAP HANA"
},
{
"code": null,
"e": 62541,
"s": 62509,
"text": "Server − Enter HANA Server name"
},
{
"code": null,
"e": 62568,
"s": 62541,
"text": "Instance − Instance number"
},
{
"code": null,
"e": 62720,
"s": 62568,
"text": "It also gives an option to connect to a single Cube (You can also choose to connect to single Analytic or Calculation view) or to the full HANA system."
},
{
"code": null,
"e": 62798,
"s": 62720,
"text": "Click on Connect and choose modeling view by entering user name and password."
},
{
"code": null,
"e": 62906,
"s": 62798,
"text": "Authentication Types − Three types of Authentication are possible while creating an OLAP connection in CMC."
},
{
"code": null,
"e": 62993,
"s": 62906,
"text": "Predefined − It will not ask user name and password again while using this connection."
},
{
"code": null,
"e": 63080,
"s": 62993,
"text": "Predefined − It will not ask user name and password again while using this connection."
},
{
"code": null,
"e": 63135,
"s": 63080,
"text": "Prompt − Every time it will ask user name and password"
},
{
"code": null,
"e": 63190,
"s": 63135,
"text": "Prompt − Every time it will ask user name and password"
},
{
"code": null,
"e": 63210,
"s": 63190,
"text": "SSO − User specific"
},
{
"code": null,
"e": 63230,
"s": 63210,
"text": "SSO − User specific"
},
{
"code": null,
"e": 63357,
"s": 63230,
"text": "Enter user − user name and password for HANA system and save and new connection will be added to existing list of connections."
},
{
"code": null,
"e": 63484,
"s": 63357,
"text": "Enter user − user name and password for HANA system and save and new connection will be added to existing list of connections."
},
{
"code": null,
"e": 63816,
"s": 63484,
"text": "Now open BI Launchpad to open all BI platform tools for reporting like Office Analysis for OLAP and it will ask to choose a connection. By default, it will show you the Information View if you have specified it while creating this connection otherwise click on Next and go to folders → Choose Views (Analytic or Calculation Views)."
},
{
"code": null,
"e": 63857,
"s": 63816,
"text": "SAP Lumira connectivity with HANA system"
},
{
"code": null,
"e": 63965,
"s": 63857,
"text": "Open SAP Lumira from Start Program, Click on file menu → New → Add new dataset → Connect to SAP HANA → Next"
},
{
"code": null,
"e": 64255,
"s": 63965,
"text": "Difference between connect to SAP HANA and download from SAP HANA is that it will download data from Hana system to BO repository and refreshing of data will not occur with changes in HANA system. Enter HANA server name and Instance number. Enter user name and password → click on Connect."
},
{
"code": null,
"e": 64452,
"s": 64255,
"text": "It will show all views. You can search with the view name → Choose View → Next. It will show all measures and dimensions. You can choose from these attributes if you want → click on create option."
},
{
"code": null,
"e": 64492,
"s": 64452,
"text": "There are four tabs inside SAP Lumira −"
},
{
"code": null,
"e": 64554,
"s": 64492,
"text": "Prepare − You can see the data and do any custom calculation."
},
{
"code": null,
"e": 64616,
"s": 64554,
"text": "Prepare − You can see the data and do any custom calculation."
},
{
"code": null,
"e": 64712,
"s": 64616,
"text": "Visualize − You can add Graphs and Charts. Click on X axis and Y axis + sign to add attributes."
},
{
"code": null,
"e": 64808,
"s": 64712,
"text": "Visualize − You can add Graphs and Charts. Click on X axis and Y axis + sign to add attributes."
},
{
"code": null,
"e": 65059,
"s": 64808,
"text": "Compose − This option can be used to create sequence of Visualization (story) → click on Board to add numbers of boards → create → it will show all the visualizations on left side. Drag first Visualization then add page then add second visualization."
},
{
"code": null,
"e": 65310,
"s": 65059,
"text": "Compose − This option can be used to create sequence of Visualization (story) → click on Board to add numbers of boards → create → it will show all the visualizations on left side. Drag first Visualization then add page then add second visualization."
},
{
"code": null,
"e": 65486,
"s": 65310,
"text": "Share − If it is built on SAP HANA, we can only publish to SAP Lumira server. Otherwise you can also publish story from SAP Lumira to SAP Community Network SCN or BI Platform."
},
{
"code": null,
"e": 65662,
"s": 65486,
"text": "Share − If it is built on SAP HANA, we can only publish to SAP Lumira server. Otherwise you can also publish story from SAP Lumira to SAP Community Network SCN or BI Platform."
},
{
"code": null,
"e": 65732,
"s": 65662,
"text": "Save the file to use it later → Go to File-Save → choose Local → Save"
},
{
"code": null,
"e": 65819,
"s": 65732,
"text": "Creating a Relational Connection in IDT to use with HANA views in WebI and Dashboard −"
},
{
"code": null,
"e": 65940,
"s": 65819,
"text": "Open Information Design Tool → by going to BI Platform Client tools. Click on New → Project Enter Project Name → Finish."
},
{
"code": null,
"e": 66210,
"s": 65940,
"text": "Right-click on Project name → Go to New → Choose Relational Connection → Enter Connection/resource name → Next → choose SAP from list to connect to HANA system → SAP HANA → Select JDBC/ODBC drivers → click on Next → Enter HANA system details → Click on Next and Finish."
},
{
"code": null,
"e": 66283,
"s": 66210,
"text": "You can also test this connection by clicking on Test Connection option."
},
{
"code": null,
"e": 66397,
"s": 66283,
"text": "Test Connection → Successful. Next step is to publish this connection to Repository to make it available for use."
},
{
"code": null,
"e": 66553,
"s": 66397,
"text": "Right Click on connection name → click on Publish connection to Repository → Enter BO Repository name and password → Click on Connect → Next →Finish → Yes."
},
{
"code": null,
"e": 66617,
"s": 66553,
"text": "It will create a new relational connection with .cns extension."
},
{
"code": null,
"e": 66728,
"s": 66617,
"text": ".cns − connection type represents secured Repository connection that should be used to create Data foundation."
},
{
"code": null,
"e": 66896,
"s": 66728,
"text": ".cnx − represents local unsecured connection. If you use this connection while creating and publishing a Universe, it will not allow you to publish that to repository."
},
{
"code": null,
"e": 67071,
"s": 66896,
"text": "Choose .cns connection type → Right Click on this → click on New Data foundation → Enter Name of Data foundation → Next → Single source/multi source → click on Next → Finish."
},
{
"code": null,
"e": 67153,
"s": 67071,
"text": "It will show all the tables in HANA database with Schema name in the middle pane."
},
{
"code": null,
"e": 67304,
"s": 67153,
"text": "Import all tables from HANA database to master pane to create a Universe. Join Dim and Fact tables with primary keys in Dim tables to create a Schema."
},
{
"code": null,
"e": 67503,
"s": 67304,
"text": "Double Click on the Joins and detect Cardinality → Detect → OK → Save All at the top. Now we have to create a new Business layer on the data foundation that will be consumed by BI Application tools."
},
{
"code": null,
"e": 67729,
"s": 67503,
"text": "Right Click on .dfx and choose new Business Layer → Enter Name → Finish →. It will show all the objects automatically, under master pane →. Change Dimension to Measures (Type-Measure change Projection as required) → Save All."
},
{
"code": null,
"e": 67849,
"s": 67729,
"text": "Right-click on .bfx file → click on Publish → To Repository → click on Next → Finish → Universe Published Successfully."
},
{
"code": null,
"e": 67985,
"s": 67849,
"text": "Now open WebI Report from BI Launchpad or Webi rich client from BI Platform client tools → New → select Universe → TEST_SAP_HANA → OK."
},
{
"code": null,
"e": 68229,
"s": 67985,
"text": "All Objects will be added to Query Panel. You can choose attributes and measures from left pane and add them to Result Objects. The Run query will run the SQL query and the output will be generated in the form of Report in WebI as shown below."
},
{
"code": null,
"e": 68438,
"s": 68229,
"text": "Microsoft Excel is considered the most common BI reporting and analysis tool by many organizations. Business Managers and Analysts can connect it to HANA database to draw Pivot tables and charts for analysis."
},
{
"code": null,
"e": 68593,
"s": 68438,
"text": "Open Excel and go to Data tab → from other sources → click on Data connection wizard → Other/ Advanced and click on Next → Data link properties will open."
},
{
"code": null,
"e": 68803,
"s": 68593,
"text": "Choose SAP HANA MDX Provider from this list to connect to any MDX data source → Enter HANA system details (server name, instance, user name and password) → click on Test Connection → Connection succeeded → OK."
},
{
"code": null,
"e": 68980,
"s": 68803,
"text": "It will give you the list of all packages in drop down list that are available in HANA system. You can choose an Information view → click Next → Select Pivot table/others → OK."
},
{
"code": null,
"e": 69210,
"s": 68980,
"text": "All attributes from Information view will be added to MS Excel. You can choose different attributes and measures to report as shown and you can choose different charts like pie charts and bar charts from design option at the top."
},
{
"code": null,
"e": 69507,
"s": 69210,
"text": "Security means protecting company’s critical data from unauthorized access and use, and to ensure that Compliance and standards are met as per the company policy. SAP HANA enables customer to implement different security policies and procedures and to meet compliance requirements of the company."
},
{
"code": null,
"e": 70065,
"s": 69507,
"text": "SAP HANA supports multiple databases in a single HANA system and this is known as multitenant database containers. HANA system can also contain more than one multitenant database containers. A multiple container system always has exactly one system database and any number of multitenant database containers. AN SAP HANA system that is installed in this environment is identified by a single system ID (SID). Database containers in HANA system are identified by a SID and database name. SAP HANA client, known as HANA studio, connects to specific databases."
},
{
"code": null,
"e": 70259,
"s": 70065,
"text": "SAP HANA provides all security related features such as Authentication, Authorization, Encryption and Auditing, and some add on features, which are not supported in other multitenant databases."
},
{
"code": null,
"e": 70334,
"s": 70259,
"text": "Below given is a list of security related features, provided by SAP HANA −"
},
{
"code": null,
"e": 70359,
"s": 70334,
"text": "User and Role Management"
},
{
"code": null,
"e": 70382,
"s": 70359,
"text": "Authentication and SSO"
},
{
"code": null,
"e": 70396,
"s": 70382,
"text": "Authorization"
},
{
"code": null,
"e": 70440,
"s": 70396,
"text": "Encryption of data communication in Network"
},
{
"code": null,
"e": 70480,
"s": 70440,
"text": "Encryption of data in Persistence Layer"
},
{
"code": null,
"e": 70531,
"s": 70480,
"text": "Additional Features in multitenant HANA database −"
},
{
"code": null,
"e": 70631,
"s": 70531,
"text": "Database Isolation − It involves preventing cross tenant attacks through operating system mechanism"
},
{
"code": null,
"e": 70731,
"s": 70631,
"text": "Database Isolation − It involves preventing cross tenant attacks through operating system mechanism"
},
{
"code": null,
"e": 70866,
"s": 70731,
"text": "Configuration Change blacklist − It involves preventing certain system properties from being changed by tenant database administrators"
},
{
"code": null,
"e": 71001,
"s": 70866,
"text": "Configuration Change blacklist − It involves preventing certain system properties from being changed by tenant database administrators"
},
{
"code": null,
"e": 71147,
"s": 71001,
"text": "Restricted Features − It involves disabling certain database features that provides direct access to file system, the network or other resources."
},
{
"code": null,
"e": 71293,
"s": 71147,
"text": "Restricted Features − It involves disabling certain database features that provides direct access to file system, the network or other resources."
},
{
"code": null,
"e": 71390,
"s": 71293,
"text": "SAP HANA user and role management configuration depends on the architecture of your HANA system."
},
{
"code": null,
"e": 71533,
"s": 71390,
"text": "If SAP HANA is integrated with BI platform tools and acts as reporting database, then the end-user and role are managed in application server."
},
{
"code": null,
"e": 71676,
"s": 71533,
"text": "If SAP HANA is integrated with BI platform tools and acts as reporting database, then the end-user and role are managed in application server."
},
{
"code": null,
"e": 71839,
"s": 71676,
"text": "If the end-user directly connects to the SAP HANA database, then user and role in database layer of HANA system is required for both end users and administrators."
},
{
"code": null,
"e": 72002,
"s": 71839,
"text": "If the end-user directly connects to the SAP HANA database, then user and role in database layer of HANA system is required for both end users and administrators."
},
{
"code": null,
"e": 72535,
"s": 72002,
"text": "Every user wants to work with HANA database must have a database user with necessary privileges. User accessing HANA system can either be a technical user or an end user depending on the access requirement. After successful logon to system, user’s authorization to perform the required operation is verified. Executing that operation depends on privileges that user has been granted. These privileges can be granted using roles in HANA Security. HANA Studio is one of powerful tool to manage user and roles for HANA database system."
},
{
"code": null,
"e": 72764,
"s": 72535,
"text": "User types vary according to security policies and different privileges assigned on user profile. User type can be a technical database user or end user needs access on HANA system for reporting purpose or for data manipulation."
},
{
"code": null,
"e": 72966,
"s": 72764,
"text": "Standard users are users who can create objects in their own Schemas and have read access in system Information models. Read access is provided by PUBLIC role which is assigned to every standard users."
},
{
"code": null,
"e": 73166,
"s": 72966,
"text": "Restricted users are those users who access HANA system with some applications and they do not have SQL privileges on HANA system. When these users are created, they do not have any access initially."
},
{
"code": null,
"e": 73219,
"s": 73166,
"text": "If we compare restricted users with Standard users −"
},
{
"code": null,
"e": 73297,
"s": 73219,
"text": "Restricted users cannot create objects in HANA database or their own Schemas."
},
{
"code": null,
"e": 73375,
"s": 73297,
"text": "Restricted users cannot create objects in HANA database or their own Schemas."
},
{
"code": null,
"e": 73505,
"s": 73375,
"text": "They do not have access to view any data in database as they don’t have generic Public role added to profile like standard users."
},
{
"code": null,
"e": 73635,
"s": 73505,
"text": "They do not have access to view any data in database as they don’t have generic Public role added to profile like standard users."
},
{
"code": null,
"e": 73692,
"s": 73635,
"text": "They can connect to HANA database only using HTTP/HTTPS."
},
{
"code": null,
"e": 73749,
"s": 73692,
"text": "They can connect to HANA database only using HTTP/HTTPS."
},
{
"code": null,
"e": 73925,
"s": 73749,
"text": "Technical database users are used only for administrative purpose such as creating new objects in database, assigning privileges to other users, on packages, applications etc."
},
{
"code": null,
"e": 74094,
"s": 73925,
"text": "Depending on business needs and configuration of HANA system, there are different user activities that can be performed using user administration tool like HANA studio."
},
{
"code": null,
"e": 74127,
"s": 74094,
"text": "Most common activities include −"
},
{
"code": null,
"e": 74140,
"s": 74127,
"text": "Create Users"
},
{
"code": null,
"e": 74161,
"s": 74140,
"text": "Grant roles to users"
},
{
"code": null,
"e": 74185,
"s": 74161,
"text": "Define and Create Roles"
},
{
"code": null,
"e": 74200,
"s": 74185,
"text": "Deleting Users"
},
{
"code": null,
"e": 74225,
"s": 74200,
"text": "Resetting user passwords"
},
{
"code": null,
"e": 74281,
"s": 74225,
"text": "Reactivating users after too many failed logon attempts"
},
{
"code": null,
"e": 74320,
"s": 74281,
"text": "Deactivating users when it is required"
},
{
"code": null,
"e": 74550,
"s": 74320,
"text": "Only database users with the system privilege ROLE ADMIN are allowed to create users and roles in HANA studio. To create users and roles in HANA studio, go to HANA Administrator Console. You will see security tab in System view −"
},
{
"code": null,
"e": 74740,
"s": 74550,
"text": "When you expand security tab, it gives option of User and Roles. To create a new user right click on User and go to New User. New window will open where you define User and User parameters."
},
{
"code": null,
"e": 74918,
"s": 74740,
"text": "Enter User name (mandate) and in Authentication field enter password. Password is applied, while saving password for a new user. You can also choose to create a restricted user."
},
{
"code": null,
"e": 75175,
"s": 74918,
"text": "The specified role name must not be identical to the name of an existing user or role. The password rules include a minimal password length and a definition of which character types (lower, upper, digit, special characters) have to be part of the password."
},
{
"code": null,
"e": 75345,
"s": 75175,
"text": "Different Authorization methods can be configured like SAML, X509 certificates, SAP Logon ticket, etc. Users in the database can be authenticated by varying mechanisms −"
},
{
"code": null,
"e": 75397,
"s": 75345,
"text": "Internal authentication mechanism using a password."
},
{
"code": null,
"e": 75490,
"s": 75397,
"text": "External mechanisms such as Kerberos, SAML, SAP Logon Ticket, SAP Assertion Ticket or X.509."
},
{
"code": null,
"e": 75764,
"s": 75490,
"text": "A user can be authenticated by more than one mechanism at a time. However, only one password and one principal name for Kerberos can be valid at any one time. One authentication mechanism has to be specified to allow the user to connect and work with the database instance."
},
{
"code": null,
"e": 75928,
"s": 75764,
"text": "It also gives an option to define validity of user, you can mention validity interval by selecting the dates. Validity specification is an optional user parameter."
},
{
"code": null,
"e": 76045,
"s": 75928,
"text": "Some users that are, by default, delivered with the SAP HANA database are − SYS, SYSTEM, _SYS_REPO, _SYS_STATISTICS."
},
{
"code": null,
"e": 76197,
"s": 76045,
"text": "Once this is done, the next step is to define privileges for user profile. There are different types of privileges that can be added to a user profile."
},
{
"code": null,
"e": 76526,
"s": 76197,
"text": "This is used to add inbuilt SAP.HANA roles to user profile or to add custom roles created under Roles tab. Custom roles allow you to define roles as per access requirement and you can add these roles directly to user profile. This removes need to remember and add objects to a user profile every time for different access types."
},
{
"code": null,
"e": 76733,
"s": 76526,
"text": "PUBLIC − This is Generic role and is assigned to all database users by default. This role contains read only access to system views and execute privileges for some procedures. These roles cannot be revoked."
},
{
"code": null,
"e": 76827,
"s": 76733,
"text": "It contains all privileges required for using the information modeler in the SAP HANA studio."
},
{
"code": null,
"e": 76974,
"s": 76827,
"text": "There are different types of System privileges that can be added to a user profile. To add a system privileges to a user profile, click on + sign."
},
{
"code": null,
"e": 77072,
"s": 76974,
"text": "System privileges are used for Backup/Restore, User Administration, Instance start and stop, etc."
},
{
"code": null,
"e": 77297,
"s": 77072,
"text": "It contains the similar privileges as that in MODELING role, but with the addition that this role is allowed to grant these privileges to other users. It also contains the repository privileges to work with imported objects."
},
{
"code": null,
"e": 77381,
"s": 77297,
"text": "This is a type of privilege, required for adding Data from objects to user profile."
},
{
"code": null,
"e": 77434,
"s": 77381,
"text": "Given below are common supported System Privileges −"
},
{
"code": null,
"e": 77588,
"s": 77434,
"text": "It authorizes the debugging of a procedure call, called by a different user. Additionally, the DEBUG privilege for the corresponding procedure is needed."
},
{
"code": null,
"e": 77810,
"s": 77588,
"text": "Controls the execution of the following auditing-related commands − CREATE AUDIT POLICY, DROP AUDIT POLICY and ALTER AUDIT POLICY and the changes of the auditing configuration. Also allows access to AUDIT_LOG system view."
},
{
"code": null,
"e": 77940,
"s": 77810,
"text": "It authorizes the execution of the following command − ALTER SYSTEM CLEAR AUDIT LOG. Also allows access to AUDIT_LOG system view."
},
{
"code": null,
"e": 78043,
"s": 77940,
"text": "It authorizes BACKUP and RECOVERY commands for defining and initiating backup and recovery procedures."
},
{
"code": null,
"e": 78106,
"s": 78043,
"text": "It authorizes the BACKUP command to initiate a backup process."
},
{
"code": null,
"e": 78279,
"s": 78106,
"text": "It authorizes users to have unfiltered read-only access to all system views. Normally, the content of these views is filtered based on the privileges of the accessing user."
},
{
"code": null,
"e": 78468,
"s": 78279,
"text": "It authorizes the creation of database schemas using the CREATE SCHEMA command. By default, each user owns one schema, with this privilege the user is allowed to create additional schemas."
},
{
"code": null,
"e": 78655,
"s": 78468,
"text": "It authorizes the creation of Structured Privileges (Analytical Privileges). Only the owner of an Analytical Privilege can further grant or revoke that privilege to other users or roles."
},
{
"code": null,
"e": 78725,
"s": 78655,
"text": "It authorizes the credential commands − CREATE/ALTER/DROP CREDENTIAL."
},
{
"code": null,
"e": 78875,
"s": 78725,
"text": "It authorizes reading all data in the system views. It also enables execution of any Data Definition Language (DDL) commands in the SAP HANA database"
},
{
"code": null,
"e": 79047,
"s": 78875,
"text": "A user having this privilege cannot select or change data stored tables for which they do not have access privileges, but they can drop tables or modify table definitions."
},
{
"code": null,
"e": 79171,
"s": 79047,
"text": "It authorizes all commands related to databases in a multi-database, such as CREATE, DROP, ALTER, RENAME, BACKUP, RECOVERY."
},
{
"code": null,
"e": 79247,
"s": 79171,
"text": "It authorizes export activity in the database via the EXPORT TABLE command."
},
{
"code": null,
"e": 79355,
"s": 79247,
"text": "Note that beside this privilege the user requires the SELECT privilege on the source tables to be exported."
},
{
"code": null,
"e": 79432,
"s": 79355,
"text": "It authorizes the import activity in the database using the IMPORT commands."
},
{
"code": null,
"e": 79540,
"s": 79432,
"text": "Note that beside this privilege the user requires the INSERT privilege on the target tables to be imported."
},
{
"code": null,
"e": 79583,
"s": 79540,
"text": "It authorizes changing of system settings."
},
{
"code": null,
"e": 79651,
"s": 79583,
"text": "It authorizes the SET SYSTEM LICENSE command install a new license."
},
{
"code": null,
"e": 79754,
"s": 79651,
"text": "It authorizes the ALTER SYSTEM LOGGING [ON|OFF] commands to enable or disable the log flush mechanism."
},
{
"code": null,
"e": 79806,
"s": 79754,
"text": "It authorizes the ALTER SYSTEM commands for EVENTs."
},
{
"code": null,
"e": 79970,
"s": 79806,
"text": "It authorizes the ALTER SYSTEM commands concerning SQL PLAN CACHE and ALTER SYSTEM UPDATE STATISTICS commands, which influence the behavior of the query optimizer."
},
{
"code": null,
"e": 80196,
"s": 79970,
"text": "This privilege authorizes commands concerning system resources. For example, ALTER SYSTEM RECLAIM DATAVOLUME and ALTER SYSTEM RESET MONITORING VIEW. It also authorizes many of the commands available in the Management Console."
},
{
"code": null,
"e": 80396,
"s": 80196,
"text": "This privilege authorizes the creation and deletion of roles using the CREATE ROLE and DROP ROLE commands. It also authorizes the granting and revocation of roles using the GRANT and REVOKE commands."
},
{
"code": null,
"e": 80664,
"s": 80396,
"text": "Activated roles, meaning roles whose creator is the pre-defined user _SYS_REPO, can neither be granted to other roles or users nor dropped directly. Not even users having ROLE ADMIN privilege are able to do so. Please check documentation concerning activated objects."
},
{
"code": null,
"e": 80757,
"s": 80664,
"text": "It authorizes the execution of a savepoint process using the ALTER SYSTEM SAVEPOINT command."
},
{
"code": null,
"e": 80970,
"s": 80757,
"text": "Components of the SAP HANA database can create new system privileges. These privileges use the component-name as first identifier of the system privilege and the component-privilege-name as the second identifier."
},
{
"code": null,
"e": 81143,
"s": 80970,
"text": "Object privileges are also known as SQL privileges. These privileges are used to allow access on objects like Select, Insert, Update and Delete of tables, Views or Schemas."
},
{
"code": null,
"e": 81197,
"s": 81143,
"text": "Given below are possible types of Object Privileges −"
},
{
"code": null,
"e": 81261,
"s": 81197,
"text": "Object privilege on database objects that exist only in runtime"
},
{
"code": null,
"e": 81325,
"s": 81261,
"text": "Object privilege on database objects that exist only in runtime"
},
{
"code": null,
"e": 81413,
"s": 81325,
"text": "Object privilege on activated objects created in the repository, like calculation views"
},
{
"code": null,
"e": 81501,
"s": 81413,
"text": "Object privilege on activated objects created in the repository, like calculation views"
},
{
"code": null,
"e": 81584,
"s": 81501,
"text": "Object privilege on schema containing activated objects created in the repository,"
},
{
"code": null,
"e": 81667,
"s": 81584,
"text": "Object privilege on schema containing activated objects created in the repository,"
},
{
"code": null,
"e": 81755,
"s": 81667,
"text": "Object/SQL Privileges are collection of all DDL and DML privileges on database objects."
},
{
"code": null,
"e": 81843,
"s": 81755,
"text": "Object/SQL Privileges are collection of all DDL and DML privileges on database objects."
},
{
"code": null,
"e": 81896,
"s": 81843,
"text": "Given below are common supported Object Privileges −"
},
{
"code": null,
"e": 82025,
"s": 81896,
"text": "There are multiple database objects in HANA database, so not all the privileges are applicable to all kinds of database objects."
},
{
"code": null,
"e": 82089,
"s": 82025,
"text": "Object Privileges and their applicability on database objects −"
},
{
"code": null,
"e": 82240,
"s": 82089,
"text": "Sometimes, it is required that data in the same view should not be accessible to other users who does not have any relevant requirement for that data."
},
{
"code": null,
"e": 82399,
"s": 82240,
"text": "Analytic privileges are used to limit the access on HANA Information Views at object level. We can apply row and column level security in Analytic Privileges."
},
{
"code": null,
"e": 82434,
"s": 82399,
"text": "Analytic Privileges are used for −"
},
{
"code": null,
"e": 82504,
"s": 82434,
"text": "Allocation of row and column level security for specific value range."
},
{
"code": null,
"e": 82568,
"s": 82504,
"text": "Allocation of row and column level security for modeling views."
},
{
"code": null,
"e": 82963,
"s": 82568,
"text": "In the SAP HANA repository, you can set package authorizations for a specific user or for a role. Package privileges are used to allow access to data models- Analytic or Calculation views or on to Repository objects. All privileges that are assigned to a repository package are assigned to all sub packages too. You can also mention if assigned user authorizations can be passed to other users."
},
{
"code": null,
"e": 83015,
"s": 82963,
"text": "Steps to add a package privileges to User profile −"
},
{
"code": null,
"e": 83163,
"s": 83015,
"text": "Click on Package privilege tab in HANA studio under User creation → Choose + to add one or more packages. Use Ctrl key to select multiple packages."
},
{
"code": null,
"e": 83311,
"s": 83163,
"text": "Click on Package privilege tab in HANA studio under User creation → Choose + to add one or more packages. Use Ctrl key to select multiple packages."
},
{
"code": null,
"e": 83459,
"s": 83311,
"text": "In the Select Repository Package dialog, use all or part of the package name to locate the repository package that you want to authorize access to."
},
{
"code": null,
"e": 83607,
"s": 83459,
"text": "In the Select Repository Package dialog, use all or part of the package name to locate the repository package that you want to authorize access to."
},
{
"code": null,
"e": 83744,
"s": 83607,
"text": "Select one or more repository packages that you want to authorize access to, the selected packages appear in the Package Privileges tab."
},
{
"code": null,
"e": 83881,
"s": 83744,
"text": "Select one or more repository packages that you want to authorize access to, the selected packages appear in the Package Privileges tab."
},
{
"code": null,
"e": 83995,
"s": 83881,
"text": "Given below are grant privileges, which are used on repository packages to authorize user to modify the objects −"
},
{
"code": null,
"e": 84094,
"s": 83995,
"text": "REPO.READ − Read access to the selected package and design-time objects (both native and imported)"
},
{
"code": null,
"e": 84193,
"s": 84094,
"text": "REPO.READ − Read access to the selected package and design-time objects (both native and imported)"
},
{
"code": null,
"e": 84265,
"s": 84193,
"text": "REPO.EDIT_NATIVE_OBJECTS − Authorization to modify objects in packages."
},
{
"code": null,
"e": 84337,
"s": 84265,
"text": "REPO.EDIT_NATIVE_OBJECTS − Authorization to modify objects in packages."
},
{
"code": null,
"e": 84457,
"s": 84337,
"text": "Grantable to Others − If you choose ‘Yes’ for this, this allows assigned user authorization to pass to the other users."
},
{
"code": null,
"e": 84577,
"s": 84457,
"text": "Grantable to Others − If you choose ‘Yes’ for this, this allows assigned user authorization to pass to the other users."
},
{
"code": null,
"e": 84957,
"s": 84577,
"text": "Application privileges in a user profile are used to define authorization for access to HANA XS application. This can be assigned to an individual user or to the group of users. Application privileges can also be used to provide different level of access to the same application like to provide advanced functions for database Administrators and read-only access to normal users."
},
{
"code": null,
"e": 85077,
"s": 84957,
"text": "To define Application specific privileges in a user profile or to add group of users, below privileges should be used −"
},
{
"code": null,
"e": 85121,
"s": 85077,
"text": "Application-privileges file (.xsprivileges)"
},
{
"code": null,
"e": 85157,
"s": 85121,
"text": "Application-access file (.xsaccess)"
},
{
"code": null,
"e": 85199,
"s": 85157,
"text": "Role-definition file (<RoleName>.hdbrole)"
},
{
"code": null,
"e": 85440,
"s": 85199,
"text": "All SAP HANA users that have access on HANA database are verified with different Authentications method. SAP HANA system supports various types of authentication method and all these login methods are configured at time of profile creation."
},
{
"code": null,
"e": 85508,
"s": 85440,
"text": "Below is the list of authentication methods supported by SAP HANA −"
},
{
"code": null,
"e": 85527,
"s": 85508,
"text": "User name/Password"
},
{
"code": null,
"e": 85536,
"s": 85527,
"text": "Kerberos"
},
{
"code": null,
"e": 85545,
"s": 85536,
"text": "SAML 2.0"
},
{
"code": null,
"e": 85563,
"s": 85545,
"text": "SAP Logon tickets"
},
{
"code": null,
"e": 85569,
"s": 85563,
"text": "X.509"
},
{
"code": null,
"e": 85738,
"s": 85569,
"text": "This method requires a HANA user to enter user name and password to login to database. This user profile is created under User management in HANA Studio → Security Tab."
},
{
"code": null,
"e": 85849,
"s": 85738,
"text": "Password should be as per password policy i.e. Password length, complexity, lower and upper case letters, etc."
},
{
"code": null,
"e": 85987,
"s": 85849,
"text": "You can change the password policy as per your organization’s security standards. Please note that password policy cannot be deactivated."
},
{
"code": null,
"e": 86171,
"s": 85987,
"text": "All users who connect to HANA database system using an external authentication method should also have a database user. It is required to map external login to internal database user."
},
{
"code": null,
"e": 86334,
"s": 86171,
"text": "This method enables users to authenticate HANA system directly using JDBC/ODBC drivers through network or by using front end applications in SAP Business Objects."
},
{
"code": null,
"e": 86462,
"s": 86334,
"text": "It also allows HTTP access in HANA Extended Service using HANA XS engine. It uses SPENGO mechanism for Kerberos authentication."
},
{
"code": null,
"e": 86703,
"s": 86462,
"text": "SAML stands for Security Assertion Markup Language and can be used to authenticate users accessing HANA system directly from ODBC/JDBC clients. It can also be used to authenticate users in HANA system coming via HTTP through HANA XS engine."
},
{
"code": null,
"e": 86775,
"s": 86703,
"text": "SAML is used only for authentication purpose and not for authorization."
},
{
"code": null,
"e": 87104,
"s": 86775,
"text": "SAP Logon/assertion tickets can be used to authenticate users in HANA system. These tickets are issued to users when they login into SAP system, which is configured to issue such tickets like SAP Portal, etc. User specified in SAP logon tickets should be created in HANA system, as it does not provide support for mapping users."
},
{
"code": null,
"e": 87336,
"s": 87104,
"text": "X.509 certificates can also be used to login to HANA system via HTTP access request from HANA XS engine. Users are authenticated by certificated that are signed from trusted Certificate Authority, which is stored in HANA XS system."
},
{
"code": null,
"e": 87433,
"s": 87336,
"text": "User in trusted certificate should exist in HANA system as there is no support for user mapping."
},
{
"code": null,
"e": 87697,
"s": 87433,
"text": "Single sign on can be configured in HANA system, which allows users to login to HANA system from an initial authentication on the client. User logins at client applications using different authentication methods and SSO allows user to access HANA system directly."
},
{
"code": null,
"e": 87752,
"s": 87697,
"text": "SSO can be configured on below configuration methods −"
},
{
"code": null,
"e": 87757,
"s": 87752,
"text": "SAML"
},
{
"code": null,
"e": 87766,
"s": 87757,
"text": "Kerberos"
},
{
"code": null,
"e": 87828,
"s": 87766,
"text": "X.509 client certificates for HTTP access from HANA XS engine"
},
{
"code": null,
"e": 87856,
"s": 87828,
"text": "SAP Logon/Assertion tickets"
},
{
"code": null,
"e": 88174,
"s": 87856,
"text": "Authorization is checked when a user tries to connect to HANA database and perform some database operations. When a user connects to HANA database using client tools via JDBC/ODBC or Via HTTP to perform some operations on database objects, corresponding action is determined by the access that is granted to the user."
},
{
"code": null,
"e": 88551,
"s": 88174,
"text": "Privileges granted to a user are determined by Object privileges assigned on user profile or role that has been granted to user. Authorization is a combination of both accesses. When a user tries to perform some operation on HANA database, system performs an authorization check. When all required privileges are found, system stops this check and grants the requested access."
},
{
"code": null,
"e": 88665,
"s": 88551,
"text": "There are different types of privileges, which are used in SAP HANA as mentioned under User role and Management −"
},
{
"code": null,
"e": 88944,
"s": 88665,
"text": "They are applicable to system and database authorization for users and control system activities. They are used for administrative tasks such as creating Schemas, data backups, creating users and roles and so on. System privileges are also used to perform Repository operations."
},
{
"code": null,
"e": 89213,
"s": 88944,
"text": "They are applicable to database operations and apply to database objects like tables, Schemas, etc. They are used to manage database objects such as tables and views. Different actions like Select, Execute, Alter, Drop, Delete can be defined based on database objects."
},
{
"code": null,
"e": 89323,
"s": 89213,
"text": "They are also used to control remote data objects, which are connected through SMART data access to SAP HANA."
},
{
"code": null,
"e": 89651,
"s": 89323,
"text": "They are applicable to data inside all the packages that are created in HANA repository. They are used to control modeling views that are created inside packages like Attribute View, Analytic View, and Calculation View. They apply row and column level security to attributes that are defined in modeling views in HANA packages."
},
{
"code": null,
"e": 89922,
"s": 89651,
"text": "They are applicable to allow access to and ability to use packages that are created in repository of HANA database. Package contains different Modeling views like Attribute, Analytic and Calculation views and also Analytic Privileges defined in HANA repository database."
},
{
"code": null,
"e": 90086,
"s": 89922,
"text": "They are applicable to HANA XS application that access HANA database via HTTP request. They are used to control access on applications created with HANA XS engine."
},
{
"code": null,
"e": 90261,
"s": 90086,
"text": "Application Privileges can be applied to users/roles directly using HANA studio but it is preferred that they should be applied to roles created in repository at design time."
},
{
"code": null,
"e": 90572,
"s": 90261,
"text": "_SYS_REPO is the user owns all the objects in HANA repository. This user should be authorized externally for the objects on which repository objects are modeled in HANA system. _SYS_REPO is owner of all objects so it can only be used to grant access on these objects, no other user can login as _SYS_REPO user."
},
{
"code": null,
"e": 90642,
"s": 90572,
"text": "GRANT SELECT ON SCHEMA \"<SCHEMA_NAME>\" TO _SYS_REPO WITH GRANT OPTION"
},
{
"code": null,
"e": 90777,
"s": 90642,
"text": "SAP HANA License management and keys are required to use HANA database. You can install or delete HANA License keys using HANA studio."
},
{
"code": null,
"e": 90830,
"s": 90777,
"text": "SAP HANA system supports two types of License keys −"
},
{
"code": null,
"e": 91104,
"s": 90830,
"text": "Temporary License Key − Temporary License keys are automatically installed when you install the HANA database. These keys are valid only for 90 days and you should request permanent license keys from SAP market place before expiry of this 90 days period after installation."
},
{
"code": null,
"e": 91378,
"s": 91104,
"text": "Temporary License Key − Temporary License keys are automatically installed when you install the HANA database. These keys are valid only for 90 days and you should request permanent license keys from SAP market place before expiry of this 90 days period after installation."
},
{
"code": null,
"e": 91802,
"s": 91378,
"text": "Permanent License Key − Permanent License keys are valid only till the predefine expiration date. License keys specify amount of memory licensed to target HANA installation. They can installed from SAP Market place under Keys and Requests tab. When a permanent License key is expired, a temporary license key is issued, which is valid for only 28 days. During this period, you have to install a permanent License key again."
},
{
"code": null,
"e": 92226,
"s": 91802,
"text": "Permanent License Key − Permanent License keys are valid only till the predefine expiration date. License keys specify amount of memory licensed to target HANA installation. They can installed from SAP Market place under Keys and Requests tab. When a permanent License key is expired, a temporary license key is issued, which is valid for only 28 days. During this period, you have to install a permanent License key again."
},
{
"code": null,
"e": 92290,
"s": 92226,
"text": "There are two types of permanent License keys for HANA system −"
},
{
"code": null,
"e": 92463,
"s": 92290,
"text": "Unenforced − If unenforced license key is installed and consumption of HANA system exceeds the license amount of memory, operation of SAP HANA is not affected in this case."
},
{
"code": null,
"e": 92636,
"s": 92463,
"text": "Unenforced − If unenforced license key is installed and consumption of HANA system exceeds the license amount of memory, operation of SAP HANA is not affected in this case."
},
{
"code": null,
"e": 92892,
"s": 92636,
"text": "Enforced − If Enforced license key is installed and consumption of HANA system exceeds the license amount of memory, HANA system gets locked. If this situation occurs, HANA system has to be restarted or a new license key should be requested and installed."
},
{
"code": null,
"e": 93148,
"s": 92892,
"text": "Enforced − If Enforced license key is installed and consumption of HANA system exceeds the license amount of memory, HANA system gets locked. If this situation occurs, HANA system has to be restarted or a new license key should be requested and installed."
},
{
"code": null,
"e": 93378,
"s": 93148,
"text": "There is different License scenarios that can be used in HANA system depending on the landscape of the system (Standalone, HANA Cloud, BW on HANA, etc.) and not all of these models are based on memory of HANA system installation."
},
{
"code": null,
"e": 93428,
"s": 93378,
"text": "Right Click on HANA system → Properties → License"
},
{
"code": null,
"e": 93621,
"s": 93428,
"text": "It tells about License type, Start Date and Expiration Date, Memory Allocation and the information (Hardware Key, System Id) that is required to request a new license through SAP Market Place."
},
{
"code": null,
"e": 93761,
"s": 93621,
"text": "Install License key → Browse → Enter Path, is used to install a new License key and delete option is used to delete any old expiration key."
},
{
"code": null,
"e": 93875,
"s": 93761,
"text": "All Licenses tab under License tells about Product name, description, Hardware key, First installation time, etc."
},
{
"code": null,
"e": 94147,
"s": 93875,
"text": "SAP HANA audit policy tells the actions to be audited and also the condition under which the action must be performed to be relevant for auditing. Audit Policy defines what activities have been performed in HANA system and who has performed those activities at what time."
},
{
"code": null,
"e": 94438,
"s": 94147,
"text": "SAP HANA database auditing feature allows monitoring action performed in HANA system. SAP HANA audit policy must be activated on HANA system to use it. When an action is performed, the policy triggers an audit event to write to audit trail. You can also delete audit entries in Audit trail."
},
{
"code": null,
"e": 94688,
"s": 94438,
"text": "In a distributed environment, where you have multiple database, Audit policy can be enabled on each individual system. For the system database, audit policy is defined in nameserver.ini file and for tenant database, it is defined in global.ini file."
},
{
"code": null,
"e": 94775,
"s": 94688,
"text": "To define Audit policy in HANA system, you should have system privilege − Audit Admin."
},
{
"code": null,
"e": 94823,
"s": 94775,
"text": "Go to Security option in HANA system → Auditing"
},
{
"code": null,
"e": 94879,
"s": 94823,
"text": "Under Global Settings → set Auditing status as enabled."
},
{
"code": null,
"e": 94969,
"s": 94879,
"text": "You can also choose Audit trail targets. The following audit trail targets are possible −"
},
{
"code": null,
"e": 95030,
"s": 94969,
"text": "Syslog (default) − Logging system of Linux Operating System."
},
{
"code": null,
"e": 95091,
"s": 95030,
"text": "Syslog (default) − Logging system of Linux Operating System."
},
{
"code": null,
"e": 95241,
"s": 95091,
"text": "Database Table − Internal database table, user who has Audit admin or Audit operator system privilege he can only run select operation on this table."
},
{
"code": null,
"e": 95391,
"s": 95241,
"text": "Database Table − Internal database table, user who has Audit admin or Audit operator system privilege he can only run select operation on this table."
},
{
"code": null,
"e": 95490,
"s": 95391,
"text": "CSV text − This type of audit trail is only used for test purpose in a non-production environment."
},
{
"code": null,
"e": 95589,
"s": 95490,
"text": "CSV text − This type of audit trail is only used for test purpose in a non-production environment."
},
{
"code": null,
"e": 95728,
"s": 95589,
"text": "You can also create a new Audit policy in the Audit Policies area → choose Create New Policy. Enter Policy name and actions to be audited."
},
{
"code": null,
"e": 95983,
"s": 95728,
"text": "Save the new policy using the Deploy button. A new policy is enabled automatically, when an action condition is met, an audit entry is created in Audit trail table. You can disable a policy by changing status to disable or you can also delete the policy."
},
{
"code": null,
"e": 96177,
"s": 95983,
"text": "SAP HANA Replication allows migration of data from source systems to SAP HANA database. Simple way to move data from existing SAP system to HANA is by using various data replication techniques."
},
{
"code": null,
"e": 96408,
"s": 96177,
"text": "System replication can be set up on the console via command line or by using HANA studio. The primary ECC or transaction systems can stay online during this process. We have three types of data replication methods in HANA system −"
},
{
"code": null,
"e": 96434,
"s": 96408,
"text": "SAP LT Replication method"
},
{
"code": null,
"e": 96490,
"s": 96434,
"text": "ETL tool SAP Business Object Data Service (BODS) method"
},
{
"code": null,
"e": 96531,
"s": 96490,
"text": "Direct Extractor connection method (DXC)"
},
{
"code": null,
"e": 96936,
"s": 96531,
"text": "SAP Landscape Transformation Replication is a trigger based data replication method in HANA system. It is a perfect solution for replicating real time data or schedule based replication from SAP and non-SAP sources. It has SAP LT Replication server, which takes care of all trigger requests. Replication server can be installed as standalone server or can run on any SAP system with SAP NW 7.02 or above."
},
{
"code": null,
"e": 97087,
"s": 96936,
"text": "There is a Trusted RFC connection between HANA DB and ECC transaction system, which enables trigger based data replication in HANA system environment."
},
{
"code": null,
"e": 97240,
"s": 97087,
"text": "SLT Replication method allows data replication from multiple source systems to one HANA system and also from one source system to multiple HANA systems."
},
{
"code": null,
"e": 97393,
"s": 97240,
"text": "SLT Replication method allows data replication from multiple source systems to one HANA system and also from one source system to multiple HANA systems."
},
{
"code": null,
"e": 97488,
"s": 97393,
"text": "SAP LT uses trigger based approach. It has no measureable performance impact in source system."
},
{
"code": null,
"e": 97583,
"s": 97488,
"text": "SAP LT uses trigger based approach. It has no measureable performance impact in source system."
},
{
"code": null,
"e": 97678,
"s": 97583,
"text": "It also provides data transformation and filtering capability before loading to HANA database."
},
{
"code": null,
"e": 97773,
"s": 97678,
"text": "It also provides data transformation and filtering capability before loading to HANA database."
},
{
"code": null,
"e": 97889,
"s": 97773,
"text": "It allows real-time data replication, replicating only relevant data into HANA from SAP and non-SAP source systems."
},
{
"code": null,
"e": 98005,
"s": 97889,
"text": "It allows real-time data replication, replicating only relevant data into HANA from SAP and non-SAP source systems."
},
{
"code": null,
"e": 98062,
"s": 98005,
"text": "It is fully integrated with HANA System and HANA studio."
},
{
"code": null,
"e": 98119,
"s": 98062,
"text": "It is fully integrated with HANA System and HANA studio."
},
{
"code": null,
"e": 98414,
"s": 98119,
"text": "On your source SAP system AA1 you want to setup a trusted RFC towards target system BB1. When it is done, it would mean that when you are logged onto AA1 and your user has enough authorization in BB1, you can use the RFC connection and logon to BB1 without having to re-enter user and password."
},
{
"code": null,
"e": 98590,
"s": 98414,
"text": "Using RFC trusted/trusting relationship between two SAP systems, RFC from a trusted system to a trusting system, password is no required for logging on to the trusting system."
},
{
"code": null,
"e": 98821,
"s": 98590,
"text": "Open SAP ECC system using SAP logon. Enter transaction number sm59 → this is transaction number to create a new Trusted RFC connection → Click on 3rd icon to open a new connection wizard → click on Create and new window will open."
},
{
"code": null,
"e": 98915,
"s": 98821,
"text": "RFC Destination ECCHANA (enter name of RFC destination) Connection Type − 3 (for ABAP system)"
},
{
"code": null,
"e": 98980,
"s": 98915,
"text": "Enter Target host − ECC system name, IP and enter System number."
},
{
"code": null,
"e": 99067,
"s": 98980,
"text": "Go to Logon & Security tab, Enter Language, Client, ECC system user name and password."
},
{
"code": null,
"e": 99104,
"s": 99067,
"text": "Click on the Save option at the top."
},
{
"code": null,
"e": 99175,
"s": 99104,
"text": "Click on Test Connection and it will successfully test the connection."
},
{
"code": null,
"e": 99304,
"s": 99175,
"text": "Run transaction − ltr (to configure RFC connection) → New browser will open → enter ECC system user name and password and logon."
},
{
"code": null,
"e": 99486,
"s": 99304,
"text": "Click on New → New Window will open → Enter configuration name → Click Next → Enter RFC Destination (connection name created earlier), Use search option, choose name and click next."
},
{
"code": null,
"e": 99690,
"s": 99486,
"text": "In Specify Target system, Enter HANA system admin user name & password, host name, Instance number and click next. Enter No of Data transfer jobs like 007(it cannot be 000) → Next → Create Configuration."
},
{
"code": null,
"e": 99737,
"s": 99690,
"text": "Now go to HANA Studio to use this connection −"
},
{
"code": null,
"e": 99805,
"s": 99737,
"text": "Go to HANA Studio → Click on Data Provisioning → choose HANA system"
},
{
"code": null,
"e": 99993,
"s": 99805,
"text": "Select source system (name of trusted RFC connection) and target schema name where you want to load tables from ECC system. Select tables you want to move to HANA database → ADD → Finish."
},
{
"code": null,
"e": 100057,
"s": 99993,
"text": "Selected tables will move to chosen schema under HANA database."
},
{
"code": null,
"e": 100291,
"s": 100057,
"text": "SAP HANA ETL based replication uses SAP Data Services to migrate data from SAP or non-SAP source system to target HANA database. BODS system is an ETL tool used to extract, transform and load data from source system to target system."
},
{
"code": null,
"e": 100506,
"s": 100291,
"text": "It enables to read the business data at Application layer. You need to define data flows in Data Services, scheduling a replication job and defining source and target system in data store in Data Services designer."
},
{
"code": null,
"e": 100578,
"s": 100506,
"text": "Login to Data Services Designer (choose Repository) → Create Data store"
},
{
"code": null,
"e": 100776,
"s": 100578,
"text": "For SAP ECC system, choose database as SAP Applications, enter ECC server name, user name and password for ECC system, Advanced tab choose details as instance number, client number, etc. and apply."
},
{
"code": null,
"e": 100878,
"s": 100776,
"text": "This data store will come under local object library, if you expand this there is no table inside it."
},
{
"code": null,
"e": 101111,
"s": 100878,
"text": "Right click on Table → Import by name → Enter ECC table to import from ECC system (MARA is default table in ECC system) → Import → Now expand Table → MARA → Right Click View Data. If data is displayed, Data store connection is fine."
},
{
"code": null,
"e": 101319,
"s": 101111,
"text": "Now, to choose target system as HANA database, create a new data store. Create Data store → Name of data store SAP_HANA_TEST → Data store type (database) → Database type SAP HANA → Database version HANA 1.x."
},
{
"code": null,
"e": 101390,
"s": 101319,
"text": "Enter HANA server name, user name and password for HANA system and OK."
},
{
"code": null,
"e": 101617,
"s": 101390,
"text": "This data store will be added to Local Object Library. You can add table if you want to move data from source table to some specific table in HANA database. Note that target table should be of similar datatype as source table."
},
{
"code": null,
"e": 101723,
"s": 101617,
"text": "Create a new Project → Enter Project Name → Right Click on Project name → New Batch Job → Enter job name."
},
{
"code": null,
"e": 101947,
"s": 101723,
"text": "From right side tab, choose work flow → Enter work flow name → Double click to add it under batch job → Enter data flow → Enter data flow name → Double click to add it under batch job in Project area Save all option at top."
},
{
"code": null,
"e": 102191,
"s": 101947,
"text": "Drag table from First Data Store ECC (MARA) to work area. Select it and right click → Add new → Template table to create new table with similar data types in HANA DB → Enter table name, Data store ECC_HANA_TEST2 → Owner name (schema name) → OK"
},
{
"code": null,
"e": 102305,
"s": 102191,
"text": "Drag table to front and connect both the table → save all. Now go to batch job → Right Click → Execute → Yes → OK"
},
{
"code": null,
"e": 102413,
"s": 102305,
"text": "Once you execute the Replication job, you will get a confirmation that job has been completed successfully."
},
{
"code": null,
"e": 102512,
"s": 102413,
"text": "Go to HANA studio → Expand Schema → Tables → Verify data. This is manual execution of a batch job."
},
{
"code": null,
"e": 102635,
"s": 102512,
"text": "You can also schedule a batch job by going to Data Services Management console. Login to Data Services Management Console."
},
{
"code": null,
"e": 102940,
"s": 102635,
"text": "Choose the repository from left side → Navigate to 'Batch Job Configuration' tab, where you will see the list of jobs → Against the job you want to schedule → click on add schedule → Enter the 'schedule name' and set the parameters like (time, date, reoccurring etc.) as appropriate and click on 'Apply'."
},
{
"code": null,
"e": 103228,
"s": 102940,
"text": "This is also known as Sybase Replication in HANA system. The main components of this replication method are the Sybase Replication Agent, which is part of the SAP source application system, Replication agent and the Sybase Replication Server that is to be implemented in SAP HANA system."
},
{
"code": null,
"e": 103615,
"s": 103228,
"text": "Initial Load in Sybase Replication method is initiated by Load Controller and triggered by the administrator, in SAP HANA. It informs R3 Load to transfer initial load to HANA database. The R3 load on source system exports data for selected tables in source system and transfer this data to R3 load components in HANA system. R3 load on target system imports data into SAP HANA database."
},
{
"code": null,
"e": 104033,
"s": 103615,
"text": "SAP Host agent manages the authentication between the source system and target system, which is part of the source system. The Sybase Replication agent detects any data changes at time of initial load and ensures every single change is completed. When th\tere is a change, update, and delete in entries of a table in source system, a table log is created. This table log moves data from source system to HANA database."
},
{
"code": null,
"e": 104294,
"s": 104033,
"text": "The delta replication captures the data changes in source system in real time once the initial load and replication is completed. All further changes in source system are captured and replicated from source system to HANA database using above-mentioned method."
},
{
"code": null,
"e": 104478,
"s": 104294,
"text": "This method was part of initial offering for SAP HANA replication, but not positioned/supported anymore due to licensing issues and complexity and also SLT provides the same features."
},
{
"code": null,
"e": 104562,
"s": 104478,
"text": "Note − This method only supports SAP ERP system as data source and DB2 as database."
},
{
"code": null,
"e": 104917,
"s": 104562,
"text": "Direct Extractor Connection data replication reuses existing extraction, transformation, and load mechanism built into SAP Business Suite systems via a simple HTTP(S) connection to SAP HANA. It is a batch-driven data replication technique. It is considered as method for extraction, transformation, and load with limited capabilities for data extraction."
},
{
"code": null,
"e": 105200,
"s": 104917,
"text": "DXC is a batch driven process and data extraction using DXC at certain interval is enough in many cases. You can set an interval when batch job executes example: every 20 minutes and in most of cases it is sufficient to extract data using these batch jobs at certain time intervals."
},
{
"code": null,
"e": 105291,
"s": 105200,
"text": "This method requires no additional server or application in the SAP HANA system landscape."
},
{
"code": null,
"e": 105382,
"s": 105291,
"text": "This method requires no additional server or application in the SAP HANA system landscape."
},
{
"code": null,
"e": 105526,
"s": 105382,
"text": "DXC method reduces complexity of data modeling in SAP HANA as data sends to HANA after applying all business extractor logics in Source System."
},
{
"code": null,
"e": 105670,
"s": 105526,
"text": "DXC method reduces complexity of data modeling in SAP HANA as data sends to HANA after applying all business extractor logics in Source System."
},
{
"code": null,
"e": 105734,
"s": 105670,
"text": "It speeds up the time lines for SAP HANA implementation project"
},
{
"code": null,
"e": 105798,
"s": 105734,
"text": "It speeds up the time lines for SAP HANA implementation project"
},
{
"code": null,
"e": 105869,
"s": 105798,
"text": "It provides semantically rich data from SAP Business Suite to SAP HANA"
},
{
"code": null,
"e": 105940,
"s": 105869,
"text": "It provides semantically rich data from SAP Business Suite to SAP HANA"
},
{
"code": null,
"e": 106102,
"s": 105940,
"text": "It reuses existing proprietary extraction, transformation, and load mechanism built into SAP business Suite systems over a simple HTTP(S) connection to SAP HANA."
},
{
"code": null,
"e": 106264,
"s": 106102,
"text": "It reuses existing proprietary extraction, transformation, and load mechanism built into SAP business Suite systems over a simple HTTP(S) connection to SAP HANA."
},
{
"code": null,
"e": 106383,
"s": 106264,
"text": "Data Source must have a predefined mechanism for extraction, transformation and load and if not we need to define one."
},
{
"code": null,
"e": 106502,
"s": 106383,
"text": "Data Source must have a predefined mechanism for extraction, transformation and load and if not we need to define one."
},
{
"code": null,
"e": 106649,
"s": 106502,
"text": "It requires a Business Suite System based on Net Weaver 7.0 or higher with at least below SP: Release 700 SAPKW70021 (SP stack 19, from Nov 2008)."
},
{
"code": null,
"e": 106796,
"s": 106649,
"text": "It requires a Business Suite System based on Net Weaver 7.0 or higher with at least below SP: Release 700 SAPKW70021 (SP stack 19, from Nov 2008)."
},
{
"code": null,
"e": 106975,
"s": 106796,
"text": "Enabling XS Engine service in Configuration tab in HANA Studio − Go to Administrator tab in HANA studio of system. Go to Configuration → xsengine.ini and set instance value to 1."
},
{
"code": null,
"e": 107097,
"s": 106975,
"text": "Enabling ICM Web Dispatcher service in HANA Studio − Go to Configuration → webdispatcher.ini and set instance value to 1."
},
{
"code": null,
"e": 107224,
"s": 107097,
"text": "It enables ICM Web Dispatcher service in HANA system. Web dispatcher uses ICM method for data read and loading in HANA system."
},
{
"code": null,
"e": 107392,
"s": 107224,
"text": "Setup SAP HANA Direct Extractor Connection − Download the DXC delivery unit into SAP HANA. You can import the unit in the location /usr/sap/HDB/SYS/global/hdb/content."
},
{
"code": null,
"e": 107559,
"s": 107392,
"text": "Import the unit using Import Dialog in SAP HANA Content Node → Configure XS Application server to utilize the DXC → Change the application_container value to libxsdxc"
},
{
"code": null,
"e": 107675,
"s": 107559,
"text": "Creating a HTTP connection in SAP BW − Now we need to create http connection in SAP BW using transaction code SM59."
},
{
"code": null,
"e": 107761,
"s": 107675,
"text": "Input Parameters − Enter Name of RFC Connection, HANA Host Name and <Instance Number>"
},
{
"code": null,
"e": 107863,
"s": 107761,
"text": "In Log on Security Tab, enter the DXC user created in HANA studio using basic Authentication method −"
},
{
"code": null,
"e": 107987,
"s": 107863,
"text": "Setting up BW Parameters for HANA − Need to Setup the Following Parameters in BW Using transaction SE 38. Parameters List −"
},
{
"code": null,
"e": 108109,
"s": 107987,
"text": "PSA_TO_HDB_DESTINATION − we need to mention where we need to move the Incoming data (Connection Name created using SM 59)"
},
{
"code": null,
"e": 108231,
"s": 108109,
"text": "PSA_TO_HDB_DESTINATION − we need to mention where we need to move the Incoming data (Connection Name created using SM 59)"
},
{
"code": null,
"e": 108302,
"s": 108231,
"text": "PSA_TO_HDB_SCHEMA − To which Schema the replicated data need to assign"
},
{
"code": null,
"e": 108373,
"s": 108302,
"text": "PSA_TO_HDB_SCHEMA − To which Schema the replicated data need to assign"
},
{
"code": null,
"e": 108523,
"s": 108373,
"text": "PSA_TO_HDB − GLOBAL To Replicate All data source to HANA. SYSTEM – Specified clients to Use DXC. DATASOURCE – Only Specified Data Source are used for"
},
{
"code": null,
"e": 108673,
"s": 108523,
"text": "PSA_TO_HDB − GLOBAL To Replicate All data source to HANA. SYSTEM – Specified clients to Use DXC. DATASOURCE – Only Specified Data Source are used for"
},
{
"code": null,
"e": 108786,
"s": 108673,
"text": "PSA_TO_HDB_DATASOURCETABLE − Need to Give the Table name having the List of data sources which are used for DXC."
},
{
"code": null,
"e": 108899,
"s": 108786,
"text": "PSA_TO_HDB_DATASOURCETABLE − Need to Give the Table name having the List of data sources which are used for DXC."
},
{
"code": null,
"e": 108938,
"s": 108899,
"text": "Install data source in ECC using RSA5."
},
{
"code": null,
"e": 109222,
"s": 108938,
"text": "Replicate the metadata using specified application component (data source version Need to 7.0, if we have 3.5 version data source we need to migrate that. Active the data Source in SAP BW. Once data source is activated in SAP BW it will create the following Table in Defined schema −"
},
{
"code": null,
"e": 109265,
"s": 109222,
"text": "/BIC/A<data source>00 – IMDSO Active Table"
},
{
"code": null,
"e": 109308,
"s": 109265,
"text": "/BIC/A<data source>00 – IMDSO Active Table"
},
{
"code": null,
"e": 109354,
"s": 109308,
"text": "/BIC/A<data source>40 –IMDSO Activation Queue"
},
{
"code": null,
"e": 109400,
"s": 109354,
"text": "/BIC/A<data source>40 –IMDSO Activation Queue"
},
{
"code": null,
"e": 109451,
"s": 109400,
"text": "/BIC/A<data source>70 – Record Mode Handling Table"
},
{
"code": null,
"e": 109502,
"s": 109451,
"text": "/BIC/A<data source>70 – Record Mode Handling Table"
},
{
"code": null,
"e": 109566,
"s": 109502,
"text": "/BIC/A<data source>80 – Request and Packet ID information Table"
},
{
"code": null,
"e": 109630,
"s": 109566,
"text": "/BIC/A<data source>80 – Request and Packet ID information Table"
},
{
"code": null,
"e": 109678,
"s": 109630,
"text": "/BIC/A<data source>A0 – Request Timestamp Table"
},
{
"code": null,
"e": 109726,
"s": 109678,
"text": "/BIC/A<data source>A0 – Request Timestamp Table"
},
{
"code": null,
"e": 109821,
"s": 109726,
"text": "RSODSO_IMOLOG - IMDSO related table. Stores information about all data sources related to DXC."
},
{
"code": null,
"e": 109916,
"s": 109821,
"text": "RSODSO_IMOLOG - IMDSO related table. Stores information about all data sources related to DXC."
},
{
"code": null,
"e": 109999,
"s": 109916,
"text": "Now data is successfully loaded into Table /BIC/A0FI_AA_2000 once it is activated."
},
{
"code": null,
"e": 110068,
"s": 109999,
"text": "Open SAP HANA Studio → Create Schema under Catalog tab. <Start here>"
},
{
"code": null,
"e": 110173,
"s": 110068,
"text": "Prepare the data and save it to csv format. Now create file with “ctl” extension with following syntax −"
},
{
"code": null,
"e": 110414,
"s": 110173,
"text": "---------------------------------------\nimport data into table Schema.\"Table name\"\nfrom 'file.csv'\nrecords delimited by '\\n'\nfields delimited by ','\nOptionally enclosed by '\"'\nerror log 'table.err'\n-----------------------------------------\n"
},
{
"code": null,
"e": 110493,
"s": 110414,
"text": "Transfer this “ctl” file to the FTP and execute this file to import the data −"
},
{
"code": null,
"e": 110517,
"s": 110493,
"text": "import from ‘table.ctl’"
},
{
"code": null,
"e": 110604,
"s": 110517,
"text": "Check data in table by going to HANA Studio → Catalog → Schema → Tables → View Content"
},
{
"code": null,
"e": 110874,
"s": 110604,
"text": "MDX Provider is used to connect MS Excel to SAP HANA database system. It provides driver to connect HANA system to Excel and is further, used for data modelling. You can use Microsoft Office Excel 2010/2013 for connectivity with HANA for both 32 bit and 64 bit Windows."
},
{
"code": null,
"e": 111320,
"s": 110874,
"text": "SAP HANA supports both query languages − SQL and MDX. Both languages can be used: JDBC and ODBC for SQL and ODBO is used for MDX processing. Excel Pivot tables use MDX as query language to read data from SAP HANA system. MDX is defined as part of ODBO (OLE DB for OLAP) specification from Microsoft and is used for data selections, calculations and layout. MDX supports multidimensional data model and support reporting and Analysis requirement."
},
{
"code": null,
"e": 111527,
"s": 111320,
"text": "MDX provider enables the consumption of Information views defined in HANA studio by SAP and non-SAP reporting tools. Existing physical tables and schemas presents the data foundation for Information models."
},
{
"code": null,
"e": 111697,
"s": 111527,
"text": "Once you choose SAP HANA MDX provider from the list of data source you want to connect, pass HANA system details like host name, instance number, user name and password."
},
{
"code": null,
"e": 111808,
"s": 111697,
"text": "Once the connection is successful, you can choose Package name → HANA Modeling views to generate Pivot tables."
},
{
"code": null,
"e": 112224,
"s": 111808,
"text": "MDX is tightly integrated into HANA database. Connection and Session management of HANA database handles statements that are executed by HANA. When these statements are executed, they are parsed by MDX interface and a calculation model is generated for each MDX statement. This calculation model creates an execution plan that generates standard results for MDX. These results are directly consumed by OLAP clients."
},
{
"code": null,
"e": 112485,
"s": 112224,
"text": "To make MDX connection to HANA database, HANA client tools are required. You can download this client tool from SAP market place. Once installation of HANA client is done, you will see the option of SAP HANA MDX provider in the list of data source in MS Excel."
},
{
"code": null,
"e": 112946,
"s": 112485,
"text": "SAP HANA alert monitoring is used to monitor the status of system resources and services that are running in the HANA system. Alert monitoring is used to handle critical alerts like CPU usage, disk full, FS reaching threshold, etc. The monitoring component of HANA system continuously collects information about health, usage and performance of all the components of HANA database. It raises an alert when any of the component breaches the set threshold value."
},
{
"code": null,
"e": 113224,
"s": 112946,
"text": "The priority of alert raised in HANA system tells the criticality of problem and it depends on the check that is performed on the component. Example − If CPU usage is 80%, a low priority alert will be raised. However, if it reaches 96%, system will raise a high priority alert."
},
{
"code": null,
"e": 113441,
"s": 113224,
"text": "The System Monitor is the most common way to monitor HANA system and to verify the availability of all your SAP HANA system components. System monitor is used to check all key component and services of a HANA system."
},
{
"code": null,
"e": 113616,
"s": 113441,
"text": "You can also drill down into details of an individual system in Administration Editor. It tells about Data Disk, Log disk, Trace Disk, alerts on resource usage with priority."
},
{
"code": null,
"e": 113710,
"s": 113616,
"text": "Alert tab in Administrator editor is used to check the current and all alerts in HANA system."
},
{
"code": null,
"e": 113818,
"s": 113710,
"text": "It also tells about the time when an alert is raised, description of the alert, priority of the alert, etc."
},
{
"code": null,
"e": 113907,
"s": 113818,
"text": "SAP HANA monitoring dashboard tells the key aspects of system health and configuration −"
},
{
"code": null,
"e": 113940,
"s": 113907,
"text": "High and Medium priority alerts."
},
{
"code": null,
"e": 113961,
"s": 113940,
"text": "Memory and CPU usage"
},
{
"code": null,
"e": 113974,
"s": 113961,
"text": "Data backups"
},
{
"code": null,
"e": 114127,
"s": 113974,
"text": "SAP HANA database persistence layer is responsible to manage logs for all the transactions to provide standard data back up and system restore function."
},
{
"code": null,
"e": 114636,
"s": 114127,
"text": "It ensures that database can be restored to the most recent committed state after a restart or after a system crash and transactions are executed completely or completely undone. SAP HANA Persistent Layer is part of Index server and it has data and transaction log volumes for HANA system and in-memory data is regularly saved to these volumes. There are services in HANA system that has their own persistence. It also provides save points and logs for all the database transactions from the last save point."
},
{
"code": null,
"e": 114717,
"s": 114636,
"text": "Main memory is volatile therefore data is lost during a restart or power outage."
},
{
"code": null,
"e": 114798,
"s": 114717,
"text": "Main memory is volatile therefore data is lost during a restart or power outage."
},
{
"code": null,
"e": 114843,
"s": 114798,
"text": "Data needs to be stored in persisted medium."
},
{
"code": null,
"e": 114888,
"s": 114843,
"text": "Data needs to be stored in persisted medium."
},
{
"code": null,
"e": 114919,
"s": 114888,
"text": "Backup & Restore is available."
},
{
"code": null,
"e": 114950,
"s": 114919,
"text": "Backup & Restore is available."
},
{
"code": null,
"e": 115116,
"s": 114950,
"text": "It ensures that the database is restored to the most recent committed state after a restart and that transaction are either completely executed or completely undone."
},
{
"code": null,
"e": 115282,
"s": 115116,
"text": "It ensures that the database is restored to the most recent committed state after a restart and that transaction are either completely executed or completely undone."
},
{
"code": null,
"e": 115570,
"s": 115282,
"text": "Database can always be restored to its most recent state, to ensure these changes to data in the database are regularly copied to disk. Log files containing data changes and certain transaction events are also saved regularly to disk. Data and logs of a system are stored in Log volumes."
},
{
"code": null,
"e": 115833,
"s": 115570,
"text": "Data volumes stores SQL data and undo log information and also SAP HANA information modeling data. This information is stored in data pages, which are called Blocks. These blocks are written to data volumes at regular time interval, which is known as save point."
},
{
"code": null,
"e": 116043,
"s": 115833,
"text": "Log volumes store the information about data changes. Changes that are made between two log points are written to Log volumes and called log entries. They are saved to log buffer when transaction is committed."
},
{
"code": null,
"e": 116410,
"s": 116043,
"text": "In SAP HANA database, changed data is automatically saved from memory to disk. These regular intervals are called savepoints and by default they are set to occur every five minutes. Persistence Layer in SAP HANA database performs these savepoint at regular interval. During this operation changed data is written to disk and redo logs are also saved to disk as well."
},
{
"code": null,
"e": 116798,
"s": 116410,
"text": "The data belonging to a Savepoint tells consistent state of the data on disk and remains there until the next savepoint operation has completed. Redo log entries are written to the log volumes for all changes to persistent data. In the event of a database restart, data from the last completed savepoint can be read from the data volumes, and redo log entries written to the log volumes."
},
{
"code": null,
"e": 117010,
"s": 116798,
"text": "Frequency of savepoint can be configured by global.ini file. Savepoints can be initiated by other operations like database shut down or system restart. You can also run savepoint by executing the below command −"
},
{
"code": null,
"e": 117213,
"s": 117010,
"text": "To save data and redo logs to log volumes, you should ensure that there is enough disk space available to capture these, otherwise the system will issue a disk full event and database will stop working."
},
{
"code": null,
"e": 117343,
"s": 117213,
"text": "During the HANA system installation, following default directories are created as the storage location for data and log volumes −"
},
{
"code": null,
"e": 117378,
"s": 117343,
"text": "/usr/sap/<SID>/SYS/global/hdb/data"
},
{
"code": null,
"e": 117412,
"s": 117378,
"text": "/usr/sap/<SID>/SYS/global/hdb/log"
},
{
"code": null,
"e": 117496,
"s": 117412,
"text": "These directories are defined in global.ini file and can be changed at later stage."
},
{
"code": null,
"e": 117768,
"s": 117496,
"text": "Note that Savepoints do not affect the performance of transactions executed in HANA system. During a savepoint operation, transactions continue to run as normal. With HANA system running on proper hardware, impact of savepoints on the performance of system is negligible."
},
{
"code": null,
"e": 117892,
"s": 117768,
"text": "SAP HANA backup and recovery is used to perform HANA system backups and recovery of system in case of any database failure."
},
{
"code": null,
"e": 117978,
"s": 117892,
"text": "It tells the status of currently running data backup and last successful data backup."
},
{
"code": null,
"e": 118035,
"s": 117978,
"text": "Backup now option can be used to run data backup wizard."
},
{
"code": null,
"e": 118147,
"s": 118035,
"text": "It tells about the Backup interval settings, file based data backup settings and log based data backup setting."
},
{
"code": null,
"e": 118265,
"s": 118147,
"text": "Backint settings give an option to use third party tool for data and log back up with configuration of backing agent."
},
{
"code": null,
"e": 118373,
"s": 118265,
"text": "Configure the connection to a third-party backup tool by specifying a parameter file for the Backint agent."
},
{
"code": null,
"e": 118511,
"s": 118373,
"text": "File based data backup setting tells the folder where you want to save the data backup on HANA system. You can change your backup folder."
},
{
"code": null,
"e": 118652,
"s": 118511,
"text": "You can also limit the size of data backup files. If system data backup exceeds this set file size, it will split across the multiple files."
},
{
"code": null,
"e": 118803,
"s": 118652,
"text": "Log backup settings tell the destination folder where you want to save log backup on external server. You can choose a destination type for log backup"
},
{
"code": null,
"e": 118867,
"s": 118803,
"text": "File − ensures that sufficient space in system to store backups"
},
{
"code": null,
"e": 118948,
"s": 118867,
"text": "Backint − is special named pipe exists on file system but require no disk space."
},
{
"code": null,
"e": 119138,
"s": 118948,
"text": "You can choose backup interval from drop down. It tells the longest amount of time that can pass before a new log backup is written. Backup Interval: It can be in seconds, minutes or hours."
},
{
"code": null,
"e": 119301,
"s": 119138,
"text": "Enable Automatic log backup option: It helps you to keep log area vacant. If you disable this log area will continue to fill and that can result database to hang."
},
{
"code": null,
"e": 119351,
"s": 119301,
"text": "Open Backup Wizard − to run the backup of system."
},
{
"code": null,
"e": 119508,
"s": 119351,
"text": "Backup wizard is used to specify backup settings. It tells the Backup type, destination Type, Backup Destination folder, Backup prefix, size of backup, etc."
},
{
"code": null,
"e": 119565,
"s": 119508,
"text": "When you click on next → Review Backup settings → Finish"
},
{
"code": null,
"e": 119651,
"s": 119565,
"text": "It runs the system backups and tells the time to complete backup for the each server."
},
{
"code": null,
"e": 119799,
"s": 119651,
"text": "To recover SAP HANA database, the database needs to be shut down. Hence, during recovery, end users or SAP applications cannot access the database."
},
{
"code": null,
"e": 119871,
"s": 119799,
"text": "Recovery of SAP HANA database is required in the following situations −"
},
{
"code": null,
"e": 119944,
"s": 119871,
"text": "A disk in the data area is unusable or disk in the log area is unusable."
},
{
"code": null,
"e": 120017,
"s": 119944,
"text": "A disk in the data area is unusable or disk in the log area is unusable."
},
{
"code": null,
"e": 120129,
"s": 120017,
"text": "As a consequence of a logical error, the database needs to be reset to its state at a particular point in time."
},
{
"code": null,
"e": 120241,
"s": 120129,
"text": "As a consequence of a logical error, the database needs to be reset to its state at a particular point in time."
},
{
"code": null,
"e": 120284,
"s": 120241,
"text": "You want to create a copy of the database."
},
{
"code": null,
"e": 120327,
"s": 120284,
"text": "You want to create a copy of the database."
},
{
"code": null,
"e": 120397,
"s": 120327,
"text": "Choose HANA system → Right click → Back and Recovery → Recover System"
},
{
"code": null,
"e": 120660,
"s": 120397,
"text": "Most Recent State − Used for recovering the database to the time as close as possible to the current time. For this recovery, the data backup and log backup have to be available since last data backup and log area are required to perform the above type recovery."
},
{
"code": null,
"e": 120895,
"s": 120660,
"text": "Point in Time − Used for recovering the database to the specific point in time. For this recovery, the data backup and log backup have to be available since last data backup and log area are required to perform the above type recovery"
},
{
"code": null,
"e": 121051,
"s": 120895,
"text": "Specific Data Backup − Used for recovering the database to a specified data backup. Specific data backup is required for the above type of recovery option."
},
{
"code": null,
"e": 121188,
"s": 121051,
"text": "Specific Log Position − This recovery type is an advanced option that can be used in exceptional cases where a previous recovery failed."
},
{
"code": null,
"e": 121275,
"s": 121188,
"text": "Note − To run recovery wizard you should have administrator privileges on HANA system."
},
{
"code": null,
"e": 121612,
"s": 121275,
"text": "SAP HANA provides mechanism for business continuity and disaster recovery for system faults and software errors. High availability in HANA system defines set of practices that helps to achieve business continuity in case of disaster like power failures in data centers, natural disasters like fire, flood, etc. or any hardware failures."
},
{
"code": null,
"e": 121758,
"s": 121612,
"text": "SAP HANA high availability provides fault tolerance and ability of system to resume system operations after an outage with minimum business loss."
},
{
"code": null,
"e": 121840,
"s": 121758,
"text": "The following illustration shows the phases of high availability in HANA system −"
},
{
"code": null,
"e": 122151,
"s": 121840,
"text": "First phase is being prepared for the fault. A fault can be detected automatically or by an administrative action. Data is backed up and stand by systems take over the operations. A recovery process is put in action includes repair of faulty system and original system to be restored to previous configuration."
},
{
"code": null,
"e": 122484,
"s": 122151,
"text": "To achieve high availability in HANA system, key is the inclusion of extra components, which are not necessary to function and use in case of failure of other components. It includes hardware redundancy, network redundancy and data center redundancy. SAP HANA provides several levels of hardware and software redundancies as below −"
},
{
"code": null,
"e": 122925,
"s": 122484,
"text": "SAP HANA appliance vendors offer multiple layers of redundant hardware, software and network components, such as redundant power supplies and fans, error-correcting memories, fully redundant network switches and routers, and uninterrupted power supply (UPS). Disk storage system guarantees writing even in the presence of power failure and use striping and mirroring features to provide redundancy for automatic recovery from disk failures."
},
{
"code": null,
"e": 123021,
"s": 122925,
"text": "SAP HANA is based on SUSE Linux Enterprise 11 for SAP and includes security pre-configurations."
},
{
"code": null,
"e": 123215,
"s": 123021,
"text": "SAP HANA system software includes a watchdog function, which automatically restarts configured services (index server, name server, and so on), in case of detected stoppage (killed or crashed)."
},
{
"code": null,
"e": 123390,
"s": 123215,
"text": "SAP HANA provides persistence of transaction logs, savepoints and snapshots to support system restart and recovery from failures, with minimal delay and without loss of data."
},
{
"code": null,
"e": 123600,
"s": 123390,
"text": "SAP HANA system involves separate standby hosts that are used for failover, in case of failure of the primary system. This improves the availability of HANA system by reducing the recovery time from an outage."
},
{
"code": null,
"e": 123951,
"s": 123600,
"text": "The SAP HANA system logs all the transactions that change application data or the database catalog in log entries and stores them in log area. It uses these log entries in log area to roll back or repeat SQL statements. The log files are available in HANA system and can be accessed via HANA studio on Diagnosis files page under Administrator editor."
},
{
"code": null,
"e": 124120,
"s": 123951,
"text": "During a log backup process, only the actual data of the log segments is written from the log area to service-specific log backup files or to a third-party backup tool."
},
{
"code": null,
"e": 124240,
"s": 124120,
"text": "After a system failure, you may need to redo log entries from log backups to restore the database to the desired state."
},
{
"code": null,
"e": 124413,
"s": 124240,
"text": "If a database service with persistence stops, it is important to ensure that it is restarted, otherwise recovery will be possible only to a point before service is stopped."
},
{
"code": null,
"e": 124633,
"s": 124413,
"text": "The log backup timeout determines the interval at which the log segments are backed up if a commit has taken place in this interval. You can configure the log backup timeout using the Backup Console in SAP HANA studio −"
},
{
"code": null,
"e": 124728,
"s": 124633,
"text": "You can also configure the log_backup_timeout_s interval in the global.ini configuration file."
},
{
"code": null,
"e": 124973,
"s": 124728,
"text": "The log backup to the “File” and backup mode “NORMAL” are the default settings for the automatic log backup function after installation of SAP HANA system. Automatic log backup only works if at least one complete data backup has been performed."
},
{
"code": null,
"e": 125313,
"s": 124973,
"text": "Once the first complete data backup has been performed, the automatic log backup function is active. SAP HANA studio can be used to enable/disable the automatic log backup function. It is recommended to keep automatic log backup enabled otherwise log area will continue to fill. A full log area can result a database freeze in HANA system."
},
{
"code": null,
"e": 125435,
"s": 125313,
"text": "You can also change the enable_auto_log_backup parameter in the persistence section of the global.ini configuration file."
},
{
"code": null,
"e": 125477,
"s": 125435,
"text": "SQL stands for Structured Query Language."
},
{
"code": null,
"e": 125622,
"s": 125477,
"text": "It is a standardized language for communicating with a database. SQL is used to retrieve the data, store or manipulate the data in the database."
},
{
"code": null,
"e": 125671,
"s": 125622,
"text": "SQL statements perform the following functions −"
},
{
"code": null,
"e": 125704,
"s": 125671,
"text": "Data definition and manipulation"
},
{
"code": null,
"e": 125722,
"s": 125704,
"text": "System management"
},
{
"code": null,
"e": 125741,
"s": 125722,
"text": "Session management"
},
{
"code": null,
"e": 125764,
"s": 125741,
"text": "Transaction management"
},
{
"code": null,
"e": 125799,
"s": 125764,
"text": "Schema definition and manipulation"
},
{
"code": null,
"e": 125900,
"s": 125799,
"text": "The set of SQL extensions, which allow developers to push data into database, is called SQL scripts."
},
{
"code": null,
"e": 125981,
"s": 125900,
"text": "DML statements are used for managing data within schema objects. Some examples −"
},
{
"code": null,
"e": 126022,
"s": 125981,
"text": "SELECT − retrieve data from the database"
},
{
"code": null,
"e": 126063,
"s": 126022,
"text": "SELECT − retrieve data from the database"
},
{
"code": null,
"e": 126097,
"s": 126063,
"text": "INSERT − insert data into a table"
},
{
"code": null,
"e": 126131,
"s": 126097,
"text": "INSERT − insert data into a table"
},
{
"code": null,
"e": 126177,
"s": 126131,
"text": "UPDATE − updates existing data within a table"
},
{
"code": null,
"e": 126223,
"s": 126177,
"text": "UPDATE − updates existing data within a table"
},
{
"code": null,
"e": 126307,
"s": 126223,
"text": "DDL statements are used to define the database structure or schema. Some examples −"
},
{
"code": null,
"e": 126350,
"s": 126307,
"text": "CREATE − to create objects in the database"
},
{
"code": null,
"e": 126393,
"s": 126350,
"text": "CREATE − to create objects in the database"
},
{
"code": null,
"e": 126438,
"s": 126393,
"text": "ALTER − alters the structure of the database"
},
{
"code": null,
"e": 126483,
"s": 126438,
"text": "ALTER − alters the structure of the database"
},
{
"code": null,
"e": 126523,
"s": 126483,
"text": "DROP − delete objects from the database"
},
{
"code": null,
"e": 126563,
"s": 126523,
"text": "DROP − delete objects from the database"
},
{
"code": null,
"e": 126601,
"s": 126563,
"text": "Some examples of DCL statements are −"
},
{
"code": null,
"e": 126652,
"s": 126601,
"text": "GRANT − gives user's access privileges to database"
},
{
"code": null,
"e": 126703,
"s": 126652,
"text": "GRANT − gives user's access privileges to database"
},
{
"code": null,
"e": 126768,
"s": 126703,
"text": "REVOKE − withdraw access privileges given with the GRANT command"
},
{
"code": null,
"e": 126833,
"s": 126768,
"text": "REVOKE − withdraw access privileges given with the GRANT command"
},
{
"code": null,
"e": 127015,
"s": 126833,
"text": "When we create Information Views in SAP HANA Modeler, we are creating it on top of some OLTP applications. All these in back end run on SQL. Database understands only this language."
},
{
"code": null,
"e": 127164,
"s": 127015,
"text": "To do a testing if our report will meet the business requirement we have to run SQL statement in database if Output is according to the requirement."
},
{
"code": null,
"e": 127340,
"s": 127164,
"text": "HANA Calculation views can be created in two ways - Graphical or using SQL script. When we create more complex Calculation views, then we might have to use direct SQL scripts."
},
{
"code": null,
"e": 127498,
"s": 127340,
"text": "Select the HANA system and click on SQL console option in system view. You can also open SQL console by right click on Catalog tab or any on any Schema name."
},
{
"code": null,
"e": 127818,
"s": 127498,
"text": "SAP HANA can act both as Relational as well as OLAP database. When we use BW on HANA, then we create cubes in BW and HANA, which act as relational database and always produce a SQL Statement. However, when we directly access HANA views using OLAP connection, then it will act as OLAP database and MDX will be generated."
},
{
"code": null,
"e": 128018,
"s": 127818,
"text": "You can create row or Column store tables in SAP HANA using create table option. A table can be created by executing a data definition create table statement or using graphical option in HANA studio."
},
{
"code": null,
"e": 128089,
"s": 128018,
"text": "When you create a table, you also need to define attributes inside it."
},
{
"code": null,
"e": 128150,
"s": 128089,
"text": "SQL statement to create a table in HANA Studio SQL Console −"
},
{
"code": null,
"e": 128236,
"s": 128150,
"text": "Create column Table TEST (\n ID INTEGER,\n NAME VARCHAR(10),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 128287,
"s": 128236,
"text": "Creating a table in HANA studio using GUI option −"
},
{
"code": null,
"e": 128466,
"s": 128287,
"text": "When you create a table, you need to define the names of columns and SQL data types. The Dimension field tells the length of value and the Key option to define it as primary key."
},
{
"code": null,
"e": 128522,
"s": 128466,
"text": "SAP HANA supports the following data types in a table −"
},
{
"code": null,
"e": 128637,
"s": 128522,
"text": "SAP HANA supports 7 categories of SQL data types and it depends on the type of data you have to store in a column."
},
{
"code": null,
"e": 128645,
"s": 128637,
"text": "Numeric"
},
{
"code": null,
"e": 128663,
"s": 128645,
"text": "Character/ String"
},
{
"code": null,
"e": 128671,
"s": 128663,
"text": "Boolean"
},
{
"code": null,
"e": 128681,
"s": 128671,
"text": "Date Time"
},
{
"code": null,
"e": 128688,
"s": 128681,
"text": "Binary"
},
{
"code": null,
"e": 128702,
"s": 128688,
"text": "Large Objects"
},
{
"code": null,
"e": 128715,
"s": 128702,
"text": "Multi-Valued"
},
{
"code": null,
"e": 128783,
"s": 128715,
"text": "The following table gives the list of data types in each category −"
},
{
"code": null,
"e": 128861,
"s": 128783,
"text": "These data types are used to store date and time in a table in HANA database."
},
{
"code": null,
"e": 129012,
"s": 128861,
"text": "DATE − data type consists of year, month and day information to represent a date value in a column. Default format for a Date data type is YYYY-MM-DD."
},
{
"code": null,
"e": 129163,
"s": 129012,
"text": "DATE − data type consists of year, month and day information to represent a date value in a column. Default format for a Date data type is YYYY-MM-DD."
},
{
"code": null,
"e": 129304,
"s": 129163,
"text": "TIME − data type consists of hours, minutes, and seconds value in a table in HANA database. Default format for Time data type is HH: MI: SS."
},
{
"code": null,
"e": 129445,
"s": 129304,
"text": "TIME − data type consists of hours, minutes, and seconds value in a table in HANA database. Default format for Time data type is HH: MI: SS."
},
{
"code": null,
"e": 129619,
"s": 129445,
"text": "SECOND DATE − data type consists of year, month, day, hour, minute, second value in a table in HANA database. Default format for SECONDDATE data type is YYYY-MM-DD HH:MM:SS."
},
{
"code": null,
"e": 129793,
"s": 129619,
"text": "SECOND DATE − data type consists of year, month, day, hour, minute, second value in a table in HANA database. Default format for SECONDDATE data type is YYYY-MM-DD HH:MM:SS."
},
{
"code": null,
"e": 129990,
"s": 129793,
"text": "TIMESTAMP − data type consists of date and time information in a table in HANA database. Default format for TIMESTAMP data type is YYYY-MM-DD HH:MM:SS:FFn, where FFn represents fraction of second."
},
{
"code": null,
"e": 130187,
"s": 129990,
"text": "TIMESTAMP − data type consists of date and time information in a table in HANA database. Default format for TIMESTAMP data type is YYYY-MM-DD HH:MM:SS:FFn, where FFn represents fraction of second."
},
{
"code": null,
"e": 130260,
"s": 130187,
"text": "TinyINT − stores 8 bit unsigned integer. Min value: 0 and max value: 255"
},
{
"code": null,
"e": 130333,
"s": 130260,
"text": "TinyINT − stores 8 bit unsigned integer. Min value: 0 and max value: 255"
},
{
"code": null,
"e": 130415,
"s": 130333,
"text": "SMALLINT − stores 16 bit signed integer. Min value: -32,768 and max value: 32,767"
},
{
"code": null,
"e": 130497,
"s": 130415,
"text": "SMALLINT − stores 16 bit signed integer. Min value: -32,768 and max value: 32,767"
},
{
"code": null,
"e": 130592,
"s": 130497,
"text": "Integer − stores 32 bit signed integer. Min value: -2,147,483,648 and max value: 2,147,483,648"
},
{
"code": null,
"e": 130687,
"s": 130592,
"text": "Integer − stores 32 bit signed integer. Min value: -2,147,483,648 and max value: 2,147,483,648"
},
{
"code": null,
"e": 130805,
"s": 130687,
"text": "BIGINT − stores 64 bit signed integer. Min value: -9,223,372,036,854,775,808 and max value: 9,223,372,036,854,775,808"
},
{
"code": null,
"e": 130923,
"s": 130805,
"text": "BIGINT − stores 64 bit signed integer. Min value: -9,223,372,036,854,775,808 and max value: 9,223,372,036,854,775,808"
},
{
"code": null,
"e": 130997,
"s": 130923,
"text": "SMALL − Decimal and Decimal: Min value: -10^38 +1 and max value: 10^38 -1"
},
{
"code": null,
"e": 131071,
"s": 130997,
"text": "SMALL − Decimal and Decimal: Min value: -10^38 +1 and max value: 10^38 -1"
},
{
"code": null,
"e": 131126,
"s": 131071,
"text": "REAL − Min Value:-3.40E + 38 and max value: 3.40E + 38"
},
{
"code": null,
"e": 131181,
"s": 131126,
"text": "REAL − Min Value:-3.40E + 38 and max value: 3.40E + 38"
},
{
"code": null,
"e": 131300,
"s": 131181,
"text": "DOUBLE − stores 64 bit floating point number. Min value: -1.7976931348623157E308 and max value: 1.7976931348623157E308"
},
{
"code": null,
"e": 131419,
"s": 131300,
"text": "DOUBLE − stores 64 bit floating point number. Min value: -1.7976931348623157E308 and max value: 1.7976931348623157E308"
},
{
"code": null,
"e": 131482,
"s": 131419,
"text": "Boolean data types stores Boolean value, which are TRUE, FALSE"
},
{
"code": null,
"e": 131520,
"s": 131482,
"text": "Varchar − maximum of 8000 characters."
},
{
"code": null,
"e": 131558,
"s": 131520,
"text": "Varchar − maximum of 8000 characters."
},
{
"code": null,
"e": 131603,
"s": 131558,
"text": "Nvarchar − maximum length of 4000 characters"
},
{
"code": null,
"e": 131648,
"s": 131603,
"text": "Nvarchar − maximum length of 4000 characters"
},
{
"code": null,
"e": 131733,
"s": 131648,
"text": "ALPHANUM − stores alphanumeric characters. Value for an integer is between 1 to 127."
},
{
"code": null,
"e": 131818,
"s": 131733,
"text": "ALPHANUM − stores alphanumeric characters. Value for an integer is between 1 to 127."
},
{
"code": null,
"e": 131934,
"s": 131818,
"text": "SHORTTEXT − stores variable length character string which supports text search features and string search features."
},
{
"code": null,
"e": 132050,
"s": 131934,
"text": "SHORTTEXT − stores variable length character string which supports text search features and string search features."
},
{
"code": null,
"e": 132103,
"s": 132050,
"text": "Binary types are used to store bytes of binary data."
},
{
"code": null,
"e": 132186,
"s": 132103,
"text": "VARBINARY − stores binary data in bytes. Max integer length is between 1 and 5000."
},
{
"code": null,
"e": 132275,
"s": 132186,
"text": "LARGEOBJECTS are used to store a large amount of data such as text documents and images."
},
{
"code": null,
"e": 132322,
"s": 132275,
"text": "NCLOB − stores large UNICODE character object."
},
{
"code": null,
"e": 132369,
"s": 132322,
"text": "NCLOB − stores large UNICODE character object."
},
{
"code": null,
"e": 132412,
"s": 132369,
"text": "BLOB − stores large amount of Binary data."
},
{
"code": null,
"e": 132455,
"s": 132412,
"text": "BLOB − stores large amount of Binary data."
},
{
"code": null,
"e": 132507,
"s": 132455,
"text": "CLOB − stores large amount of ASCII character data."
},
{
"code": null,
"e": 132559,
"s": 132507,
"text": "CLOB − stores large amount of ASCII character data."
},
{
"code": null,
"e": 132682,
"s": 132559,
"text": "TEXT − it enables text search features. This data type can be defined for only column tables and not for row store tables."
},
{
"code": null,
"e": 132805,
"s": 132682,
"text": "TEXT − it enables text search features. This data type can be defined for only column tables and not for row store tables."
},
{
"code": null,
"e": 132887,
"s": 132805,
"text": "BINTEXT − supports text search features but it is possible to insert binary data."
},
{
"code": null,
"e": 132969,
"s": 132887,
"text": "BINTEXT − supports text search features but it is possible to insert binary data."
},
{
"code": null,
"e": 133052,
"s": 132969,
"text": "Multivalued data types are used to store collection of values with same data type."
},
{
"code": null,
"e": 133146,
"s": 133052,
"text": "Arrays store collections of value with the same data type. They can also contain null values."
},
{
"code": null,
"e": 133351,
"s": 133146,
"text": "An operator is a special character used primarily in SQL statement's with WHERE clause to perform operation, such as comparisons and arithmetic operations. They are used to pass conditions in a SQL query."
},
{
"code": null,
"e": 133418,
"s": 133351,
"text": "Operator types given below can be used in SQL statements in HANA −"
},
{
"code": null,
"e": 133439,
"s": 133418,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 133471,
"s": 133439,
"text": "Comparison/Relational Operators"
},
{
"code": null,
"e": 133489,
"s": 133471,
"text": "Logical Operators"
},
{
"code": null,
"e": 133503,
"s": 133489,
"text": "Set Operators"
},
{
"code": null,
"e": 133642,
"s": 133503,
"text": "Arithmetic operators are used to perform simple calculation functions like addition, subtraction, multiplication, division and percentage."
},
{
"code": null,
"e": 133712,
"s": 133642,
"text": "Comparison operators are used to compare the values in SQL statement."
},
{
"code": null,
"e": 133837,
"s": 133712,
"text": "Logical operators are used to pass multiple conditions in SQL statement or are used to manipulate the results of conditions."
},
{
"code": null,
"e": 133962,
"s": 133837,
"text": "Set operators are used to combine results of two queries into a single result. Data type should be same for both the tables."
},
{
"code": null,
"e": 134070,
"s": 133962,
"text": "UNION − It combines the results of two or more Select statements. However it will eliminate duplicate rows."
},
{
"code": null,
"e": 134178,
"s": 134070,
"text": "UNION − It combines the results of two or more Select statements. However it will eliminate duplicate rows."
},
{
"code": null,
"e": 134262,
"s": 134178,
"text": "UNION ALL − This operator is similar to Union but it also shows the duplicate rows."
},
{
"code": null,
"e": 134346,
"s": 134262,
"text": "UNION ALL − This operator is similar to Union but it also shows the duplicate rows."
},
{
"code": null,
"e": 134588,
"s": 134346,
"text": "INTERSECT − Intersect operation is used to combine the two SELECT statements, and it returns the records, which are common from both SELECT statements. In case of Intersect, the number of columns and datatype must be same in both the tables."
},
{
"code": null,
"e": 134830,
"s": 134588,
"text": "INTERSECT − Intersect operation is used to combine the two SELECT statements, and it returns the records, which are common from both SELECT statements. In case of Intersect, the number of columns and datatype must be same in both the tables."
},
{
"code": null,
"e": 135031,
"s": 134830,
"text": "MINUS − Minus operation combines result of two SELECT statements and return only those results, which belong to first set of result and eliminate the rows in second statement from the output of first."
},
{
"code": null,
"e": 135232,
"s": 135031,
"text": "MINUS − Minus operation combines result of two SELECT statements and return only those results, which belong to first set of result and eliminate the rows in second statement from the output of first."
},
{
"code": null,
"e": 135296,
"s": 135232,
"text": "There are various SQL functions provided by SAP HANA database −"
},
{
"code": null,
"e": 135314,
"s": 135296,
"text": "Numeric Functions"
},
{
"code": null,
"e": 135331,
"s": 135314,
"text": "String Functions"
},
{
"code": null,
"e": 135350,
"s": 135331,
"text": "Fulltext Functions"
},
{
"code": null,
"e": 135369,
"s": 135350,
"text": "Datetime Functions"
},
{
"code": null,
"e": 135389,
"s": 135369,
"text": "Aggregate Functions"
},
{
"code": null,
"e": 135420,
"s": 135389,
"text": "Data Type Conversion Functions"
},
{
"code": null,
"e": 135437,
"s": 135420,
"text": "Window Functions"
},
{
"code": null,
"e": 135459,
"s": 135437,
"text": "Series Data Functions"
},
{
"code": null,
"e": 135483,
"s": 135459,
"text": "Miscellaneous Functions"
},
{
"code": null,
"e": 135634,
"s": 135483,
"text": "These are inbuilt numeric functions in SQL and use in scripting. It takes numeric values or strings with numeric characters and return numeric values."
},
{
"code": null,
"e": 135693,
"s": 135634,
"text": "ABS − It returns the absolute value of a numeric argument."
},
{
"code": null,
"e": 135752,
"s": 135693,
"text": "ABS − It returns the absolute value of a numeric argument."
},
{
"code": null,
"e": 135801,
"s": 135752,
"text": "Example − SELECT ABS (-1) \"abs\" FROM TEST;\nabs\n1"
},
{
"code": null,
"e": 135886,
"s": 135801,
"text": "ACOS, ASIN, ATAN, ATAN2 (These functions return trigonometric value of the argument)"
},
{
"code": null,
"e": 135948,
"s": 135886,
"text": "BINTOHEX − It converts a Binary value to a hexadecimal value."
},
{
"code": null,
"e": 136010,
"s": 135948,
"text": "BINTOHEX − It converts a Binary value to a hexadecimal value."
},
{
"code": null,
"e": 136076,
"s": 136010,
"text": "BITAND − It performs an AND operation on bits of passed argument."
},
{
"code": null,
"e": 136142,
"s": 136076,
"text": "BITAND − It performs an AND operation on bits of passed argument."
},
{
"code": null,
"e": 136213,
"s": 136142,
"text": "BITCOUNT − It performs the count of number of set bits in an argument."
},
{
"code": null,
"e": 136284,
"s": 136213,
"text": "BITCOUNT − It performs the count of number of set bits in an argument."
},
{
"code": null,
"e": 136354,
"s": 136284,
"text": "BITNOT − It performs a bitwise NOT operation on the bits of argument."
},
{
"code": null,
"e": 136424,
"s": 136354,
"text": "BITNOT − It performs a bitwise NOT operation on the bits of argument."
},
{
"code": null,
"e": 136487,
"s": 136424,
"text": "BITOR − It perform an OR operation on bits of passed argument."
},
{
"code": null,
"e": 136550,
"s": 136487,
"text": "BITOR − It perform an OR operation on bits of passed argument."
},
{
"code": null,
"e": 136634,
"s": 136550,
"text": "BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 136718,
"s": 136634,
"text": "BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 136804,
"s": 136718,
"text": "BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 136890,
"s": 136804,
"text": "BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 136953,
"s": 136890,
"text": "BITXOR − It performs XOR operation on bits of passed argument."
},
{
"code": null,
"e": 137016,
"s": 136953,
"text": "BITXOR − It performs XOR operation on bits of passed argument."
},
{
"code": null,
"e": 137098,
"s": 137016,
"text": "CEIL − It returns the first integer that is greater or equal to the passed value."
},
{
"code": null,
"e": 137180,
"s": 137098,
"text": "CEIL − It returns the first integer that is greater or equal to the passed value."
},
{
"code": null,
"e": 137257,
"s": 137180,
"text": "COS, COSH, COT ((These functions return trigonometric value of the argument)"
},
{
"code": null,
"e": 137334,
"s": 137257,
"text": "COS, COSH, COT ((These functions return trigonometric value of the argument)"
},
{
"code": null,
"e": 137435,
"s": 137334,
"text": "EXP − It returns the result of the base of natural logarithms e raised to the power of passed value."
},
{
"code": null,
"e": 137536,
"s": 137435,
"text": "EXP − It returns the result of the base of natural logarithms e raised to the power of passed value."
},
{
"code": null,
"e": 137614,
"s": 137536,
"text": "FLOOR − It returns the largest integer not greater than the numeric argument."
},
{
"code": null,
"e": 137692,
"s": 137614,
"text": "FLOOR − It returns the largest integer not greater than the numeric argument."
},
{
"code": null,
"e": 137754,
"s": 137692,
"text": "HEXTOBIN − It converts a hexadecimal value to a binary value."
},
{
"code": null,
"e": 137816,
"s": 137754,
"text": "HEXTOBIN − It converts a hexadecimal value to a binary value."
},
{
"code": null,
"e": 137871,
"s": 137816,
"text": "LN − It returns the natural logarithm of the argument."
},
{
"code": null,
"e": 137926,
"s": 137871,
"text": "LN − It returns the natural logarithm of the argument."
},
{
"code": null,
"e": 138035,
"s": 137926,
"text": "LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive."
},
{
"code": null,
"e": 138144,
"s": 138035,
"text": "LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive."
},
{
"code": null,
"e": 138261,
"s": 138144,
"text": "Various other numeric functions can also be used − MOD, POWER, RAND, ROUND, SIGN, SIN, SINH, SQRT, TAN, TANH, UMINUS"
},
{
"code": null,
"e": 138365,
"s": 138261,
"text": "Various SQL string functions can be used in HANA with SQL scripting. Most common string functions are −"
},
{
"code": null,
"e": 138422,
"s": 138365,
"text": "ASCII − It returns integer ASCII value of passed string."
},
{
"code": null,
"e": 138479,
"s": 138422,
"text": "ASCII − It returns integer ASCII value of passed string."
},
{
"code": null,
"e": 138547,
"s": 138479,
"text": "CHAR − It returns the character associated with passed ASCII value."
},
{
"code": null,
"e": 138615,
"s": 138547,
"text": "CHAR − It returns the character associated with passed ASCII value."
},
{
"code": null,
"e": 138694,
"s": 138615,
"text": "CONCAT − It is Concatenation operator and returns the combined passed strings."
},
{
"code": null,
"e": 138773,
"s": 138694,
"text": "CONCAT − It is Concatenation operator and returns the combined passed strings."
},
{
"code": null,
"e": 138834,
"s": 138773,
"text": "LCASE − It converts all character of a string to Lower case."
},
{
"code": null,
"e": 138895,
"s": 138834,
"text": "LCASE − It converts all character of a string to Lower case."
},
{
"code": null,
"e": 138977,
"s": 138895,
"text": "LEFT − It returns the first characters of a passed string as per mentioned value."
},
{
"code": null,
"e": 139059,
"s": 138977,
"text": "LEFT − It returns the first characters of a passed string as per mentioned value."
},
{
"code": null,
"e": 139122,
"s": 139059,
"text": "LENGTH − It returns the number of characters in passed string."
},
{
"code": null,
"e": 139185,
"s": 139122,
"text": "LENGTH − It returns the number of characters in passed string."
},
{
"code": null,
"e": 139253,
"s": 139185,
"text": "LOCATE − It returns the position of substring within passed string."
},
{
"code": null,
"e": 139321,
"s": 139253,
"text": "LOCATE − It returns the position of substring within passed string."
},
{
"code": null,
"e": 139380,
"s": 139321,
"text": "LOWER − It converts all characters in string to lowercase."
},
{
"code": null,
"e": 139439,
"s": 139380,
"text": "LOWER − It converts all characters in string to lowercase."
},
{
"code": null,
"e": 139507,
"s": 139439,
"text": "NCHAR − It returns the Unicode character with passed integer value."
},
{
"code": null,
"e": 139575,
"s": 139507,
"text": "NCHAR − It returns the Unicode character with passed integer value."
},
{
"code": null,
"e": 139699,
"s": 139575,
"text": "REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string."
},
{
"code": null,
"e": 139823,
"s": 139699,
"text": "REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string."
},
{
"code": null,
"e": 139901,
"s": 139823,
"text": "RIGHT − It returns the rightmost passed value characters of mentioned string."
},
{
"code": null,
"e": 139979,
"s": 139901,
"text": "RIGHT − It returns the rightmost passed value characters of mentioned string."
},
{
"code": null,
"e": 140045,
"s": 139979,
"text": "UPPER − It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 140111,
"s": 140045,
"text": "UPPER − It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 140212,
"s": 140111,
"text": "UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 140313,
"s": 140212,
"text": "UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 140459,
"s": 140313,
"text": "Other string functions that can be used are − LPAD, LTRIM, RTRIM, STRTOBIN, SUBSTR_AFTER, SUBSTR_BEFORE, SUBSTRING, TRIM, UNICODE, RPAD, BINTOSTR"
},
{
"code": null,
"e": 140576,
"s": 140459,
"text": "There are various Date Time functions that can be used in HANA in SQL scripts. Most common Date Time functions are −"
},
{
"code": null,
"e": 140633,
"s": 140576,
"text": "CURRENT_DATE − It returns the current local system date."
},
{
"code": null,
"e": 140690,
"s": 140633,
"text": "CURRENT_DATE − It returns the current local system date."
},
{
"code": null,
"e": 140747,
"s": 140690,
"text": "CURRENT_TIME − It returns the current local system time."
},
{
"code": null,
"e": 140804,
"s": 140747,
"text": "CURRENT_TIME − It returns the current local system time."
},
{
"code": null,
"e": 140904,
"s": 140804,
"text": "CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF)."
},
{
"code": null,
"e": 141004,
"s": 140904,
"text": "CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF)."
},
{
"code": null,
"e": 141073,
"s": 141004,
"text": "CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date."
},
{
"code": null,
"e": 141142,
"s": 141073,
"text": "CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date."
},
{
"code": null,
"e": 141211,
"s": 141142,
"text": "CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time."
},
{
"code": null,
"e": 141280,
"s": 141211,
"text": "CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time."
},
{
"code": null,
"e": 141301,
"s": 141280,
"text": "CURRENT_UTCTIMESTAMP"
},
{
"code": null,
"e": 141322,
"s": 141301,
"text": "CURRENT_UTCTIMESTAMP"
},
{
"code": null,
"e": 141399,
"s": 141322,
"text": "DAYOFMONTH − It returns the integer value of day in passed date in argument."
},
{
"code": null,
"e": 141476,
"s": 141399,
"text": "DAYOFMONTH − It returns the integer value of day in passed date in argument."
},
{
"code": null,
"e": 141544,
"s": 141476,
"text": "HOUR − It returns integer value of hour in passed time in argument."
},
{
"code": null,
"e": 141612,
"s": 141544,
"text": "HOUR − It returns integer value of hour in passed time in argument."
},
{
"code": null,
"e": 141661,
"s": 141612,
"text": "YEAR − It returns the year value of passed date."
},
{
"code": null,
"e": 141710,
"s": 141661,
"text": "YEAR − It returns the year value of passed date."
},
{
"code": null,
"e": 142001,
"s": 141710,
"text": "Other Date Time functions are − DAYOFYEAR, DAYNAME, DAYS_BETWEEN, EXTRACT, NANO100_BETWEEN, NEXT_DAY, NOW, QUARTER, SECOND, SECONDS_BETWEEN, UTCTOLOCAL, WEEK, WEEKDAY, WORKDAYS_BETWEEN, ISOWEEK, LAST_DAY, LOCALTOUTC, MINUTE, MONTH, MONTHNAME, ADD_DAYS, ADD_MONTHS, ADD_SECONDS, ADD_WORKDAYS"
},
{
"code": null,
"e": 142116,
"s": 142001,
"text": "These functions are used to convert one data type to other or to perform a check if conversion is possible or not."
},
{
"code": null,
"e": 142189,
"s": 142116,
"text": "Most common data type conversion functions used in HANA in SQL scripts −"
},
{
"code": null,
"e": 142269,
"s": 142189,
"text": "CAST − It returns the value of an expression converted to a supplied data type."
},
{
"code": null,
"e": 142349,
"s": 142269,
"text": "CAST − It returns the value of an expression converted to a supplied data type."
},
{
"code": null,
"e": 142415,
"s": 142349,
"text": "TO_ALPHANUM − It converts a passed value to an ALPHANUM data type"
},
{
"code": null,
"e": 142481,
"s": 142415,
"text": "TO_ALPHANUM − It converts a passed value to an ALPHANUM data type"
},
{
"code": null,
"e": 142532,
"s": 142481,
"text": "TO_REAL − It converts a value to a REAL data type."
},
{
"code": null,
"e": 142583,
"s": 142532,
"text": "TO_REAL − It converts a value to a REAL data type."
},
{
"code": null,
"e": 142649,
"s": 142583,
"text": "TO_TIME − It converts a passed time string to the TIME data type."
},
{
"code": null,
"e": 142715,
"s": 142649,
"text": "TO_TIME − It converts a passed time string to the TIME data type."
},
{
"code": null,
"e": 142766,
"s": 142715,
"text": "TO_CLOB − It converts a value to a CLOB data type."
},
{
"code": null,
"e": 142817,
"s": 142766,
"text": "TO_CLOB − It converts a value to a CLOB data type."
},
{
"code": null,
"e": 143079,
"s": 142817,
"text": "Other similar Data Type conversion functions are − TO_BIGINT, TO_BINARY, TO_BLOB, TO_DATE, TO_DATS, TO_DECIMAL, TO_DOUBLE, TO_FIXEDCHAR, TO_INT, TO_INTEGER, TO_NCLOB, TO_NVARCHAR, TO_TIMESTAMP, TO_TINYINT, TO_VARCHAR, TO_SECONDDATE, TO_SMALLDECIMAL, TO_SMALLINT"
},
{
"code": null,
"e": 143182,
"s": 143079,
"text": "There are also various Windows and other miscellaneous functions that can be used in HANA SQL scripts."
},
{
"code": null,
"e": 143255,
"s": 143182,
"text": "Current_Schema − It returns a string containing the current schema name."
},
{
"code": null,
"e": 143328,
"s": 143255,
"text": "Current_Schema − It returns a string containing the current schema name."
},
{
"code": null,
"e": 143387,
"s": 143328,
"text": "Session_User − It returns the user name of current session"
},
{
"code": null,
"e": 143446,
"s": 143387,
"text": "Session_User − It returns the user name of current session"
},
{
"code": null,
"e": 143570,
"s": 143446,
"text": "An Expression is used to evaluate a clause to return values. There are different SQL expressions that can be used in HANA −"
},
{
"code": null,
"e": 143587,
"s": 143570,
"text": "Case Expressions"
},
{
"code": null,
"e": 143608,
"s": 143587,
"text": "Function Expressions"
},
{
"code": null,
"e": 143630,
"s": 143608,
"text": "Aggregate Expressions"
},
{
"code": null,
"e": 143656,
"s": 143630,
"text": "Subqueries in Expressions"
},
{
"code": null,
"e": 143802,
"s": 143656,
"text": "This is used to pass multiple conditions in a SQL expression. It allows the use of IF-ELSE-THEN logic without using procedures in SQL statements."
},
{
"code": null,
"e": 144010,
"s": 143802,
"text": "SELECT COUNT( CASE WHEN sal < 2000 THEN 1 ELSE NULL END ) count1,\nCOUNT( CASE WHEN sal BETWEEN 2001 AND 4000 THEN 1 ELSE NULL END ) count2,\nCOUNT( CASE WHEN sal > 4000 THEN 1 ELSE NULL END ) count3 FROM emp;"
},
{
"code": null,
"e": 144104,
"s": 144010,
"text": "This statement will return count1, count2, count3 with integer value as per passed condition."
},
{
"code": null,
"e": 144182,
"s": 144104,
"text": "Function expressions involve SQL inbuilt functions to be used in Expressions."
},
{
"code": null,
"e": 144395,
"s": 144182,
"text": "Aggregate functions are used to perform complex calculations like Sum, Percentage, Min, Max, Count, Mode, Median, etc. Aggregate Expression uses Aggregate functions to calculate single value from multiple values."
},
{
"code": null,
"e": 144537,
"s": 144395,
"text": "Aggregate Functions − Sum, Count, Minimum, Maximum. These are applied on measure values (facts) and It is always associated with a dimension."
},
{
"code": null,
"e": 144574,
"s": 144537,
"text": "Common aggregate functions include −"
},
{
"code": null,
"e": 144585,
"s": 144574,
"text": "Average ()"
},
{
"code": null,
"e": 144594,
"s": 144585,
"text": "Count ()"
},
{
"code": null,
"e": 144605,
"s": 144594,
"text": "Maximum ()"
},
{
"code": null,
"e": 144615,
"s": 144605,
"text": "Median ()"
},
{
"code": null,
"e": 144626,
"s": 144615,
"text": "Minimum ()"
},
{
"code": null,
"e": 144634,
"s": 144626,
"text": "Mode ()"
},
{
"code": null,
"e": 144641,
"s": 144634,
"text": "Sum ()"
},
{
"code": null,
"e": 144763,
"s": 144641,
"text": "A subquery as an expression is a Select statement. When it is used in an expression, it returns a zero or a single value."
},
{
"code": null,
"e": 144894,
"s": 144763,
"text": "A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved."
},
{
"code": null,
"e": 145036,
"s": 144894,
"text": "Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc."
},
{
"code": null,
"e": 145088,
"s": 145036,
"text": "There are a few rules that subqueries must follow −"
},
{
"code": null,
"e": 145136,
"s": 145088,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 145184,
"s": 145136,
"text": "Subqueries must be enclosed within parentheses."
},
{
"code": null,
"e": 145338,
"s": 145184,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 145492,
"s": 145338,
"text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns."
},
{
"code": null,
"e": 145664,
"s": 145492,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 145836,
"s": 145664,
"text": "An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY in a subquery."
},
{
"code": null,
"e": 145950,
"s": 145836,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator."
},
{
"code": null,
"e": 146064,
"s": 145950,
"text": "Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator."
},
{
"code": null,
"e": 146168,
"s": 146064,
"text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB."
},
{
"code": null,
"e": 146272,
"s": 146168,
"text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB."
},
{
"code": null,
"e": 146333,
"s": 146272,
"text": "A subquery cannot be immediately enclosed in a set function."
},
{
"code": null,
"e": 146394,
"s": 146333,
"text": "A subquery cannot be immediately enclosed in a set function."
},
{
"code": null,
"e": 146510,
"s": 146394,
"text": "The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery."
},
{
"code": null,
"e": 146626,
"s": 146510,
"text": "The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator can be used within the subquery."
},
{
"code": null,
"e": 146722,
"s": 146626,
"text": "Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −"
},
{
"code": null,
"e": 146807,
"s": 146722,
"text": "SELECT * FROM CUSTOMERS\nWHERE ID IN (SELECT ID\nFROM CUSTOMERS\nWHERE SALARY > 4500) ;"
},
{
"code": null,
"e": 147123,
"s": 146807,
"text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n"
},
{
"code": null,
"e": 147463,
"s": 147123,
"text": "A procedure allows you to group the SQL statement into a single block. Stored Procedures are used to achieve certain result across applications. The set of SQL statements and the logic that is used to perform some specific task are stored in SQL Stored Procedures. These stored procedures are executed by applications to perform that task."
},
{
"code": null,
"e": 147666,
"s": 147463,
"text": "Stored Procedures can return data in the form of output parameters (integer or character) or a cursor variable. It can also result in set of Select statements, which are used by other Stored Procedures."
},
{
"code": null,
"e": 148052,
"s": 147666,
"text": "Stored Procedures are also used for performance optimization as it contains series of SQL statements and results from one set of statement determines next set of statements to be executed. Stored procedures prevent users to see the complexity and details of tables in a database. As Stored procedures contain certain business logic, so users need to execute or call the procedure name."
},
{
"code": null,
"e": 148145,
"s": 148052,
"text": "No need to keep reissuing the individual statements but can refer to the database procedure."
},
{
"code": null,
"e": 148311,
"s": 148145,
"text": "Create procedure prc_name (in inp integer, out opt \"EFASION\".\"ARTICLE_LOOKUP\")\nas\nbegin\nopt = select * from \"EFASION\".\"ARTICLE_LOOKUP\" where article_id = :inp ;\nend;"
},
{
"code": null,
"e": 148567,
"s": 148311,
"text": "A sequence is a set of integers 1, 2, 3, that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value, and sequences provide an easy way to generate them."
},
{
"code": null,
"e": 148702,
"s": 148567,
"text": "The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQL to take care."
},
{
"code": null,
"e": 148893,
"s": 148702,
"text": "Try out the following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because it is auto-incremented by MySQL."
},
{
"code": null,
"e": 149510,
"s": 148893,
"text": "mysql> CREATE TABLE INSECT\n -> (\n -> id INT UNSIGNED NOT NULL AUTO_INCREMENT,\n -> PRIMARY KEY (id),\n -> name VARCHAR(30) NOT NULL, # type of insect\n -> date DATE NOT NULL, # date collected\n -> origin VARCHAR(30) NOT NULL # where collected\n);\n\nQuery OK, 0 rows affected (0.02 sec)\n\nmysql> INSERT INTO INSECT (id,name,date,origin) VALUES\n -> (NULL,'housefly','2001-09-10','kitchen'),\n -> (NULL,'millipede','2001-09-10','driveway'),\n -> (NULL,'grasshopper','2001-09-10','front yard');\n\t\nQuery OK, 3 rows affected (0.02 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\nmysql> SELECT * FROM INSECT ORDER BY id;"
},
{
"code": null,
"e": 149865,
"s": 149510,
"text": "+----+-------------+------------+------------+\n| id | name | date | origin |\n+----+-------------+------------+------------+\n| 1 | housefly | 2001-09-10 | kitchen |\n| 2 | millipede | 2001-09-10 | driveway |\n| 3 | grasshopper | 2001-09-10 | front yard |\n+----+-------------+------------+------------+\n3 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 150100,
"s": 149865,
"text": "LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. Otherwise, PERL and PHP scripts provide exclusive functions to retrieve auto-incremented value of last record."
},
{
"code": null,
"e": 150377,
"s": 150100,
"text": "Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle −"
},
{
"code": null,
"e": 150504,
"s": 150377,
"text": "$dbh->do (\"INSERT INTO INSECT (name,date,origin)\nVALUES('moth','2001-09-14','windowsill')\");\nmy $seq = $dbh->{mysql_insertid};"
},
{
"code": null,
"e": 150617,
"s": 150504,
"text": "After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling mysql_insert_id( ) −"
},
{
"code": null,
"e": 150758,
"s": 150617,
"text": "mysql_query (\"INSERT INTO INSECT (name,date,origin)\nVALUES('moth','2001-09-14','windowsill')\", $conn_id);\n$seq = mysql_insert_id ($conn_id);"
},
{
"code": null,
"e": 151000,
"s": 150758,
"text": "There may be a case when you have deleted many records from a table and you want to re-sequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having join, with other table."
},
{
"code": null,
"e": 151251,
"s": 151000,
"text": "If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique −"
},
{
"code": null,
"e": 151397,
"s": 151251,
"text": "mysql> ALTER TABLE INSECT DROP id;\nmysql> ALTER TABLE insect\n -> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,\n -> ADD PRIMARY KEY (id);"
},
{
"code": null,
"e": 151585,
"s": 151397,
"text": "By default, MySQL will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQL will start sequence from 100."
},
{
"code": null,
"e": 151845,
"s": 151585,
"text": "mysql> CREATE TABLE INSECT\n -> (\n -> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,\n -> PRIMARY KEY (id),\n -> name VARCHAR(30) NOT NULL, # type of insect\n -> date DATE NOT NULL, # date collected\n -> origin VARCHAR(30) NOT NULL # where collected\n);"
},
{
"code": null,
"e": 151943,
"s": 151845,
"text": "Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE."
},
{
"code": null,
"e": 152130,
"s": 151943,
"text": "Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events −"
},
{
"code": null,
"e": 152199,
"s": 152130,
"text": "A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)."
},
{
"code": null,
"e": 152268,
"s": 152199,
"text": "A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)."
},
{
"code": null,
"e": 152332,
"s": 152268,
"text": "A database definition (DDL) statement (CREATE, ALTER, or DROP)."
},
{
"code": null,
"e": 152396,
"s": 152332,
"text": "A database definition (DDL) statement (CREATE, ALTER, or DROP)."
},
{
"code": null,
"e": 152469,
"s": 152396,
"text": "A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN)."
},
{
"code": null,
"e": 152542,
"s": 152469,
"text": "A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN)."
},
{
"code": null,
"e": 152644,
"s": 152542,
"text": "Triggers could be defined on the table, view, schema, or database with which the event is associated."
},
{
"code": null,
"e": 152697,
"s": 152644,
"text": "Triggers can be written for the following purposes −"
},
{
"code": null,
"e": 152749,
"s": 152697,
"text": "Generating some derived column values automatically"
},
{
"code": null,
"e": 152781,
"s": 152749,
"text": "Enforcing referential integrity"
},
{
"code": null,
"e": 152835,
"s": 152781,
"text": "Event logging and storing information on table access"
},
{
"code": null,
"e": 152844,
"s": 152835,
"text": "Auditing"
},
{
"code": null,
"e": 152878,
"s": 152844,
"text": "Synchronous replication of tables"
},
{
"code": null,
"e": 152911,
"s": 152878,
"text": "Imposing security authorizations"
},
{
"code": null,
"e": 152943,
"s": 152911,
"text": "Preventing invalid transactions"
},
{
"code": null,
"e": 153115,
"s": 152943,
"text": "SQL Synonyms is an alias for a table or a Schema object in a database. They are used to protect client applications from the changes made to name or location of an object."
},
{
"code": null,
"e": 153242,
"s": 153115,
"text": "Synonyms permit applications to function irrespective of user who owns the table and which database holds the table or object."
},
{
"code": null,
"e": 153345,
"s": 153242,
"text": "Create Synonym statement is used create a Synonym for a table, view, package, procedure, objects, etc."
},
{
"code": null,
"e": 153626,
"s": 153345,
"text": "There is a table Customer of efashion, located on a Server1. To access this from Server2, a client application would have to use name as Server1.efashion.Customer. Now we change the location of Customer table the client application would have to be modified to reflect the change."
},
{
"code": null,
"e": 153950,
"s": 153626,
"text": "To address these we can create a synonym of Customer table Cust_Table on Server2 for the table on Server1. So now client application has to use the single-part name Cust_Table to reference this table. Now, if the location of this table changes, you will have to modify the synonym to point to the new location of the table."
},
{
"code": null,
"e": 154141,
"s": 153950,
"text": "As there is no ALTER SYNONYM statement, you have to drop the synonym Cust_Table and then re-create the synonym with the same name and point the synonym to the new location of Customer table."
},
{
"code": null,
"e": 154423,
"s": 154141,
"text": "Public Synonyms are owned by PUBLIC schema in a database. Public synonyms can be referenced by all users in the database. They are created by the application owner for the tables and other objects such as procedures and packages so the users of the application can see the objects."
},
{
"code": null,
"e": 154480,
"s": 154423,
"text": "CREATE PUBLIC SYNONYM Cust_table for efashion.Customer;\n"
},
{
"code": null,
"e": 154549,
"s": 154480,
"text": "To create a PUBLIC Synonym, you have to use keyword PUBLIC as shown."
},
{
"code": null,
"e": 154676,
"s": 154549,
"text": "Private Synonyms are used in a database schema to hide the true name of a table, procedure, view or any other database object."
},
{
"code": null,
"e": 154761,
"s": 154676,
"text": "Private synonyms can be referenced only by the schema that owns the table or object."
},
{
"code": null,
"e": 154811,
"s": 154761,
"text": "CREATE SYNONYM Cust_table FOR efashion.Customer;\n"
},
{
"code": null,
"e": 154959,
"s": 154811,
"text": "Synonyms can be dropped using DROP Synonym command. If you are dropping a public Synonym, you have to use the keyword public in the drop statement."
},
{
"code": null,
"e": 155017,
"s": 154959,
"text": "DROP PUBLIC Synonym Cust_table;\nDROP Synonym Cust_table;\n"
},
{
"code": null,
"e": 155197,
"s": 155017,
"text": "SQL explain plans are used to generate detail explanation of SQL statements. They are used to evaluate execution plan that SAP HANA database follows to execute the SQL statements."
},
{
"code": null,
"e": 155358,
"s": 155197,
"text": "The results of explain plan are stored into EXPLAIN_PLAN_TABLE for evaluation. To use Explain Plan, passed SQL query must be a data manipulation language (DML)."
},
{
"code": null,
"e": 155401,
"s": 155358,
"text": "SELECT − retrieve data from the a database"
},
{
"code": null,
"e": 155444,
"s": 155401,
"text": "SELECT − retrieve data from the a database"
},
{
"code": null,
"e": 155478,
"s": 155444,
"text": "INSERT − insert data into a table"
},
{
"code": null,
"e": 155512,
"s": 155478,
"text": "INSERT − insert data into a table"
},
{
"code": null,
"e": 155558,
"s": 155512,
"text": "UPDATE − updates existing data within a table"
},
{
"code": null,
"e": 155604,
"s": 155558,
"text": "UPDATE − updates existing data within a table"
},
{
"code": null,
"e": 155670,
"s": 155604,
"text": "SQL Explain Plans cannot be used with DDL and DCL SQL statements."
},
{
"code": null,
"e": 155830,
"s": 155670,
"text": "EXPLAIN PLAN_TABLE in database consists of multiple columns. Few common column names − OPERATOR_NAME, OPERATOR_ID, PARENT_OPERATOR_ID, LEVEL and POSITION, etc."
},
{
"code": null,
"e": 155906,
"s": 155830,
"text": "COLUMN SEARCH value tells the starting position of column engine operators."
},
{
"code": null,
"e": 155976,
"s": 155906,
"text": "ROW SEARCH value tells the starting position of row engine operators."
},
{
"code": null,
"e": 156052,
"s": 155976,
"text": "EXPLAIN PLAN SET STATEMENT_NAME = ‘statement_name’ FOR <SQL DML statement>\n"
},
{
"code": null,
"e": 156151,
"s": 156052,
"text": "SELECT Operator_Name, Operator_ID\nFROM explain_plan_table\nWHERE statement_name = 'statement_name';"
},
{
"code": null,
"e": 156219,
"s": 156151,
"text": "DELETE FROM explain_plan_table WHERE statement_name = 'TPC-H Q10';\n"
},
{
"code": null,
"e": 156434,
"s": 156219,
"text": "SQL Data Profiling task is used to understand and analyze data from multiple data sources. It is used to remove incorrect, incomplete data and prevent data quality problems before they are loaded in Data warehouse."
},
{
"code": null,
"e": 156486,
"s": 156434,
"text": "Here are the benefits of SQL Data Profiling tasks −"
},
{
"code": null,
"e": 156538,
"s": 156486,
"text": "It helps is analyzing source data more effectively."
},
{
"code": null,
"e": 156590,
"s": 156538,
"text": "It helps is analyzing source data more effectively."
},
{
"code": null,
"e": 156640,
"s": 156590,
"text": "It helps in understanding the source data better."
},
{
"code": null,
"e": 156690,
"s": 156640,
"text": "It helps in understanding the source data better."
},
{
"code": null,
"e": 156793,
"s": 156690,
"text": "It remove incorrect, incomplete data and improve data quality before it is loaded into Data warehouse."
},
{
"code": null,
"e": 156896,
"s": 156793,
"text": "It remove incorrect, incomplete data and improve data quality before it is loaded into Data warehouse."
},
{
"code": null,
"e": 156957,
"s": 156896,
"text": "It is used with Extraction, Transformation and Loading task."
},
{
"code": null,
"e": 157018,
"s": 156957,
"text": "It is used with Extraction, Transformation and Loading task."
},
{
"code": null,
"e": 157153,
"s": 157018,
"text": "The Data Profiling task checks profiles that helps to understand a data source and identify problems in the data that has to be fixed."
},
{
"code": null,
"e": 157327,
"s": 157153,
"text": "You can use the Data Profiling task inside an Integration Services package to profile data that is stored in SQL Server and to identify potential problems with data quality."
},
{
"code": null,
"e": 157465,
"s": 157327,
"text": "Note − Data Profiling Task works only with SQL Server data sources and does not support any other file based or third party data sources."
},
{
"code": null,
"e": 157612,
"s": 157465,
"text": "To run a package contains Data Profiling task, user account must have read/write permissions with CREATE TABLE permissions on the tempdb database."
},
{
"code": null,
"e": 157891,
"s": 157612,
"text": "Data Profile Viewer is used to review the profiler output. The Data Profile Viewer also supports drilldown capability to help you understand data quality issues that are identified in the profile output. This drill down capability sends live queries to the original data source."
},
{
"code": null,
"e": 158058,
"s": 157891,
"text": "It involves execution of a package that contains Data Profiling task to compute the profiles. The task saves the output in XML format to a file or a package variable."
},
{
"code": null,
"e": 158289,
"s": 158058,
"text": "To view the data profiles, send the output to a file and then use the Data Profile Viewer. This viewer is a stand-alone utility that displays the profile output in both summary and detail format with optional drilldown capability."
},
{
"code": null,
"e": 158358,
"s": 158289,
"text": "The Data Profiling task has these convenient configuration options −"
},
{
"code": null,
"e": 158644,
"s": 158358,
"text": "While configuring a profile request, the task accepts ‘*’ wildcard in place of a column name. This simplifies the configuration and makes it easier to discover the characteristics of unfamiliar data. When the task runs, the task profiles every column that has an appropriate data type."
},
{
"code": null,
"e": 158793,
"s": 158644,
"text": "You can select Quick Profile to configure the task quickly. A Quick Profile profiles a table or view by using all the default profiles and settings."
},
{
"code": null,
"e": 158996,
"s": 158793,
"text": "The Data Profiling Task can compute eight different data profiles. Five of these profiles can check individual columns and the remaining three analyze- multiple columns or relationships between columns."
},
{
"code": null,
"e": 159114,
"s": 158996,
"text": "The Data Profiling task outputs the selected profiles into XML format that is structured like DataProfile.xsd schema."
},
{
"code": null,
"e": 159299,
"s": 159114,
"text": "You can save a local copy of the schema and view the local copy of the schema in Microsoft Visual Studio or another schema editor, in an XML editor or in a text editor such as Notepad."
},
{
"code": null,
"e": 159557,
"s": 159299,
"text": "Set of SQL statements for HANA database which allows developer to pass complex logic into database is called SQL Script. SQL Script is known as collections of SQL extensions. These extension are Data Extensions, Function Extensions, and Procedure Extension."
},
{
"code": null,
"e": 159681,
"s": 159557,
"text": "SQL Script supports stored Functions and Procedures and that allows pushing complex parts of Application logic to database."
},
{
"code": null,
"e": 160031,
"s": 159681,
"text": "Main benefit of using SQL Script is to allow the execution of complex calculations inside SAP HANA database. Using SQL Scripts in place of single query enables Functions to return multiple values. Complex SQL functions can be further decomposed into smaller functions. SQL Script provides control logic that is not available in single SQL statement."
},
{
"code": null,
"e": 160131,
"s": 160031,
"text": "SQL Scripts are used to achieve performance optimization in HANA by executing scripts at DB layer −"
},
{
"code": null,
"e": 160257,
"s": 160131,
"text": "By Executing SQL scripts at database layer, it eliminates need to transfer large amount of data from database to application."
},
{
"code": null,
"e": 160383,
"s": 160257,
"text": "By Executing SQL scripts at database layer, it eliminates need to transfer large amount of data from database to application."
},
{
"code": null,
"e": 160521,
"s": 160383,
"text": "Calculations are executed at database layer to get benefits of HANA database like column operations, parallel processing of queries, etc."
},
{
"code": null,
"e": 160659,
"s": 160521,
"text": "Calculations are executed at database layer to get benefits of HANA database like column operations, parallel processing of queries, etc."
},
{
"code": null,
"e": 160747,
"s": 160659,
"text": "While using SQL scripts in Information Modeler, below given are applied to Procedures −"
},
{
"code": null,
"e": 160796,
"s": 160747,
"text": "Input parameters can be of scalar or table type."
},
{
"code": null,
"e": 160838,
"s": 160796,
"text": "Output parameters must be of table types."
},
{
"code": null,
"e": 160906,
"s": 160838,
"text": "Table types required for the signature are generated automatically."
},
{
"code": null,
"e": 161114,
"s": 160906,
"text": "SQL script are used to create script based Calculation views. Type SQL statements against existing raw tables or column store. Define output structure, activation of view creates table type as per structure."
},
{
"code": null,
"e": 161326,
"s": 161114,
"text": "Launch SAP HANA studio. Expand the content node → Select a package where you want to create the new Calculation view. Right Click → New Calculation View End of the navigation path → Provide name and description."
},
{
"code": null,
"e": 161562,
"s": 161326,
"text": "Select calculation view type → from Type dropdown list, select SQL Script → Set Parameter Case Sensitive to True or False based on how you require the naming convention for the output parameters of the calculation view → Choose Finish."
},
{
"code": null,
"e": 161711,
"s": 161562,
"text": "Select default schema − Select the Semantics node → Choose the View Properties tab → In the Default Schema dropdown list, select the default schema."
},
{
"code": null,
"e": 161897,
"s": 161711,
"text": "Choose SQL Script node in the Semantics node → Define the output structure. In the output pane, choose Create Target. Add the required output parameters and specify its length and type."
},
{
"code": null,
"e": 162062,
"s": 161897,
"text": "To add multiple columns that are part of existing information views or catalog tables or table functions to the output structure of script-based calculation views −"
},
{
"code": null,
"e": 162331,
"s": 162062,
"text": "In the Output pane, choose Start of the navigation path New Next navigation step Add Columns from End of the navigation path → Name of the object that contains the columns you want to add to the output → Select one or more objects from the dropdown list → Choose Next."
},
{
"code": null,
"e": 162584,
"s": 162331,
"text": "In the Source pane, choose the columns that you want to add to the output → To add selective columns to the output, then select those columns and choose Add. To add all columns of an object to the output, then select the object and choose Add → Finish."
},
{
"code": null,
"e": 162849,
"s": 162584,
"text": "Activate the script-based calculation view − In the SAP HANA Modeler perspective − Save and Activate - to activate the current view and redeploy the affected objects if an active version of the affected object exists. Otherwise, only the current view is activated."
},
{
"code": null,
"e": 162948,
"s": 162849,
"text": "Save and activate all − to activate the current view along with the required and affected objects."
},
{
"code": null,
"e": 163164,
"s": 162948,
"text": "In the SAP HANA Development perspective − In Project Explorer view, select the required object. In the context menu, select Start of the navigation path Team Next navigation step Activate End of the navigation path."
},
{
"code": null,
"e": 163302,
"s": 163164,
"text": "SQL Scripting in HANA Information Modeler is used to create complex Calculation Views, which are not possible to create using GUI option."
},
{
"code": null,
"e": 163335,
"s": 163302,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 163349,
"s": 163335,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 163382,
"s": 163349,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 163394,
"s": 163382,
"text": " Neha Gupta"
},
{
"code": null,
"e": 163429,
"s": 163394,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 163444,
"s": 163429,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 163477,
"s": 163444,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 163492,
"s": 163477,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 163527,
"s": 163492,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 163539,
"s": 163527,
"text": " Neha Malik"
},
{
"code": null,
"e": 163574,
"s": 163539,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 163586,
"s": 163574,
"text": " Neha Malik"
},
{
"code": null,
"e": 163593,
"s": 163586,
"text": " Print"
},
{
"code": null,
"e": 163604,
"s": 163593,
"text": " Add Notes"
}
] |
Probabilistic Linear Regression with Weight Uncertainty | by Ruben Winastwan | Towards Data Science | Linear regression is probably the first statistical approach that you’ll ever encounter when you’re learning data science and machine learning. So, I’d take my chance to guess that this is not the first time you’re dealing with linear regression. Thus in this article, I want to talk about probabilistic linear regression instead of the typical/deterministic linear regression.
But before that, let’s briefly discuss the concept of deterministic linear regression to get us up to the speed to the main talking point of this article.
Linear regression is a fundamental statistical approach to model the linear relationship between one or multiple input variables (or independent variables) with one or multiple output variables (or dependent variables).
In the above equation, a is called the intercept, and b is called the slope. x is our independent variable, and y is our dependent variable, which the value we try to predict.
The value for a and b need to be optimized with a gradient descent algorithm. Then, we obtain a regression line that shows the best fit between independent and dependent variables. With the regression line, we can predict the value of ywith any given input of x . Those are the steps on how the typical or deterministic linear regression algorithm is normally built.
However, this deterministic linear regression algorithm doesn’t really tell the complete story of both the data and the model. Why is that?
In reality, there are two types of uncertainty that arise when we do linear regression analysis:
Aleatoric uncertainty, which is the uncertainty that arises from the data.
Epistemic uncertainty, which is the uncertainty that arises from the regression model.
I’m going to elaborate more on these uncertainties as we go through the article. To take these uncertainties into account, probabilistic linear regression should be used instead of deterministic linear regression.
In this article, we will talk about probabilistic linear regression and how it differs from the deterministic linear regression. We will first see how deterministic linear regression is built in TensorFlow, and then we will move on to build a probabilistic linear regression model with TensorFlow probability.
First, let’s start with loading the dataset that we will use in this article.
The dataset that will be used in this article is car’s MPG dataset. As usual, we can load the data with Pandas.
Below is the statistical summary of the data.
Next, we can look at the correlation between variables in the dataset with the code below.
Now if we look at the correlation, the car’s Miles per Gallon (MPG) and the car’s weight has a strong negative correlation.
In this article, I’m going to do a simple linear regression analysis for visualization purpose. The independent variable will be the car’s weight and the dependent variable will be the car’s MPG.
Now, let’s split the data into training data and test data with Scikit-learn. After splitting the data, we can now scale both of the dependent and independent variables. This is to make sure that both variables are going to be on the same scale and this will also improve the convergence rate of our linear regression model.
Now if we visualize the training data, we get the following visualization:
Awesome! Next, let’s move on to build our deterministic linear regression model with TensorFlow.
It is very easy to build a simple linear regression model with TensorFlow. All we need to do to build the model is one single dense layer without any activation function. For the cost function, the mean squared error is normally used. In this example, I will use RMSprop as the optimizer and the model will be trained in 100 epochs. We can build and train the model in just a few lines of code as below.
After we trained the model, let’s take a look at the loss history of the model to check the loss convergence.
It seems like the loss has converged. Now if we use the trained model to predict the test set, we can see the following regression line.
And that’s it. We’re done!
As I mentioned earlier, it is very easy to build a simple linear regression model with TensorFlow. With the regression line, we can now approximate the car’s MPG at any given input of the car’s weight. As an example, let’s say that the car’s weight after feature scaling is 0.64. We can get the corresponding value of the car’s MPG by passing this value to the trained model as follows.
Now as you can see, the model predicts that the car’s MPG would be 0.21. Simply put, for any given car’s weight, we get a single deterministic value of the car’s MPG
However, that output value doesn’t really tell the whole story. There are two things that we should pay attention here. First, we only have a limited amount of data points. Second, as we can see from the linear regression plot, most of the data points don’t really lie on the regression line.
Although we get the output value of 0.21, we know that the actual car’s MPG is not precisely 0.21. It could be slightly below that, could be slightly above that. In other words, there is an uncertainty that needs to be taken into account. And this uncertainty is called aleatoric uncertainty.
Deterministic linear regression fails to capture this aleatoric uncertainty of the data. To capture this aleatoric uncertainty, the probabilistic linear regression can be applied instead.
Thanks to TensorFlow Probability, it is also very easy to build a probabilistic linear regression model. However, you need to install tensorflow_probability library first. You can install it using pip command as follows:
pip install tensorflow_probability
The prerequisite to install this library is that you need to have TensorFlow version 2.3.0. So make sure you upgrade your TensorFlow version before installing TensorFlow Probability.
In this section, we will build a probabilistic linear regression model that takes aleatoric uncertainty into account.
The model is pretty much similar to the deterministic linear regression. However, instead of just using one single dense layer like before, we need to add one more layer as the final layer. This final layer converts the final output value from deterministic into a probability distribution.
In this example, we will create a final layer that converts the output value into probability value that is normally distributed. Below is the implementation of that.
Note that we applied one additional layer in the end with TensorFlow Probability layer. This layer will turn the two outputs of the previous dense layer (one for the mean and one for the standard deviation) into probability value which is normally distributed with a trainable mean (loc) and standard deviation (scale).
We can use RMSprop as the optimizer, but you can use other optimizers if you wish. For the loss function, we need to use the negative log-likelihood.
But why do we use the negative log-likelihood as the loss function?
In order to fit a distribution to some data, we need to use the likelihood function. With likelihood function, we try to estimate the unknown parameters θ (for example, the mean and the standard deviation of normally distributed data) given the pattern that we’ve seen in the data.
The job for the optimizer in our probabilistic regression model is to find the maximum likelihood estimate for the unknown parameters. In other words, the model is trained to find the most likely parameter value given the pattern from our data.
Maximizing the likelihood estimate is the same as minimizing the negative log-likelihood. In the optimization domain, often the objective is to minimizing the cost instead of maximizing it. That’s why we use the negative log-likelihood as our cost function.
Below is the implementation of the negative log-likelihood as our custom loss function.
Now that we have built the model and define the optimizer as well as the loss function, let’s compile and train the model.
Now we can draw samples from the trained model. We can visualize the comparison between the test set and the samples generated from the model with the following code.
As you can see from the visualization above, now for any given input value, the model won’t return a deterministic value. Instead, it will return a distribution and it will draw a sample based on that distribution.
If you compare the data points of the test set (blue points) to the data points predicted by the trained model (green points), you’d probably believe that the green points come from the same distribution as the blue points.
Next, we can also visualize the mean and the standard deviation of the distribution generated by the trained model, given the data in the training set. We can do this by applying the following code.
We can see that the probabilistic linear regression model gives us more than the regression line. It also gives the approximation of the standard deviation of the data. It can be seen that roughly 95% of the data points of the test set lie within the two standard deviations.
So far, we’ve built a probabilistic regression model that takes into account the uncertainty that comes from the data or as we call it, aleatoric uncertainty.
However, in reality, we also need to deal with the uncertainty that comes from the regression model itself. Due to the imperfection of the data, there is also uncertainty regarding the weight or slope of the regression parameter. This uncertainty is called epistemic uncertainty.
The probabilistic model that we’ve built so far only considers one deterministic weight. As you’ve seen from the visualization, the model generates only one regression line and often this is not entirely accurate.
In this section, we will improve our probabilistic regression model that takes both aleatoric and epistemic uncertainties into account.We can use the Bayesian perspective to introduce the uncertainty of the regression weights.
First, we need to define our prior belief about what the weight distribution looks like before we see the data. Often, we don’t know what to expect about this, right? To make it simple, let’s assume that the distribution of the weight is normally distributed with a mean equal to 0 and a standard deviation equal to 1.
Since we hard-coded the mean and the standard deviation, this prior belief is not trainable.
Next, we need to define the posterior distribution of the regression weights. The posterior distribution shows how our belief has changed after seeing the pattern in the data. Thus, the parameters in this posterior distribution are trainable. Below is the code implementation to define our posterior distribution.
Now the question is, what is this VariableLayers defined in the posterior function above? The idea behind this variable layers is that we try to approximate the true posterior distribution. Normally, it’s not possible to derive the true posterior distribution, hence we need to approximate it.
After defining the prior and the posterior function, now we can build our probabilistic linear regression model with weight uncertainty. Below is the code implementation for that.
As you may notice, the only difference between this model and the previous probabilistic regression model is just the first layer. Instead of using a normal dense layer, we use the DenseVariational layer. In this layer, we pass our prior and posterior functions as the argument. The second layer is exactly the same as the previous model.
Now it’s time for us to compile and train the model.
The optimizer and the cost function are still the same as the previous model. We use RMSprop as the optimizer and the negative log-likelihood as our cost function. Let’s compile and train or model.
Now it’s time for us to visualize the weight or slope uncertainty of our regression model. Below is the code implementation to visualize the result.
In the visualization above, you can see that the linear line (mean) as well as the standard deviation that has been generated by the posterior distribution of the trained model is different in each iteration. All of these lines are a plausible solution to fit the data points in the test set. However, due to epistemic uncertainty, we don’t know which line would be the best one.
Usually, the more the data points we have, the less the uncertainty of the regression line that we will see.
And that’s it! Now you’ve seen how the probabilistic linear regression differs from the deterministic linear regression. With probabilistic linear regression, two types of uncertainty that arise from both the data (aleatoric) and the regression model (epistemic) can be taken into account.
Taking these uncertainties into account is very important if we want to build a deep learning model where the inaccurate predictions lead to very serious negative consequences, for example in the field of autonomous driving and medical diagnosis.
Normally, as we have more data points, the epistemic uncertainty of the model will be reduced. | [
{
"code": null,
"e": 550,
"s": 172,
"text": "Linear regression is probably the first statistical approach that you’ll ever encounter when you’re learning data science and machine learning. So, I’d take my chance to guess that this is not the first time you’re dealing with linear regression. Thus in this article, I want to talk about probabilistic linear regression instead of the typical/deterministic linear regression."
},
{
"code": null,
"e": 705,
"s": 550,
"text": "But before that, let’s briefly discuss the concept of deterministic linear regression to get us up to the speed to the main talking point of this article."
},
{
"code": null,
"e": 925,
"s": 705,
"text": "Linear regression is a fundamental statistical approach to model the linear relationship between one or multiple input variables (or independent variables) with one or multiple output variables (or dependent variables)."
},
{
"code": null,
"e": 1101,
"s": 925,
"text": "In the above equation, a is called the intercept, and b is called the slope. x is our independent variable, and y is our dependent variable, which the value we try to predict."
},
{
"code": null,
"e": 1468,
"s": 1101,
"text": "The value for a and b need to be optimized with a gradient descent algorithm. Then, we obtain a regression line that shows the best fit between independent and dependent variables. With the regression line, we can predict the value of ywith any given input of x . Those are the steps on how the typical or deterministic linear regression algorithm is normally built."
},
{
"code": null,
"e": 1608,
"s": 1468,
"text": "However, this deterministic linear regression algorithm doesn’t really tell the complete story of both the data and the model. Why is that?"
},
{
"code": null,
"e": 1705,
"s": 1608,
"text": "In reality, there are two types of uncertainty that arise when we do linear regression analysis:"
},
{
"code": null,
"e": 1780,
"s": 1705,
"text": "Aleatoric uncertainty, which is the uncertainty that arises from the data."
},
{
"code": null,
"e": 1867,
"s": 1780,
"text": "Epistemic uncertainty, which is the uncertainty that arises from the regression model."
},
{
"code": null,
"e": 2081,
"s": 1867,
"text": "I’m going to elaborate more on these uncertainties as we go through the article. To take these uncertainties into account, probabilistic linear regression should be used instead of deterministic linear regression."
},
{
"code": null,
"e": 2391,
"s": 2081,
"text": "In this article, we will talk about probabilistic linear regression and how it differs from the deterministic linear regression. We will first see how deterministic linear regression is built in TensorFlow, and then we will move on to build a probabilistic linear regression model with TensorFlow probability."
},
{
"code": null,
"e": 2469,
"s": 2391,
"text": "First, let’s start with loading the dataset that we will use in this article."
},
{
"code": null,
"e": 2581,
"s": 2469,
"text": "The dataset that will be used in this article is car’s MPG dataset. As usual, we can load the data with Pandas."
},
{
"code": null,
"e": 2627,
"s": 2581,
"text": "Below is the statistical summary of the data."
},
{
"code": null,
"e": 2718,
"s": 2627,
"text": "Next, we can look at the correlation between variables in the dataset with the code below."
},
{
"code": null,
"e": 2842,
"s": 2718,
"text": "Now if we look at the correlation, the car’s Miles per Gallon (MPG) and the car’s weight has a strong negative correlation."
},
{
"code": null,
"e": 3038,
"s": 2842,
"text": "In this article, I’m going to do a simple linear regression analysis for visualization purpose. The independent variable will be the car’s weight and the dependent variable will be the car’s MPG."
},
{
"code": null,
"e": 3363,
"s": 3038,
"text": "Now, let’s split the data into training data and test data with Scikit-learn. After splitting the data, we can now scale both of the dependent and independent variables. This is to make sure that both variables are going to be on the same scale and this will also improve the convergence rate of our linear regression model."
},
{
"code": null,
"e": 3438,
"s": 3363,
"text": "Now if we visualize the training data, we get the following visualization:"
},
{
"code": null,
"e": 3535,
"s": 3438,
"text": "Awesome! Next, let’s move on to build our deterministic linear regression model with TensorFlow."
},
{
"code": null,
"e": 3939,
"s": 3535,
"text": "It is very easy to build a simple linear regression model with TensorFlow. All we need to do to build the model is one single dense layer without any activation function. For the cost function, the mean squared error is normally used. In this example, I will use RMSprop as the optimizer and the model will be trained in 100 epochs. We can build and train the model in just a few lines of code as below."
},
{
"code": null,
"e": 4049,
"s": 3939,
"text": "After we trained the model, let’s take a look at the loss history of the model to check the loss convergence."
},
{
"code": null,
"e": 4186,
"s": 4049,
"text": "It seems like the loss has converged. Now if we use the trained model to predict the test set, we can see the following regression line."
},
{
"code": null,
"e": 4213,
"s": 4186,
"text": "And that’s it. We’re done!"
},
{
"code": null,
"e": 4600,
"s": 4213,
"text": "As I mentioned earlier, it is very easy to build a simple linear regression model with TensorFlow. With the regression line, we can now approximate the car’s MPG at any given input of the car’s weight. As an example, let’s say that the car’s weight after feature scaling is 0.64. We can get the corresponding value of the car’s MPG by passing this value to the trained model as follows."
},
{
"code": null,
"e": 4766,
"s": 4600,
"text": "Now as you can see, the model predicts that the car’s MPG would be 0.21. Simply put, for any given car’s weight, we get a single deterministic value of the car’s MPG"
},
{
"code": null,
"e": 5059,
"s": 4766,
"text": "However, that output value doesn’t really tell the whole story. There are two things that we should pay attention here. First, we only have a limited amount of data points. Second, as we can see from the linear regression plot, most of the data points don’t really lie on the regression line."
},
{
"code": null,
"e": 5352,
"s": 5059,
"text": "Although we get the output value of 0.21, we know that the actual car’s MPG is not precisely 0.21. It could be slightly below that, could be slightly above that. In other words, there is an uncertainty that needs to be taken into account. And this uncertainty is called aleatoric uncertainty."
},
{
"code": null,
"e": 5540,
"s": 5352,
"text": "Deterministic linear regression fails to capture this aleatoric uncertainty of the data. To capture this aleatoric uncertainty, the probabilistic linear regression can be applied instead."
},
{
"code": null,
"e": 5761,
"s": 5540,
"text": "Thanks to TensorFlow Probability, it is also very easy to build a probabilistic linear regression model. However, you need to install tensorflow_probability library first. You can install it using pip command as follows:"
},
{
"code": null,
"e": 5796,
"s": 5761,
"text": "pip install tensorflow_probability"
},
{
"code": null,
"e": 5979,
"s": 5796,
"text": "The prerequisite to install this library is that you need to have TensorFlow version 2.3.0. So make sure you upgrade your TensorFlow version before installing TensorFlow Probability."
},
{
"code": null,
"e": 6097,
"s": 5979,
"text": "In this section, we will build a probabilistic linear regression model that takes aleatoric uncertainty into account."
},
{
"code": null,
"e": 6388,
"s": 6097,
"text": "The model is pretty much similar to the deterministic linear regression. However, instead of just using one single dense layer like before, we need to add one more layer as the final layer. This final layer converts the final output value from deterministic into a probability distribution."
},
{
"code": null,
"e": 6555,
"s": 6388,
"text": "In this example, we will create a final layer that converts the output value into probability value that is normally distributed. Below is the implementation of that."
},
{
"code": null,
"e": 6875,
"s": 6555,
"text": "Note that we applied one additional layer in the end with TensorFlow Probability layer. This layer will turn the two outputs of the previous dense layer (one for the mean and one for the standard deviation) into probability value which is normally distributed with a trainable mean (loc) and standard deviation (scale)."
},
{
"code": null,
"e": 7025,
"s": 6875,
"text": "We can use RMSprop as the optimizer, but you can use other optimizers if you wish. For the loss function, we need to use the negative log-likelihood."
},
{
"code": null,
"e": 7093,
"s": 7025,
"text": "But why do we use the negative log-likelihood as the loss function?"
},
{
"code": null,
"e": 7375,
"s": 7093,
"text": "In order to fit a distribution to some data, we need to use the likelihood function. With likelihood function, we try to estimate the unknown parameters θ (for example, the mean and the standard deviation of normally distributed data) given the pattern that we’ve seen in the data."
},
{
"code": null,
"e": 7620,
"s": 7375,
"text": "The job for the optimizer in our probabilistic regression model is to find the maximum likelihood estimate for the unknown parameters. In other words, the model is trained to find the most likely parameter value given the pattern from our data."
},
{
"code": null,
"e": 7878,
"s": 7620,
"text": "Maximizing the likelihood estimate is the same as minimizing the negative log-likelihood. In the optimization domain, often the objective is to minimizing the cost instead of maximizing it. That’s why we use the negative log-likelihood as our cost function."
},
{
"code": null,
"e": 7966,
"s": 7878,
"text": "Below is the implementation of the negative log-likelihood as our custom loss function."
},
{
"code": null,
"e": 8089,
"s": 7966,
"text": "Now that we have built the model and define the optimizer as well as the loss function, let’s compile and train the model."
},
{
"code": null,
"e": 8256,
"s": 8089,
"text": "Now we can draw samples from the trained model. We can visualize the comparison between the test set and the samples generated from the model with the following code."
},
{
"code": null,
"e": 8471,
"s": 8256,
"text": "As you can see from the visualization above, now for any given input value, the model won’t return a deterministic value. Instead, it will return a distribution and it will draw a sample based on that distribution."
},
{
"code": null,
"e": 8695,
"s": 8471,
"text": "If you compare the data points of the test set (blue points) to the data points predicted by the trained model (green points), you’d probably believe that the green points come from the same distribution as the blue points."
},
{
"code": null,
"e": 8894,
"s": 8695,
"text": "Next, we can also visualize the mean and the standard deviation of the distribution generated by the trained model, given the data in the training set. We can do this by applying the following code."
},
{
"code": null,
"e": 9170,
"s": 8894,
"text": "We can see that the probabilistic linear regression model gives us more than the regression line. It also gives the approximation of the standard deviation of the data. It can be seen that roughly 95% of the data points of the test set lie within the two standard deviations."
},
{
"code": null,
"e": 9329,
"s": 9170,
"text": "So far, we’ve built a probabilistic regression model that takes into account the uncertainty that comes from the data or as we call it, aleatoric uncertainty."
},
{
"code": null,
"e": 9609,
"s": 9329,
"text": "However, in reality, we also need to deal with the uncertainty that comes from the regression model itself. Due to the imperfection of the data, there is also uncertainty regarding the weight or slope of the regression parameter. This uncertainty is called epistemic uncertainty."
},
{
"code": null,
"e": 9823,
"s": 9609,
"text": "The probabilistic model that we’ve built so far only considers one deterministic weight. As you’ve seen from the visualization, the model generates only one regression line and often this is not entirely accurate."
},
{
"code": null,
"e": 10050,
"s": 9823,
"text": "In this section, we will improve our probabilistic regression model that takes both aleatoric and epistemic uncertainties into account.We can use the Bayesian perspective to introduce the uncertainty of the regression weights."
},
{
"code": null,
"e": 10369,
"s": 10050,
"text": "First, we need to define our prior belief about what the weight distribution looks like before we see the data. Often, we don’t know what to expect about this, right? To make it simple, let’s assume that the distribution of the weight is normally distributed with a mean equal to 0 and a standard deviation equal to 1."
},
{
"code": null,
"e": 10462,
"s": 10369,
"text": "Since we hard-coded the mean and the standard deviation, this prior belief is not trainable."
},
{
"code": null,
"e": 10776,
"s": 10462,
"text": "Next, we need to define the posterior distribution of the regression weights. The posterior distribution shows how our belief has changed after seeing the pattern in the data. Thus, the parameters in this posterior distribution are trainable. Below is the code implementation to define our posterior distribution."
},
{
"code": null,
"e": 11070,
"s": 10776,
"text": "Now the question is, what is this VariableLayers defined in the posterior function above? The idea behind this variable layers is that we try to approximate the true posterior distribution. Normally, it’s not possible to derive the true posterior distribution, hence we need to approximate it."
},
{
"code": null,
"e": 11250,
"s": 11070,
"text": "After defining the prior and the posterior function, now we can build our probabilistic linear regression model with weight uncertainty. Below is the code implementation for that."
},
{
"code": null,
"e": 11589,
"s": 11250,
"text": "As you may notice, the only difference between this model and the previous probabilistic regression model is just the first layer. Instead of using a normal dense layer, we use the DenseVariational layer. In this layer, we pass our prior and posterior functions as the argument. The second layer is exactly the same as the previous model."
},
{
"code": null,
"e": 11642,
"s": 11589,
"text": "Now it’s time for us to compile and train the model."
},
{
"code": null,
"e": 11840,
"s": 11642,
"text": "The optimizer and the cost function are still the same as the previous model. We use RMSprop as the optimizer and the negative log-likelihood as our cost function. Let’s compile and train or model."
},
{
"code": null,
"e": 11989,
"s": 11840,
"text": "Now it’s time for us to visualize the weight or slope uncertainty of our regression model. Below is the code implementation to visualize the result."
},
{
"code": null,
"e": 12369,
"s": 11989,
"text": "In the visualization above, you can see that the linear line (mean) as well as the standard deviation that has been generated by the posterior distribution of the trained model is different in each iteration. All of these lines are a plausible solution to fit the data points in the test set. However, due to epistemic uncertainty, we don’t know which line would be the best one."
},
{
"code": null,
"e": 12478,
"s": 12369,
"text": "Usually, the more the data points we have, the less the uncertainty of the regression line that we will see."
},
{
"code": null,
"e": 12768,
"s": 12478,
"text": "And that’s it! Now you’ve seen how the probabilistic linear regression differs from the deterministic linear regression. With probabilistic linear regression, two types of uncertainty that arise from both the data (aleatoric) and the regression model (epistemic) can be taken into account."
},
{
"code": null,
"e": 13015,
"s": 12768,
"text": "Taking these uncertainties into account is very important if we want to build a deep learning model where the inaccurate predictions lead to very serious negative consequences, for example in the field of autonomous driving and medical diagnosis."
}
] |
HTML - <noframes> Tag | The HTML <noframes> tag is used to handle the browsers which do not support <frame> tag. This tag is used to display alternate text message.
<!DOCTYPE html>
<html>
<head>
<title>HTML noframes Tag</title>
</head>
<frameset cols = "200, *">
<frame src = "/html/menu.htm" name = "menu_page" />
<frame src = "/html/main.htm" name = "main_page" />
<noframes>
<body>
Your browser does not support frames.
</body>
</noframes>
</frameset>
</html>
This will produce the following result, refer the image given below. The left frame is menu.htm and the right one is main.htm. If the browser doesn't support frames, it will display the message "Your browser does not support frames."
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
HTML Tutorial
HTML - Home
HTML - Overview
HTML - Basic Tags
HTML - Elements
HTML - Attributes
HTML - Formatting
HTML - Phrase Tags
HTML - Meta Tags
HTML - Comments
HTML - Images
HTML - Tables
HTML - Lists
HTML - Text Links
HTML - Image Links
HTML - Email Links
HTML - Frames
HTML - Iframes
HTML - Blocks
HTML - Backgrounds
HTML - Colors
HTML - Fonts
HTML - Forms
HTML - Embed Multimedia
HTML - Marquees
HTML - Header
HTML - Style Sheet
HTML - Javascript
HTML - Layouts
HTML References
HTML - Tags Reference
HTML - Attributes Reference
HTML - Events Reference
HTML - Fonts Reference
HTML - ASCII Codes
ASCII Table Lookup
HTML - Color Names
HTML - Entities
HTML - Fonts Ref
HTML - Events Ref
MIME Media Types
HTML - URL Encoding
Language ISO Codes
HTML - Character Encodings
HTML - Deprecated Tags
HTML Resources
HTML - Quick Guide
HTML - Useful Resources
HTML - Color Code Builder
HTML - Discussion
HTML - Online Editor
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
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": 2515,
"s": 2374,
"text": "The HTML <noframes> tag is used to handle the browsers which do not support <frame> tag. This tag is used to display alternate text message."
},
{
"code": null,
"e": 2898,
"s": 2515,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML noframes Tag</title>\n </head>\n \n <frameset cols = \"200, *\">\n <frame src = \"/html/menu.htm\" name = \"menu_page\" />\n <frame src = \"/html/main.htm\" name = \"main_page\" />\n \n <noframes>\n <body>\n Your browser does not support frames.\n </body>\n </noframes>\n </frameset>\n\n</html>"
},
{
"code": null,
"e": 3132,
"s": 2898,
"text": "This will produce the following result, refer the image given below. The left frame is menu.htm and the right one is main.htm. If the browser doesn't support frames, it will display the message \"Your browser does not support frames.\""
},
{
"code": null,
"e": 3779,
"s": 3132,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 3799,
"s": 3779,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 3822,
"s": 3799,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 3845,
"s": 3822,
"text": " Computer Programming "
},
{
"code": null,
"e": 3864,
"s": 3845,
"text": " Computer Science "
},
{
"code": null,
"e": 3876,
"s": 3864,
"text": " Databases "
},
{
"code": null,
"e": 3885,
"s": 3876,
"text": " DevOps "
},
{
"code": null,
"e": 3905,
"s": 3885,
"text": " Digital Marketing "
},
{
"code": null,
"e": 3929,
"s": 3905,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 3946,
"s": 3929,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 3965,
"s": 3946,
"text": " Famous Monuments "
},
{
"code": null,
"e": 3987,
"s": 3965,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 4009,
"s": 3987,
"text": " Latest Technologies "
},
{
"code": null,
"e": 4028,
"s": 4009,
"text": " Machine Learning "
},
{
"code": null,
"e": 4052,
"s": 4028,
"text": " Mainframe Development "
},
{
"code": null,
"e": 4075,
"s": 4052,
"text": " Management Tutorials "
},
{
"code": null,
"e": 4098,
"s": 4075,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 4123,
"s": 4098,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 4140,
"s": 4123,
"text": " Misc tutorials "
},
{
"code": null,
"e": 4161,
"s": 4140,
"text": " Mobile Development "
},
{
"code": null,
"e": 4181,
"s": 4161,
"text": " Java Technologies "
},
{
"code": null,
"e": 4203,
"s": 4181,
"text": " Python Technologies "
},
{
"code": null,
"e": 4219,
"s": 4203,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 4240,
"s": 4219,
"text": "Programming Scripts "
},
{
"code": null,
"e": 4259,
"s": 4240,
"text": " Selected Reading "
},
{
"code": null,
"e": 4278,
"s": 4259,
"text": " Software Quality "
},
{
"code": null,
"e": 4292,
"s": 4278,
"text": " Soft Skills "
},
{
"code": null,
"e": 4312,
"s": 4292,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 4329,
"s": 4312,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 4347,
"s": 4329,
"text": " Web Development "
},
{
"code": null,
"e": 4366,
"s": 4347,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 4385,
"s": 4366,
"text": " XML Technologies "
},
{
"code": null,
"e": 4401,
"s": 4385,
"text": " Multi-Language"
},
{
"code": null,
"e": 4422,
"s": 4401,
"text": " Interview Questions"
},
{
"code": null,
"e": 4436,
"s": 4422,
"text": "HTML Tutorial"
},
{
"code": null,
"e": 4448,
"s": 4436,
"text": "HTML - Home"
},
{
"code": null,
"e": 4464,
"s": 4448,
"text": "HTML - Overview"
},
{
"code": null,
"e": 4482,
"s": 4464,
"text": "HTML - Basic Tags"
},
{
"code": null,
"e": 4498,
"s": 4482,
"text": "HTML - Elements"
},
{
"code": null,
"e": 4516,
"s": 4498,
"text": "HTML - Attributes"
},
{
"code": null,
"e": 4534,
"s": 4516,
"text": "HTML - Formatting"
},
{
"code": null,
"e": 4553,
"s": 4534,
"text": "HTML - Phrase Tags"
},
{
"code": null,
"e": 4570,
"s": 4553,
"text": "HTML - Meta Tags"
},
{
"code": null,
"e": 4586,
"s": 4570,
"text": "HTML - Comments"
},
{
"code": null,
"e": 4600,
"s": 4586,
"text": "HTML - Images"
},
{
"code": null,
"e": 4614,
"s": 4600,
"text": "HTML - Tables"
},
{
"code": null,
"e": 4627,
"s": 4614,
"text": "HTML - Lists"
},
{
"code": null,
"e": 4645,
"s": 4627,
"text": "HTML - Text Links"
},
{
"code": null,
"e": 4664,
"s": 4645,
"text": "HTML - Image Links"
},
{
"code": null,
"e": 4683,
"s": 4664,
"text": "HTML - Email Links"
},
{
"code": null,
"e": 4697,
"s": 4683,
"text": "HTML - Frames"
},
{
"code": null,
"e": 4712,
"s": 4697,
"text": "HTML - Iframes"
},
{
"code": null,
"e": 4726,
"s": 4712,
"text": "HTML - Blocks"
},
{
"code": null,
"e": 4745,
"s": 4726,
"text": "HTML - Backgrounds"
},
{
"code": null,
"e": 4759,
"s": 4745,
"text": "HTML - Colors"
},
{
"code": null,
"e": 4772,
"s": 4759,
"text": "HTML - Fonts"
},
{
"code": null,
"e": 4785,
"s": 4772,
"text": "HTML - Forms"
},
{
"code": null,
"e": 4809,
"s": 4785,
"text": "HTML - Embed Multimedia"
},
{
"code": null,
"e": 4825,
"s": 4809,
"text": "HTML - Marquees"
},
{
"code": null,
"e": 4839,
"s": 4825,
"text": "HTML - Header"
},
{
"code": null,
"e": 4858,
"s": 4839,
"text": "HTML - Style Sheet"
},
{
"code": null,
"e": 4876,
"s": 4858,
"text": "HTML - Javascript"
},
{
"code": null,
"e": 4891,
"s": 4876,
"text": "HTML - Layouts"
},
{
"code": null,
"e": 4907,
"s": 4891,
"text": "HTML References"
},
{
"code": null,
"e": 4929,
"s": 4907,
"text": "HTML - Tags Reference"
},
{
"code": null,
"e": 4957,
"s": 4929,
"text": "HTML - Attributes Reference"
},
{
"code": null,
"e": 4982,
"s": 4957,
"text": "HTML - Events Reference "
},
{
"code": null,
"e": 5005,
"s": 4982,
"text": "HTML - Fonts Reference"
},
{
"code": null,
"e": 5024,
"s": 5005,
"text": "HTML - ASCII Codes"
},
{
"code": null,
"e": 5043,
"s": 5024,
"text": "ASCII Table Lookup"
},
{
"code": null,
"e": 5062,
"s": 5043,
"text": "HTML - Color Names"
},
{
"code": null,
"e": 5078,
"s": 5062,
"text": "HTML - Entities"
},
{
"code": null,
"e": 5095,
"s": 5078,
"text": "HTML - Fonts Ref"
},
{
"code": null,
"e": 5113,
"s": 5095,
"text": "HTML - Events Ref"
},
{
"code": null,
"e": 5130,
"s": 5113,
"text": "MIME Media Types"
},
{
"code": null,
"e": 5150,
"s": 5130,
"text": "HTML - URL Encoding"
},
{
"code": null,
"e": 5169,
"s": 5150,
"text": "Language ISO Codes"
},
{
"code": null,
"e": 5196,
"s": 5169,
"text": "HTML - Character Encodings"
},
{
"code": null,
"e": 5219,
"s": 5196,
"text": "HTML - Deprecated Tags"
},
{
"code": null,
"e": 5234,
"s": 5219,
"text": "HTML Resources"
},
{
"code": null,
"e": 5253,
"s": 5234,
"text": "HTML - Quick Guide"
},
{
"code": null,
"e": 5277,
"s": 5253,
"text": "HTML - Useful Resources"
},
{
"code": null,
"e": 5303,
"s": 5277,
"text": "HTML - Color Code Builder"
},
{
"code": null,
"e": 5321,
"s": 5303,
"text": "HTML - Discussion"
},
{
"code": null,
"e": 5342,
"s": 5321,
"text": "HTML - Online Editor"
},
{
"code": null,
"e": 5359,
"s": 5342,
"text": "Selected Reading"
},
{
"code": null,
"e": 5380,
"s": 5359,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 5407,
"s": 5380,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 5429,
"s": 5407,
"text": "Questions and Answers"
},
{
"code": null,
"e": 5454,
"s": 5429,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 5477,
"s": 5454,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 5495,
"s": 5477,
"text": "Computer Glossary"
},
{
"code": null,
"e": 5506,
"s": 5495,
"text": "Who is Who"
},
{
"code": null,
"e": 5539,
"s": 5506,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5553,
"s": 5539,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5588,
"s": 5553,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5602,
"s": 5588,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5637,
"s": 5602,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5654,
"s": 5637,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5689,
"s": 5654,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5720,
"s": 5689,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5753,
"s": 5720,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5784,
"s": 5753,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5819,
"s": 5784,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5850,
"s": 5819,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5857,
"s": 5850,
"text": " Print"
},
{
"code": null,
"e": 5868,
"s": 5857,
"text": " Add Notes"
}
] |
How to call Private Constructor in Java | The method java.lang.Class.getDeclaredConstructor() can be used to obtain the constructor object for the private constructor of the class. The parameter for this method is a Class object array that contains the formal parameter types of the constructor.
A program that demonstrates this is given as follows −
Live Demo
package Test;
import java.lang.reflect.*;
public class Demo {
String str;
Double d;
public Demo(String str, Double d) {
this.str = str;
this.d = d;
}
public static void main(String[] args) {
try {
Demo obj = new Demo("Apple", 55.983);
Class c = obj.getClass();
Class[] arguments = new Class[2];
arguments[0] = String.class;
arguments[1] = Double.class;
Constructor constructor = c.getDeclaredConstructor(arguments);
System.out.println("Constructor = " + constructor.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
} catch(SecurityException e) {
System.out.println(e.toString());
}
}
}
Constructor = public Test.Demo(java.lang.String,java.lang.Double)
Now let us understand the above program.
An object of class Demo is created in the main() method. Then the array arguments[] stores the String.Class and Double.Class objects. Finally, the method getDeclaredConstructor() can be used to obtain the constructor object and this is displayed. A code snippet which demonstrates this is as follows −
Demo obj = new Demo("Apple", 55.983);
Class c = obj.getClass();
Class[] arguments = new Class[2];
arguments[0] = String.class;
arguments[1] = Double.class;
Constructor constructor = c.getDeclaredConstructor(arguments);
System.out.println("Constructor = " + constructor.toString()); | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": "The method java.lang.Class.getDeclaredConstructor() can be used to obtain the constructor object for the private constructor of the class. The parameter for this method is a Class object array that contains the formal parameter types of the constructor."
},
{
"code": null,
"e": 1371,
"s": 1316,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1382,
"s": 1371,
"text": " Live Demo"
},
{
"code": null,
"e": 2136,
"s": 1382,
"text": "package Test;\nimport java.lang.reflect.*;\npublic class Demo {\n String str;\n Double d;\n public Demo(String str, Double d) {\n this.str = str;\n this.d = d;\n }\n public static void main(String[] args) {\n try {\n Demo obj = new Demo(\"Apple\", 55.983);\n Class c = obj.getClass();\n Class[] arguments = new Class[2];\n arguments[0] = String.class;\n arguments[1] = Double.class;\n Constructor constructor = c.getDeclaredConstructor(arguments);\n System.out.println(\"Constructor = \" + constructor.toString());\n } catch(NoSuchMethodException e) {\n System.out.println(e.toString());\n } catch(SecurityException e) {\n System.out.println(e.toString());\n }\n }\n}"
},
{
"code": null,
"e": 2202,
"s": 2136,
"text": "Constructor = public Test.Demo(java.lang.String,java.lang.Double)"
},
{
"code": null,
"e": 2243,
"s": 2202,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2545,
"s": 2243,
"text": "An object of class Demo is created in the main() method. Then the array arguments[] stores the String.Class and Double.Class objects. Finally, the method getDeclaredConstructor() can be used to obtain the constructor object and this is displayed. A code snippet which demonstrates this is as follows −"
},
{
"code": null,
"e": 2827,
"s": 2545,
"text": "Demo obj = new Demo(\"Apple\", 55.983);\nClass c = obj.getClass();\nClass[] arguments = new Class[2];\narguments[0] = String.class;\narguments[1] = Double.class;\nConstructor constructor = c.getDeclaredConstructor(arguments);\nSystem.out.println(\"Constructor = \" + constructor.toString());"
}
] |
logb() function in C++ STL - GeeksforGeeks | 18 Jul, 2018
The logb() is a builtin function in C++ STL which returns the logarithm of |x|, using FLT_RADIX as base for the logarithm. In general, the value of FLT_RADIX is 2, so logb() is equivalent to log2()(for positive values only).
Syntax:
logb(val)
Parameter: The function accepts a single mandatory parameter val which specifies the val whose logb() is to be calculated. The data-type can be of double, float, long double or int.
Return Type: The function returns the logarithm of |x|.
Below programs illustrate the above function:
Program 1:
// C++ program to illustrate// to implement logb() function// when data-type is integer#include <cmath>#include <iostream>using namespace std;int main(){ double result; int x = -10; result = logb(x); cout << "logb(" << x << ") = " << "log(|" << x << "|) = " << result << endl; x = 10; result = logb(x); cout << "logb(" << x << ") = " << "log(|" << x << "|) = " << result << endl; return 0;}
logb(-10) = log(|-10|) = 3
logb(10) = log(|10|) = 3
Program2:
// C++ program to illustrate// to implement logb() function// when data-type is double#include <cmath>#include <iostream> using namespace std; int main(){ double x = 70.56, result; result = logb(x); cout << "logb(" << x << ") = " << "log(|" << x << "|) = " << result << endl; x = 17.6; result = logb(x); cout << "logb(" << x << ") = " << "log(|" << x << "|) = " << result << endl; return 0;}
logb(70.56) = log(|70.56|) = 6
logb(17.6) = log(|17.6|) = 4
Program3:
// C++ program to illustrate// to implement logb() function// when input is 0#include <cmath>#include <iostream> using namespace std; int main(){ double result; int x = 0; result = logb(x); cout << "logb(" << x << ") = " << "log(|" << x << "|) = " << result << endl; return 0;}
logb(0) = log(|0|) = -inf
CPP-Functions
cpp-math
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
new and delete operators in C++ for dynamic memory
Destructors in C++
Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 23707,
"s": 23679,
"text": "\n18 Jul, 2018"
},
{
"code": null,
"e": 23932,
"s": 23707,
"text": "The logb() is a builtin function in C++ STL which returns the logarithm of |x|, using FLT_RADIX as base for the logarithm. In general, the value of FLT_RADIX is 2, so logb() is equivalent to log2()(for positive values only)."
},
{
"code": null,
"e": 23940,
"s": 23932,
"text": "Syntax:"
},
{
"code": null,
"e": 23950,
"s": 23940,
"text": "logb(val)"
},
{
"code": null,
"e": 24132,
"s": 23950,
"text": "Parameter: The function accepts a single mandatory parameter val which specifies the val whose logb() is to be calculated. The data-type can be of double, float, long double or int."
},
{
"code": null,
"e": 24188,
"s": 24132,
"text": "Return Type: The function returns the logarithm of |x|."
},
{
"code": null,
"e": 24234,
"s": 24188,
"text": "Below programs illustrate the above function:"
},
{
"code": null,
"e": 24245,
"s": 24234,
"text": "Program 1:"
},
{
"code": "// C++ program to illustrate// to implement logb() function// when data-type is integer#include <cmath>#include <iostream>using namespace std;int main(){ double result; int x = -10; result = logb(x); cout << \"logb(\" << x << \") = \" << \"log(|\" << x << \"|) = \" << result << endl; x = 10; result = logb(x); cout << \"logb(\" << x << \") = \" << \"log(|\" << x << \"|) = \" << result << endl; return 0;}",
"e": 24684,
"s": 24245,
"text": null
},
{
"code": null,
"e": 24737,
"s": 24684,
"text": "logb(-10) = log(|-10|) = 3\nlogb(10) = log(|10|) = 3\n"
},
{
"code": null,
"e": 24747,
"s": 24737,
"text": "Program2:"
},
{
"code": "// C++ program to illustrate// to implement logb() function// when data-type is double#include <cmath>#include <iostream> using namespace std; int main(){ double x = 70.56, result; result = logb(x); cout << \"logb(\" << x << \") = \" << \"log(|\" << x << \"|) = \" << result << endl; x = 17.6; result = logb(x); cout << \"logb(\" << x << \") = \" << \"log(|\" << x << \"|) = \" << result << endl; return 0;}",
"e": 25186,
"s": 24747,
"text": null
},
{
"code": null,
"e": 25247,
"s": 25186,
"text": "logb(70.56) = log(|70.56|) = 6\nlogb(17.6) = log(|17.6|) = 4\n"
},
{
"code": null,
"e": 25257,
"s": 25247,
"text": "Program3:"
},
{
"code": "// C++ program to illustrate// to implement logb() function// when input is 0#include <cmath>#include <iostream> using namespace std; int main(){ double result; int x = 0; result = logb(x); cout << \"logb(\" << x << \") = \" << \"log(|\" << x << \"|) = \" << result << endl; return 0;}",
"e": 25564,
"s": 25257,
"text": null
},
{
"code": null,
"e": 25591,
"s": 25564,
"text": "logb(0) = log(|0|) = -inf\n"
},
{
"code": null,
"e": 25605,
"s": 25591,
"text": "CPP-Functions"
},
{
"code": null,
"e": 25614,
"s": 25605,
"text": "cpp-math"
},
{
"code": null,
"e": 25618,
"s": 25614,
"text": "STL"
},
{
"code": null,
"e": 25622,
"s": 25618,
"text": "C++"
},
{
"code": null,
"e": 25626,
"s": 25622,
"text": "STL"
},
{
"code": null,
"e": 25630,
"s": 25626,
"text": "CPP"
},
{
"code": null,
"e": 25728,
"s": 25630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25737,
"s": 25728,
"text": "Comments"
},
{
"code": null,
"e": 25750,
"s": 25737,
"text": "Old Comments"
},
{
"code": null,
"e": 25778,
"s": 25750,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25802,
"s": 25778,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 25835,
"s": 25802,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 25855,
"s": 25835,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25899,
"s": 25855,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25943,
"s": 25899,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 25979,
"s": 25943,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 26030,
"s": 25979,
"text": "new and delete operators in C++ for dynamic memory"
},
{
"code": null,
"e": 26049,
"s": 26030,
"text": "Destructors in C++"
}
] |
How to subset an R data frame based on numerical and categorical column? | Subsetting is one of the commonly used technique which serves many different purposes
depending on the objective of analysis. To subset a data frame by excluding a column
with the help of dplyr package, we can follow the below steps −
Creating a data frame.
Subsetting the data frame based on numerical as well as categorical column at the
same time with the help of filter function of dplyr package.
Let's create a data frame as shown below −
Live Demo
Level<-sample(c("Low","Medium","High"),20,replace=TRUE)
Score<-sample(1:10,20,replace=TRUE)
Dat<-data.frame(Level,Score)
Dat
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
Level Score
1 High 4
2 Low 7
3 High 1
4 Medium 6
5 Medium 10
6 High 9
7 High 9
8 Low 3
9 Low 3
10 High 4
11 Low 5
12 Medium 3
13 High 8
14 High 10
15 High 5
16 Low 8
17 High 10
18 High 7
19 Low 10
20 Low 6
Loading dplyr package and subsetting Dat when Score column is greater than 5 and Level is equal to Low −
library(dplyr)
Level<-sample(c("Low","Medium","High"),20,replace=TRUE)
Score<-sample(1:10,20,replace=TRUE)
Dat<-data.frame(Level,Score)
Dat%>%filter(Score>5,Level=="Low")
Level Score
1 Low 7
2 Low 8
3 Low 10
4 Low 6 | [
{
"code": null,
"e": 1297,
"s": 1062,
"text": "Subsetting is one of the commonly used technique which serves many different purposes\ndepending on the objective of analysis. To subset a data frame by excluding a column\nwith the help of dplyr package, we can follow the below steps −"
},
{
"code": null,
"e": 1320,
"s": 1297,
"text": "Creating a data frame."
},
{
"code": null,
"e": 1463,
"s": 1320,
"text": "Subsetting the data frame based on numerical as well as categorical column at the\nsame time with the help of filter function of dplyr package."
},
{
"code": null,
"e": 1506,
"s": 1463,
"text": "Let's create a data frame as shown below −"
},
{
"code": null,
"e": 1517,
"s": 1506,
"text": " Live Demo"
},
{
"code": null,
"e": 1642,
"s": 1517,
"text": "Level<-sample(c(\"Low\",\"Medium\",\"High\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\nDat<-data.frame(Level,Score)\nDat"
},
{
"code": null,
"e": 1761,
"s": 1642,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 1978,
"s": 1761,
"text": " Level Score\n1 High 4\n2 Low 7\n3 High 1\n4 Medium 6\n5 Medium 10\n6 High 9\n7 High 9\n8 Low 3\n9 Low 3\n10 High 4\n11 Low 5\n12 Medium 3\n13 High 8\n14 High 10\n15 High 5\n16 Low 8\n17 High 10\n18 High 7\n19 Low 10\n20 Low 6"
},
{
"code": null,
"e": 2083,
"s": 1978,
"text": "Loading dplyr package and subsetting Dat when Score column is greater than 5 and Level is equal to Low −"
},
{
"code": null,
"e": 2254,
"s": 2083,
"text": "library(dplyr)\nLevel<-sample(c(\"Low\",\"Medium\",\"High\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\nDat<-data.frame(Level,Score)\nDat%>%filter(Score>5,Level==\"Low\")"
},
{
"code": null,
"e": 2300,
"s": 2254,
"text": " Level Score\n1 Low 7\n2 Low 8\n3 Low 10\n4 Low 6"
}
] |
Boolean Literals in Java | The Boolean literals have two values i.e. True and False.
The following is an example to display Boolean Literals.
Live Demo
public class Demo {
public static void main(String[] args) {
System.out.println("Boolean Literals");
boolean one = true;
System.out.println(one);
one = false;
System.out.println(one);
}
}
Boolean Literals
true
false
In the above program, we have declared a boolean value and assigned the boolean literal “true”.
boolean one = true;
In the same way, we have added another boolean literal “false”.
one = false;
Both of the above values are displayed, which are the boolean literals. | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "The Boolean literals have two values i.e. True and False."
},
{
"code": null,
"e": 1177,
"s": 1120,
"text": "The following is an example to display Boolean Literals."
},
{
"code": null,
"e": 1188,
"s": 1177,
"text": " Live Demo"
},
{
"code": null,
"e": 1412,
"s": 1188,
"text": "public class Demo {\n public static void main(String[] args) {\n System.out.println(\"Boolean Literals\");\n boolean one = true;\n System.out.println(one);\n one = false;\n System.out.println(one);\n }\n}"
},
{
"code": null,
"e": 1440,
"s": 1412,
"text": "Boolean Literals\ntrue\nfalse"
},
{
"code": null,
"e": 1536,
"s": 1440,
"text": "In the above program, we have declared a boolean value and assigned the boolean literal “true”."
},
{
"code": null,
"e": 1556,
"s": 1536,
"text": "boolean one = true;"
},
{
"code": null,
"e": 1620,
"s": 1556,
"text": "In the same way, we have added another boolean literal “false”."
},
{
"code": null,
"e": 1633,
"s": 1620,
"text": "one = false;"
},
{
"code": null,
"e": 1705,
"s": 1633,
"text": "Both of the above values are displayed, which are the boolean literals."
}
] |
Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second) - GeeksforGeeks | 28 Jun, 2021
What is Vector of Pairs?A pair is a container which stores two values mapped to each other, and a vector containing multiple number of such pairs is called a vector of pairs.
// C++ program to demonstrate vector of pairs#include<bits/stdc++.h>using namespace std; int main(){ //declaring vector of pairs vector< pair <int,int> > vect; // initialising 1st and 2nd element of // pairs with array values int arr[] = {10, 20, 5, 40 }; int arr1[] = {30, 60, 20, 50}; int n = sizeof(arr)/sizeof(arr[0]); // Entering values in vector of pairs for (int i=0; i<n; i++) vect.push_back( make_pair(arr[i],arr1[i]) ); // Printing the vector for (int i=0; i<n; i++) { // "first" and "second" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << " " << vect[i].second << endl; } return 0;}
Output:
10 30
20 60
5 20
40 50
Case 1 : Sorting the vector elements on the basis of first element of pairs in ascending order.This type of sorting can be achieved using simple “ sort() ” function. By default the sort function sorts the vector elements on basis of first element of pairs.
// C++ program to demonstrate sorting in// vector of pair according to 1st element// of pair#include<bits/stdc++.h>using namespace std; int main(){ // Declaring vector of pairs vector< pair <int,int> > vect; // Initializing 1st and 2nd element of // pairs with array values int arr[] = {10, 20, 5, 40 }; int arr1[] = {30, 60, 20, 50}; int n = sizeof(arr)/sizeof(arr[0]); // Entering values in vector of pairs for (int i=0; i<n; i++) vect.push_back( make_pair(arr[i],arr1[i]) ); // Printing the original vector(before sort()) cout << "The vector before sort operation is:\n" ; for (int i=0; i<n; i++) { // "first" and "second" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << " " << vect[i].second << endl; } // Using simple sort() function to sort sort(vect.begin(), vect.end()); // Printing the sorted vector(after using sort()) cout << "The vector after sort operation is:\n" ; for (int i=0; i<n; i++) { // "first" and "second" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << " " << vect[i].second << endl; } return 0;}
Output:
The vector before applying sort operation is:
10 30
20 60
5 20
40 50
The vector after applying sort operation is:
5 20
10 30
20 60
40 50
Case 2 : Sorting the vector elements on the basis of second element of pairs in ascending order.There are instances when we require to sort the elements of vector on the basis of second elements of pair. For that, we modify the sort() function and we pass a third argument, a call to an user defined explicit function in the sort() function.
// C++ program to demonstrate sorting in vector// of pair according to 2nd element of pair#include<bits/stdc++.h>using namespace std; // Driver function to sort the vector elements// by second element of pairsbool sortbysec(const pair<int,int> &a, const pair<int,int> &b){ return (a.second < b.second);} int main(){ // declaring vector of pairs vector< pair <int, int> > vect; // Initialising 1st and 2nd element of pairs // with array values int arr[] = {10, 20, 5, 40 }; int arr1[] = {30, 60, 20, 50}; int n = sizeof(arr)/sizeof(arr[0]); // Entering values in vector of pairs for (int i=0; i<n; i++) vect.push_back( make_pair(arr[i],arr1[i]) ); // Printing the original vector(before sort()) cout << "The vector before sort operation is:\n" ; for (int i=0; i<n; i++) { // "first" and "second" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << " " << vect[i].second << endl; } // Using sort() function to sort by 2nd element // of pair sort(vect.begin(), vect.end(), sortbysec); // Printing the sorted vector(after using sort()) cout << "The vector after sort operation is:\n" ; for (int i=0; i<n; i++) { // "first" and "second" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << " " << vect[i].second << endl; } return 0;}
Output:
The vector before applying sort operation is:
10 30
20 60
5 20
40 50
The vector after applying sort operation is:
5 20
10 30
40 50
20 60
Sorting Vector of Pairs in C++ | Set 2 (Sort in descending order by first and second) This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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.
CPP-Library
cpp-vector
STL
C Language
C++
Sorting
Sorting
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
Constructors in C++ | [
{
"code": null,
"e": 24533,
"s": 24505,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24708,
"s": 24533,
"text": "What is Vector of Pairs?A pair is a container which stores two values mapped to each other, and a vector containing multiple number of such pairs is called a vector of pairs."
},
{
"code": "// C++ program to demonstrate vector of pairs#include<bits/stdc++.h>using namespace std; int main(){ //declaring vector of pairs vector< pair <int,int> > vect; // initialising 1st and 2nd element of // pairs with array values int arr[] = {10, 20, 5, 40 }; int arr1[] = {30, 60, 20, 50}; int n = sizeof(arr)/sizeof(arr[0]); // Entering values in vector of pairs for (int i=0; i<n; i++) vect.push_back( make_pair(arr[i],arr1[i]) ); // Printing the vector for (int i=0; i<n; i++) { // \"first\" and \"second\" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << \" \" << vect[i].second << endl; } return 0;}",
"e": 25434,
"s": 24708,
"text": null
},
{
"code": null,
"e": 25442,
"s": 25434,
"text": "Output:"
},
{
"code": null,
"e": 25466,
"s": 25442,
"text": "10 30\n20 60\n5 20\n40 50\n"
},
{
"code": null,
"e": 25725,
"s": 25468,
"text": "Case 1 : Sorting the vector elements on the basis of first element of pairs in ascending order.This type of sorting can be achieved using simple “ sort() ” function. By default the sort function sorts the vector elements on basis of first element of pairs."
},
{
"code": "// C++ program to demonstrate sorting in// vector of pair according to 1st element// of pair#include<bits/stdc++.h>using namespace std; int main(){ // Declaring vector of pairs vector< pair <int,int> > vect; // Initializing 1st and 2nd element of // pairs with array values int arr[] = {10, 20, 5, 40 }; int arr1[] = {30, 60, 20, 50}; int n = sizeof(arr)/sizeof(arr[0]); // Entering values in vector of pairs for (int i=0; i<n; i++) vect.push_back( make_pair(arr[i],arr1[i]) ); // Printing the original vector(before sort()) cout << \"The vector before sort operation is:\\n\" ; for (int i=0; i<n; i++) { // \"first\" and \"second\" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << \" \" << vect[i].second << endl; } // Using simple sort() function to sort sort(vect.begin(), vect.end()); // Printing the sorted vector(after using sort()) cout << \"The vector after sort operation is:\\n\" ; for (int i=0; i<n; i++) { // \"first\" and \"second\" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << \" \" << vect[i].second << endl; } return 0;}",
"e": 26981,
"s": 25725,
"text": null
},
{
"code": null,
"e": 26989,
"s": 26981,
"text": "Output:"
},
{
"code": null,
"e": 27127,
"s": 26989,
"text": "The vector before applying sort operation is:\n10 30\n20 60\n5 20\n40 50\nThe vector after applying sort operation is:\n5 20\n10 30\n20 60\n40 50\n"
},
{
"code": null,
"e": 27471,
"s": 27129,
"text": "Case 2 : Sorting the vector elements on the basis of second element of pairs in ascending order.There are instances when we require to sort the elements of vector on the basis of second elements of pair. For that, we modify the sort() function and we pass a third argument, a call to an user defined explicit function in the sort() function."
},
{
"code": "// C++ program to demonstrate sorting in vector// of pair according to 2nd element of pair#include<bits/stdc++.h>using namespace std; // Driver function to sort the vector elements// by second element of pairsbool sortbysec(const pair<int,int> &a, const pair<int,int> &b){ return (a.second < b.second);} int main(){ // declaring vector of pairs vector< pair <int, int> > vect; // Initialising 1st and 2nd element of pairs // with array values int arr[] = {10, 20, 5, 40 }; int arr1[] = {30, 60, 20, 50}; int n = sizeof(arr)/sizeof(arr[0]); // Entering values in vector of pairs for (int i=0; i<n; i++) vect.push_back( make_pair(arr[i],arr1[i]) ); // Printing the original vector(before sort()) cout << \"The vector before sort operation is:\\n\" ; for (int i=0; i<n; i++) { // \"first\" and \"second\" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << \" \" << vect[i].second << endl; } // Using sort() function to sort by 2nd element // of pair sort(vect.begin(), vect.end(), sortbysec); // Printing the sorted vector(after using sort()) cout << \"The vector after sort operation is:\\n\" ; for (int i=0; i<n; i++) { // \"first\" and \"second\" are used to access // 1st and 2nd element of pair respectively cout << vect[i].first << \" \" << vect[i].second << endl; } return 0;}",
"e": 28943,
"s": 27471,
"text": null
},
{
"code": null,
"e": 28951,
"s": 28943,
"text": "Output:"
},
{
"code": null,
"e": 29091,
"s": 28951,
"text": " \nThe vector before applying sort operation is:\n10 30\n20 60\n5 20\n40 50\nThe vector after applying sort operation is:\n5 20\n10 30\n40 50\n20 60\n"
},
{
"code": null,
"e": 29474,
"s": 29091,
"text": "Sorting Vector of Pairs in C++ | Set 2 (Sort in descending order by first and second) This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29599,
"s": 29474,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29611,
"s": 29599,
"text": "CPP-Library"
},
{
"code": null,
"e": 29622,
"s": 29611,
"text": "cpp-vector"
},
{
"code": null,
"e": 29626,
"s": 29622,
"text": "STL"
},
{
"code": null,
"e": 29637,
"s": 29626,
"text": "C Language"
},
{
"code": null,
"e": 29641,
"s": 29637,
"text": "C++"
},
{
"code": null,
"e": 29649,
"s": 29641,
"text": "Sorting"
},
{
"code": null,
"e": 29657,
"s": 29649,
"text": "Sorting"
},
{
"code": null,
"e": 29661,
"s": 29657,
"text": "STL"
},
{
"code": null,
"e": 29665,
"s": 29661,
"text": "CPP"
},
{
"code": null,
"e": 29763,
"s": 29665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29772,
"s": 29763,
"text": "Comments"
},
{
"code": null,
"e": 29785,
"s": 29772,
"text": "Old Comments"
},
{
"code": null,
"e": 29813,
"s": 29785,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29859,
"s": 29813,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29871,
"s": 29859,
"text": "fork() in C"
},
{
"code": null,
"e": 29911,
"s": 29871,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 29943,
"s": 29911,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 29989,
"s": 29943,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30032,
"s": 29989,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 30051,
"s": 30032,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30075,
"s": 30051,
"text": "C++ Classes and Objects"
}
] |
Tryit Editor v3.7 | Tryit: HTML color values | [] |
Building Box Plots Using JavaScript: Visualizing World Happiness | by Wayde Herman | Towards Data Science | Data visualization is an important and sometimes undervalued tool in a data scientist’s toolkit. It allows us to gain an understanding and intuition about the data, through exploratory data analysis, which influences preprocessing, feature engineering, and the correct machine learning algorithm choice. It also helps to better evaluate models and even allows you to spot areas in the data where models could have poor performance.
Taking data visualization one step further by adding interactivity is even more advantageous. By adding interactive elements to your visualizations you create a more engaging experience. This in turn makes a user ‘explore’ visualizations instead of just reading them!
In this tutorial, I will be covering how to build an interactive data visualization, specifically a box plot as an example, using JavaScript and a charting library. I will begin by first briefly covering the basics of box plots before going through the steps of building one and then finally using the technique in a fun example to investigate the distribution of happiness between the different regions of the planet in an attempt to answer the question: ‘Where should you live to be happier?’.
A box plot, also widely called a box-and-whisker plot, is a data visualization technique used to visualize descriptive statistics of datasets. While this chart type is not as useful as a histogram at understanding a single datasets distribution, these visualizations do well at allowing a user to compare different datasets.
Box plots visualize the following summary statistics: The median, the first and third quartile (Q1 and Q3), the low and the high as well as the outliers. These are displayed as follows:
To build an interactive data visualization there are a quite a few options. If you want to learn about JavaScript alternatives, you can have a look here. In this example I will be using a JS charting library and specifically AnyChart. I’m going with AnyChart as it supports box-and-whisker plots (among multiple other chart types), and I think both its documentation and API are really great for beginners and advanced users alike but alternatives which better suit your needs can work too and will follow similar steps.
The first step is to set up a page for the box plot visualization. This includes adding the HTML elements, loading the required scripts and setting up the CSS for our chart. Which looks like:
<html> <head> <script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js"></script> <style type="text/css"> html, body, #container { width: 100%; height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="container"></div> </body> <script> anychart.onDocumentReady(function () { // code goes here. }); </script></html>
When using a charting library you will need to import the correct script in order to use that library and in some cases different modules for different chart types. For access to AnyChart’s box-and-whisker chart, for example, I will need to use the base module.
Once that is sorted I will then need to set the CSS properties for my chart element. Here I have set the box chart to have a width and height of 100%. You can change this depending on your own use case. CSS width and height properties accept percentages (of the parent element), and various length units (most commonly pixels).
Finally, I have a script tag with the JavaScript function anychart.onDocumentReady() which is simply a function triggered when the document is loaded. Placing the JavaScript charting code within this function ensures that the code does not trigger before the page is ready which can lead to bad results (read up on asynchronous JavaScript to learn more about this).
I will be using data sourced from the World Happiness Report which is the results compiled from a global survey that attempts to quantify happiness of each country’s citizens to a value between 0 and 10. I obtained this data from Kaggle, a great place to find fun and interesting datasets. Admittedly most of them are geared towards machine learning applications but a few work well for data visualization purposes.
In preparation for drawing box plots, I need to provide the data in a format and form that is accepted by our chosen charting library. For example, AnyChart JS accepts box plot data in the following form:
{x:"Name", low: value, q1: value, median: value, q3: value, high: value, outliers: array}
Where x is the label, q1 and q3 are the first and third quartile values, low and high are the 1.5 x the interquartile range below q1 and 1.5 x the interquartile range above q3 respectively, and the outliers is an array containing all the outlier values.
I have conveniently preprocessed the data from the world happiness report to produce the following array:
var data = [ {x:"Western Europe", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53}, {x:"North America", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40}, {x:"Australia and New Zealand", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33}, {x:"Middle East and Northern Africa", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27}, {x:"Latin America and Caribbean", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]}, {x:"Southeastern Asia", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74}, {x:"Central and Eastern Europe", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60}, {x:"Eastern Asia", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38}, {x:"Sub-Saharan Africa", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]}, {x:"Southern Asia", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]}]
With only these few lines of code I can draw my box plots:
// create a chartchart = anychart.box();// create a box series and set the dataseries = chart.box(data);// set the container idchart.container("container");// initiate drawing the chartchart.draw();
And putting this all together, you will get the following:
<html> <head> <script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js"></script> <style type="text/css"> html, body, #container { width: 100%; height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="container"></div> </body> <script> anychart.onDocumentReady(function () { var data = [ {x:"Western Europe", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53}, {x:"North America", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40}, {x:"Australia and New Zealand", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33}, {x:"Middle East and Northern Africa", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27}, {x:"Latin America and Caribbean", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]}, {x:"Southeastern Asia", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74}, {x:"Central and Eastern Europe", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60}, {x:"Eastern Asia", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38}, {x:"Sub-Saharan Africa", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]}, {x:"Southern Asia", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]} ] // create a chart chart = anychart.box(); // create a box series and set the data series = chart.box(data); // set the container id chart.container("container"); // initiate drawing the chart chart.draw(); }); </script></html>
Which results in:
HTML
CSS
JS
Result
Skip Results Iframe
<html>
<head>
<script src="https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
html, body, #container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
anychart.onDocumentReady(function () {
var data = [
{x:"Western Europe", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53},
{x:"North America", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40},
{x:"Australia & New Zealand", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33},
{x:"Middle East & Northern Africa", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27},
{x:"Latin America & Caribbean", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]},
{x:"Southeastern Asia", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74},
{x:"Central & Eastern Europe", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60},
{x:"Eastern Asia", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38},
{x:"Sub-Saharan Africa", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]},
{x:"Southern Asia", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]}
]
// create a chart
chart = anychart.box();
// create a box series and set the data
series = chart.box(data);
// set the container id
chart.container("container");
// initiate drawing the chart
chart.draw();
});
This Pen is owned by Wayde Herman on CodePen.
See more by @waydeherman on CodePen
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources. | [
{
"code": null,
"e": 603,
"s": 171,
"text": "Data visualization is an important and sometimes undervalued tool in a data scientist’s toolkit. It allows us to gain an understanding and intuition about the data, through exploratory data analysis, which influences preprocessing, feature engineering, and the correct machine learning algorithm choice. It also helps to better evaluate models and even allows you to spot areas in the data where models could have poor performance."
},
{
"code": null,
"e": 871,
"s": 603,
"text": "Taking data visualization one step further by adding interactivity is even more advantageous. By adding interactive elements to your visualizations you create a more engaging experience. This in turn makes a user ‘explore’ visualizations instead of just reading them!"
},
{
"code": null,
"e": 1367,
"s": 871,
"text": "In this tutorial, I will be covering how to build an interactive data visualization, specifically a box plot as an example, using JavaScript and a charting library. I will begin by first briefly covering the basics of box plots before going through the steps of building one and then finally using the technique in a fun example to investigate the distribution of happiness between the different regions of the planet in an attempt to answer the question: ‘Where should you live to be happier?’."
},
{
"code": null,
"e": 1692,
"s": 1367,
"text": "A box plot, also widely called a box-and-whisker plot, is a data visualization technique used to visualize descriptive statistics of datasets. While this chart type is not as useful as a histogram at understanding a single datasets distribution, these visualizations do well at allowing a user to compare different datasets."
},
{
"code": null,
"e": 1878,
"s": 1692,
"text": "Box plots visualize the following summary statistics: The median, the first and third quartile (Q1 and Q3), the low and the high as well as the outliers. These are displayed as follows:"
},
{
"code": null,
"e": 2399,
"s": 1878,
"text": "To build an interactive data visualization there are a quite a few options. If you want to learn about JavaScript alternatives, you can have a look here. In this example I will be using a JS charting library and specifically AnyChart. I’m going with AnyChart as it supports box-and-whisker plots (among multiple other chart types), and I think both its documentation and API are really great for beginners and advanced users alike but alternatives which better suit your needs can work too and will follow similar steps."
},
{
"code": null,
"e": 2591,
"s": 2399,
"text": "The first step is to set up a page for the box plot visualization. This includes adding the HTML elements, loading the required scripts and setting up the CSS for our chart. Which looks like:"
},
{
"code": null,
"e": 3009,
"s": 2591,
"text": "<html> <head> <script src=\"https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js\"></script> <style type=\"text/css\"> html, body, #container { width: 100%; height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id=\"container\"></div> </body> <script> anychart.onDocumentReady(function () { // code goes here. }); </script></html>"
},
{
"code": null,
"e": 3271,
"s": 3009,
"text": "When using a charting library you will need to import the correct script in order to use that library and in some cases different modules for different chart types. For access to AnyChart’s box-and-whisker chart, for example, I will need to use the base module."
},
{
"code": null,
"e": 3599,
"s": 3271,
"text": "Once that is sorted I will then need to set the CSS properties for my chart element. Here I have set the box chart to have a width and height of 100%. You can change this depending on your own use case. CSS width and height properties accept percentages (of the parent element), and various length units (most commonly pixels)."
},
{
"code": null,
"e": 3965,
"s": 3599,
"text": "Finally, I have a script tag with the JavaScript function anychart.onDocumentReady() which is simply a function triggered when the document is loaded. Placing the JavaScript charting code within this function ensures that the code does not trigger before the page is ready which can lead to bad results (read up on asynchronous JavaScript to learn more about this)."
},
{
"code": null,
"e": 4381,
"s": 3965,
"text": "I will be using data sourced from the World Happiness Report which is the results compiled from a global survey that attempts to quantify happiness of each country’s citizens to a value between 0 and 10. I obtained this data from Kaggle, a great place to find fun and interesting datasets. Admittedly most of them are geared towards machine learning applications but a few work well for data visualization purposes."
},
{
"code": null,
"e": 4586,
"s": 4381,
"text": "In preparation for drawing box plots, I need to provide the data in a format and form that is accepted by our chosen charting library. For example, AnyChart JS accepts box plot data in the following form:"
},
{
"code": null,
"e": 4676,
"s": 4586,
"text": "{x:\"Name\", low: value, q1: value, median: value, q3: value, high: value, outliers: array}"
},
{
"code": null,
"e": 4930,
"s": 4676,
"text": "Where x is the label, q1 and q3 are the first and third quartile values, low and high are the 1.5 x the interquartile range below q1 and 1.5 x the interquartile range above q3 respectively, and the outliers is an array containing all the outlier values."
},
{
"code": null,
"e": 5036,
"s": 4930,
"text": "I have conveniently preprocessed the data from the world happiness report to produce the following array:"
},
{
"code": null,
"e": 5960,
"s": 5036,
"text": "var data = [ {x:\"Western Europe\", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53}, {x:\"North America\", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40}, {x:\"Australia and New Zealand\", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33}, {x:\"Middle East and Northern Africa\", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27}, {x:\"Latin America and Caribbean\", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]}, {x:\"Southeastern Asia\", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74}, {x:\"Central and Eastern Europe\", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60}, {x:\"Eastern Asia\", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38}, {x:\"Sub-Saharan Africa\", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]}, {x:\"Southern Asia\", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]}]"
},
{
"code": null,
"e": 6019,
"s": 5960,
"text": "With only these few lines of code I can draw my box plots:"
},
{
"code": null,
"e": 6218,
"s": 6019,
"text": "// create a chartchart = anychart.box();// create a box series and set the dataseries = chart.box(data);// set the container idchart.container(\"container\");// initiate drawing the chartchart.draw();"
},
{
"code": null,
"e": 6277,
"s": 6218,
"text": "And putting this all together, you will get the following:"
},
{
"code": null,
"e": 7911,
"s": 6277,
"text": "<html> <head> <script src=\"https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js\"></script> <style type=\"text/css\"> html, body, #container { width: 100%; height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id=\"container\"></div> </body> <script> anychart.onDocumentReady(function () { var data = [ {x:\"Western Europe\", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53}, {x:\"North America\", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40}, {x:\"Australia and New Zealand\", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33}, {x:\"Middle East and Northern Africa\", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27}, {x:\"Latin America and Caribbean\", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]}, {x:\"Southeastern Asia\", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74}, {x:\"Central and Eastern Europe\", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60}, {x:\"Eastern Asia\", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38}, {x:\"Sub-Saharan Africa\", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]}, {x:\"Southern Asia\", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]} ] // create a chart chart = anychart.box(); // create a box series and set the data series = chart.box(data); // set the container id chart.container(\"container\"); // initiate drawing the chart chart.draw(); }); </script></html>"
},
{
"code": null,
"e": 7929,
"s": 7911,
"text": "Which results in:"
},
{
"code": null,
"e": 7938,
"s": 7929,
"text": "\n\nHTML\n\n"
},
{
"code": null,
"e": 7946,
"s": 7938,
"text": "\n\nCSS\n\n"
},
{
"code": null,
"e": 7953,
"s": 7946,
"text": "\n\nJS\n\n"
},
{
"code": null,
"e": 7964,
"s": 7953,
"text": "\n\nResult\n\n"
},
{
"code": null,
"e": 7986,
"s": 7964,
"text": "\nSkip Results Iframe\n"
},
{
"code": null,
"e": 8179,
"s": 7986,
"text": "<html>\n <head>\n <script src=\"https://cdn.anychart.com/releases/8.8.0/js/anychart-base.min.js\"></script>\n </head>\n <body>\n <div id=\"container\"></div>\n </body>\n</html>\n"
},
{
"code": null,
"e": 8272,
"s": 8179,
"text": "html, body, #container {\n width: 100%;\n height: 100%;\n margin: 0;\n padding: 0;\n}"
},
{
"code": null,
"e": 9505,
"s": 8272,
"text": "anychart.onDocumentReady(function () {\n var data = [\n {x:\"Western Europe\", low: 5.03, q1: 6.36, median: 6.91, q3: 7.34, high: 7.53},\n {x:\"North America\", low: 7.10, q1: 7.18, median: 7.25, q3: 7.33, high: 7.40},\n {x:\"Australia & New Zealand\", low: 7.31, q1: 7.32, median: 7.32, q3: 7.33, high: 7.33},\n {x:\"Middle East & Northern Africa\", low: 3.07, q1: 4.78, median: 5.30, q3: 6.30, high: 7.27},\n {x:\"Latin America & Caribbean\", low: 4.87, q1: 5.80, median: 6.13, q3: 6.66, high: 7.09, outliers: [4.03]},\n {x:\"Southeastern Asia\", low: 3.91, q1: 4.88, median: 5.28, q3: 6.01, high: 6.74},\n {x:\"Central & Eastern Europe\", low: 4.22, q1: 5.15, median: 5.49, q3: 5.81, high: 6.60},\n {x:\"Eastern Asia\", low: 4.91, q1: 5.30, median: 5.65, q3: 5.90, high: 6.38},\n {x:\"Sub-Saharan Africa\", low: 2.91, q1: 3.74, median: 4.13, q3: 4.43, high: 5.44, outliers: [5.648]},\n {x:\"Southern Asia\", low: 4.40, q1: 4.41, median: 4.64, q3: 4.96, high: 5.20, outliers: [3.36]}\n ]\n\n // create a chart\n chart = anychart.box();\n\n // create a box series and set the data\n series = chart.box(data);\n\n // set the container id\n chart.container(\"container\");\n\n // initiate drawing the chart\n chart.draw();\n\n });"
},
{
"code": null,
"e": 9553,
"s": 9505,
"text": "\nThis Pen is owned by Wayde Herman on CodePen.\n"
},
{
"code": null,
"e": 9593,
"s": 9553,
"text": "\n\nSee more by @waydeherman on CodePen\n\n"
},
{
"code": null,
"e": 9644,
"s": 9593,
"text": "\nThis Pen doesn't use any external CSS resources.\n"
}
] |
Count of strings that can be formed from another string using each character at-most once - GeeksforGeeks | 25 Feb, 2022
Given two strings str1 and str2, the task is to print the number of times str2 can be formed using characters of str1. However, a character at any index of str1 can only be used once in the formation of str2.
Examples:
Input: str1 = “arajjhupoot”, str2 = “rajput” Output: 1 Explanation:str2 can only be formed once using characters of str1.
Input: str1 = “foreeksgekseg”, str2 = “geeks” Output: 2
Approach: Since the problem has a restriction on using characters of str1 only once to form str2. If one character has been used to form one str2, it cannot be used in forming another str2. Every character of str2 must be present in str1 at least for the formation of one str1. If all the characters of str2 are already present in str1, then the character which has the minimum occurrence in str1 will be the number of str2’s that can be formed using the characters of str1 once. Below are the steps:
Create an hash-array which stores the number of occurrences of each character of str1 and str2.
Iterate for all the characters of str2, and find the minimum most occurrences of every character in str1.
Return the minimum occurrence which will be the answer.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
PHP
Javascript
/// C++ program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once#include <bits/stdc++.h>using namespace std; // Function to find the number of str2// that can be formed using characters of str1int findNumberOfTimes(string str1, string str2){ int freq[26] = { 0 }; int freq2[26] = { 0 }; int l1 = str1.length(); int l2 = str2.length(); // iterate and mark the frequencies of // all characters in str1 for (int i = 0; i < l1; i++) freq[str1[i] - 'a'] += 1; for (int i = 0; i < l2; i++) freq2[str2[i] - 'a'] += 1; int count = INT_MAX; // find the minimum frequency of // every character in str1 for (int i = 0; i < l2; i++) { if(freq2[str2[i]-'a']!=0) count = min(count, freq[str2[i] - 'a']/freq2[str2[i]-'a']); } return count;} // Driver Codeint main(){ string str1 = "foreeksgekseg"; string str2 = "geeks"; cout << findNumberOfTimes(str1, str2) << endl; return 0;}
// Java program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once class GFG { // Function to find the number of str2// that can be formed using characters of str1 static int findNumberOfTimes(String str1, String str2) { int freq[] = new int[26]; int freq2[] = new int[26]; int l1 = str1.length(); // iterate and mark the frequencies of // all characters in str1 for (int i = 0; i < l1; i++) { freq[str1.charAt(i) - 'a'] += 1; } int l2 = str2.length(); for (int i = 0; i < l2; i++) { freq2[str2.charAt(i) - 'a'] += 1; } int count = Integer.MAX_VALUE; // find the minimum frequency of // every character in str1 for (int i = 0; i < l2; i++) { if(freq2[str2.charAt(i)-'a']!=0) count = Math.min(count, freq[str2.charAt(i) - 'a']/freq2[str2.charAt(i)-'a']); } return count; } public static void main(String[] args) { String str1 = "foreeksgekseg"; String str2 ="geeks"; System.out.println(findNumberOfTimes(str1, str2)); }}/* This code is contributed by 29AjayKumar*/
# Python3 program to print the number of# times str2 can be formed from str1 using# the characters of str1 only onceimport sys # Function to find the number of str2# that can be formed using characters of str1def findNumberOfTimes(str1, str2): freq = [0] * 26 l1 = len(str1) freq2= [0] * 26 l2 = len(str2) # iterate and mark the frequencies # of all characters in str1 for i in range(l1): freq[ord(str1[i]) - ord("a")] += 1 for i in range(l2): freq2[ord(str2[i]) - ord("a")] += 1 count = sys.maxsize # find the minimum frequency of # every character in str1 for i in range(l2): count = min(count, freq[ord(str2[i]) - ord('a')]/freq2[ord(str2[i])-ord('a')]) return count # Driver Codeif __name__ == '__main__': str1 = "foreeksgekseg" str2 = "geeks" print(findNumberOfTimes(str1, str2)) # This code is contributed by PrinciRaj1992
// C# program to print the number of// times str2 can be formed from str1// using the characters of str1 only onceusing System; class GFG { // Function to find the number of // str2 that can be formed using // characters of str1 static int findNumberOfTimes(String str1, String str2) { int[] freq = new int[26]; int l1 = str1.Length; int[] freq2 = new int[26]; int l2 = str2.Length; // iterate and mark the frequencies // of all characters in str1 for (int i = 0; i < l1; i++) { freq[str1[i] - 'a'] += 1; } for (int i = 0; i < l2; i++) { freq2[str2[i] - 'a'] += 1; } int count = int.MaxValue; // find the minimum frequency of // every character in str1 for (int i = 0; i < l2; i++) { if (freq2[str2[i] - 'a'] != 0) count = Math.Min( count, freq[str2[i] - 'a'] / freq2[str2[i] - 'a']); } return count; } // Driver Code public static void Main() { String str1 = "foreeksgekseg"; String str2 = "geeks"; Console.Write(findNumberOfTimes(str1, str2)); }} // This code is contributed by 29AjayKumar
<?php// PHP program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once // Function to find the number of str2// that can be formed using characters of str1function findNumberOfTimes($str1, $str2){ $freq = array_fill(0, 26, NULL); $l1 = strlen($str1); $freq2 = array_fill(0, 26, NULL); $l2 = strlen($str2); // iterate and mark the frequencies // of all characters in str1 for ($i = 0; $i < $l1; $i++) $freq[ord($str1[$i]) - ord('a')] += 1; for ($i = 0; $i < $l2; $i++) $freq2[ord($str2[$i]) - ord('a')] += 1; $count = PHP_INT_MAX; // find the minimum frequency of // every character in str1 for ($i = 0; $i < $l2; $i++) $count = min($count, $freq[ord($str2[$i]) - ord('a')]/$freq2[ord($str2[$i]) - ord('a')]); return $count;} // Driver Code$str1 = "foreeksgekseg";$str2 = "geeks"; echo findNumberOfTimes($str1, $str2) . "\n"; // This code is contributed by ita_c?>
<script>// Javascript program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once // Function to find the number of str2 // that can be formed using characters of str1 function findNumberOfTimes(str1, str2) { let freq = new Array(26); let freq2 = new Array(26); for(let i = 0; i < 26; i++) { freq[i] = 0; freq2[i] = 0; } let l1 = str1.length; // iterate and mark the frequencies of // all characters in str1 for (let i = 0; i < l1; i++) { freq[str1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } let l2 = str2.length; for (let i = 0; i < l2; i++) { freq2[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } let count = Number.MAX_VALUE; // find the minimum frequency of // every character in str1 for (let i = 0; i < l2; i++) { if(freq2[str2[i].charCodeAt(0)-'a'.charCodeAt(0)]!=0) count = Math.min(count, freq[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)]/freq2[str2[i].charCodeAt(0)-'a'.charCodeAt(0)]); } return count; } let str1 = "foreeksgekseg"; let str2 ="geeks"; document.write(findNumberOfTimes(str1, str2)); // This code is contributed by avanitrachhadiya2155</script>
2
Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively. Auxiliary Space: O(1)
Case: Using STL Maps with both uppercase and lowercase characters in str1 and str2.
Approach: The operation is similar to the normal hash-array.
Here, the order does not matter. We just need to check if there are sufficient words in str1 to make str2. Traverse both strings str1 and str2 to store characters as key and their frequencies as value in maps freq1 and freq2. Divide the frequencies stored in map freq1 with frequencies that have a matching key in map freq2. This will give us the maximum number of cycles of str2 that can be formed. Finally return minimum frequency from map freq1 which will be the final answer.
C++14
Javascript
#include <bits/stdc++.h>using namespace std; int countSubStr(char* str,char* substr){ unordered_map<char,int>freq1; unordered_map<char,int>freq2; int i,mn=INT_MAX; int l1=strlen(str); int l2=strlen(substr); for(i=0;i<l1;i++) freq1[str[i]]++; for(i=0;i<l2;i++) freq2[substr[i]]++; for(auto x:freq2) mn=min(mn,freq1[x.first]/x.second); return mn;} int main(){ char str1[]= "arajjhupoot"; char str2[]="rajput"; cout<<countSubStr(str1,str2); return 0;}
<script>function countSubStr(str,substr){ let freq1 = new Map(); let freq2 = new Map(); let i,mn=Number.MAX_VALUE; let l1 = str.length; let l2 = substr.length; for(i = 0; i < l1; i++){ if(freq1.has(str[i]) == true){ freq1.set(str[i], freq1.get(str[i]) + 1); } else{ freq1.set(str[i], 1); } } for(i = 0; i < l2; i++){ if(freq2.has(substr[i]) == true){ freq2.set(substr[i], freq1.get(str[i]) + 1); } else{ freq2.set(substr[i], 1); } } for(let [x, y] of freq2) mn = Math.min(mn,Math.floor(freq1.get(x)/y)); return mn;} // driver codelet str1 = "arajjhupoot";let str2 ="rajput";document.write(countSubStr(str1,str2)); // This code is contributed by shinjanpatra </script>
Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively
Auxiliary Space: O(1) since the total number of distinct characters in both lowercase and uppercase English alphabets is 52 (Constant).
29AjayKumar
princiraj1992
ukasp
nidhi_biet
jyoti369
avanitrachhadiya2155
prophet1999
shinjanpatra
Constructive Algorithms
Hash
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Rearrange an array such that arr[i] = i
Quadratic Probing in Hashing
Hashing in Java
What are Hash Functions and How to choose a good Hash Function?
Real-time application of Data Structures
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": 24767,
"s": 24739,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 24977,
"s": 24767,
"text": "Given two strings str1 and str2, the task is to print the number of times str2 can be formed using characters of str1. However, a character at any index of str1 can only be used once in the formation of str2. "
},
{
"code": null,
"e": 24989,
"s": 24977,
"text": "Examples: "
},
{
"code": null,
"e": 25111,
"s": 24989,
"text": "Input: str1 = “arajjhupoot”, str2 = “rajput” Output: 1 Explanation:str2 can only be formed once using characters of str1."
},
{
"code": null,
"e": 25167,
"s": 25111,
"text": "Input: str1 = “foreeksgekseg”, str2 = “geeks” Output: 2"
},
{
"code": null,
"e": 25669,
"s": 25167,
"text": "Approach: Since the problem has a restriction on using characters of str1 only once to form str2. If one character has been used to form one str2, it cannot be used in forming another str2. Every character of str2 must be present in str1 at least for the formation of one str1. If all the characters of str2 are already present in str1, then the character which has the minimum occurrence in str1 will be the number of str2’s that can be formed using the characters of str1 once. Below are the steps: "
},
{
"code": null,
"e": 25765,
"s": 25669,
"text": "Create an hash-array which stores the number of occurrences of each character of str1 and str2."
},
{
"code": null,
"e": 25871,
"s": 25765,
"text": "Iterate for all the characters of str2, and find the minimum most occurrences of every character in str1."
},
{
"code": null,
"e": 25927,
"s": 25871,
"text": "Return the minimum occurrence which will be the answer."
},
{
"code": null,
"e": 25979,
"s": 25927,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25985,
"s": 25979,
"text": "C++14"
},
{
"code": null,
"e": 25990,
"s": 25985,
"text": "Java"
},
{
"code": null,
"e": 25998,
"s": 25990,
"text": "Python3"
},
{
"code": null,
"e": 26001,
"s": 25998,
"text": "C#"
},
{
"code": null,
"e": 26005,
"s": 26001,
"text": "PHP"
},
{
"code": null,
"e": 26016,
"s": 26005,
"text": "Javascript"
},
{
"code": "/// C++ program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once#include <bits/stdc++.h>using namespace std; // Function to find the number of str2// that can be formed using characters of str1int findNumberOfTimes(string str1, string str2){ int freq[26] = { 0 }; int freq2[26] = { 0 }; int l1 = str1.length(); int l2 = str2.length(); // iterate and mark the frequencies of // all characters in str1 for (int i = 0; i < l1; i++) freq[str1[i] - 'a'] += 1; for (int i = 0; i < l2; i++) freq2[str2[i] - 'a'] += 1; int count = INT_MAX; // find the minimum frequency of // every character in str1 for (int i = 0; i < l2; i++) { if(freq2[str2[i]-'a']!=0) count = min(count, freq[str2[i] - 'a']/freq2[str2[i]-'a']); } return count;} // Driver Codeint main(){ string str1 = \"foreeksgekseg\"; string str2 = \"geeks\"; cout << findNumberOfTimes(str1, str2) << endl; return 0;}",
"e": 27035,
"s": 26016,
"text": null
},
{
"code": "// Java program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once class GFG { // Function to find the number of str2// that can be formed using characters of str1 static int findNumberOfTimes(String str1, String str2) { int freq[] = new int[26]; int freq2[] = new int[26]; int l1 = str1.length(); // iterate and mark the frequencies of // all characters in str1 for (int i = 0; i < l1; i++) { freq[str1.charAt(i) - 'a'] += 1; } int l2 = str2.length(); for (int i = 0; i < l2; i++) { freq2[str2.charAt(i) - 'a'] += 1; } int count = Integer.MAX_VALUE; // find the minimum frequency of // every character in str1 for (int i = 0; i < l2; i++) { if(freq2[str2.charAt(i)-'a']!=0) count = Math.min(count, freq[str2.charAt(i) - 'a']/freq2[str2.charAt(i)-'a']); } return count; } public static void main(String[] args) { String str1 = \"foreeksgekseg\"; String str2 =\"geeks\"; System.out.println(findNumberOfTimes(str1, str2)); }}/* This code is contributed by 29AjayKumar*/",
"e": 28311,
"s": 27035,
"text": null
},
{
"code": "# Python3 program to print the number of# times str2 can be formed from str1 using# the characters of str1 only onceimport sys # Function to find the number of str2# that can be formed using characters of str1def findNumberOfTimes(str1, str2): freq = [0] * 26 l1 = len(str1) freq2= [0] * 26 l2 = len(str2) # iterate and mark the frequencies # of all characters in str1 for i in range(l1): freq[ord(str1[i]) - ord(\"a\")] += 1 for i in range(l2): freq2[ord(str2[i]) - ord(\"a\")] += 1 count = sys.maxsize # find the minimum frequency of # every character in str1 for i in range(l2): count = min(count, freq[ord(str2[i]) - ord('a')]/freq2[ord(str2[i])-ord('a')]) return count # Driver Codeif __name__ == '__main__': str1 = \"foreeksgekseg\" str2 = \"geeks\" print(findNumberOfTimes(str1, str2)) # This code is contributed by PrinciRaj1992",
"e": 29293,
"s": 28311,
"text": null
},
{
"code": "// C# program to print the number of// times str2 can be formed from str1// using the characters of str1 only onceusing System; class GFG { // Function to find the number of // str2 that can be formed using // characters of str1 static int findNumberOfTimes(String str1, String str2) { int[] freq = new int[26]; int l1 = str1.Length; int[] freq2 = new int[26]; int l2 = str2.Length; // iterate and mark the frequencies // of all characters in str1 for (int i = 0; i < l1; i++) { freq[str1[i] - 'a'] += 1; } for (int i = 0; i < l2; i++) { freq2[str2[i] - 'a'] += 1; } int count = int.MaxValue; // find the minimum frequency of // every character in str1 for (int i = 0; i < l2; i++) { if (freq2[str2[i] - 'a'] != 0) count = Math.Min( count, freq[str2[i] - 'a'] / freq2[str2[i] - 'a']); } return count; } // Driver Code public static void Main() { String str1 = \"foreeksgekseg\"; String str2 = \"geeks\"; Console.Write(findNumberOfTimes(str1, str2)); }} // This code is contributed by 29AjayKumar",
"e": 30574,
"s": 29293,
"text": null
},
{
"code": "<?php// PHP program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once // Function to find the number of str2// that can be formed using characters of str1function findNumberOfTimes($str1, $str2){ $freq = array_fill(0, 26, NULL); $l1 = strlen($str1); $freq2 = array_fill(0, 26, NULL); $l2 = strlen($str2); // iterate and mark the frequencies // of all characters in str1 for ($i = 0; $i < $l1; $i++) $freq[ord($str1[$i]) - ord('a')] += 1; for ($i = 0; $i < $l2; $i++) $freq2[ord($str2[$i]) - ord('a')] += 1; $count = PHP_INT_MAX; // find the minimum frequency of // every character in str1 for ($i = 0; $i < $l2; $i++) $count = min($count, $freq[ord($str2[$i]) - ord('a')]/$freq2[ord($str2[$i]) - ord('a')]); return $count;} // Driver Code$str1 = \"foreeksgekseg\";$str2 = \"geeks\"; echo findNumberOfTimes($str1, $str2) . \"\\n\"; // This code is contributed by ita_c?>",
"e": 31634,
"s": 30574,
"text": null
},
{
"code": "<script>// Javascript program to print the number of times// str2 can be formed from str1 using the// characters of str1 only once // Function to find the number of str2 // that can be formed using characters of str1 function findNumberOfTimes(str1, str2) { let freq = new Array(26); let freq2 = new Array(26); for(let i = 0; i < 26; i++) { freq[i] = 0; freq2[i] = 0; } let l1 = str1.length; // iterate and mark the frequencies of // all characters in str1 for (let i = 0; i < l1; i++) { freq[str1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } let l2 = str2.length; for (let i = 0; i < l2; i++) { freq2[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; } let count = Number.MAX_VALUE; // find the minimum frequency of // every character in str1 for (let i = 0; i < l2; i++) { if(freq2[str2[i].charCodeAt(0)-'a'.charCodeAt(0)]!=0) count = Math.min(count, freq[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)]/freq2[str2[i].charCodeAt(0)-'a'.charCodeAt(0)]); } return count; } let str1 = \"foreeksgekseg\"; let str2 =\"geeks\"; document.write(findNumberOfTimes(str1, str2)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 33070,
"s": 31634,
"text": null
},
{
"code": null,
"e": 33072,
"s": 33070,
"text": "2"
},
{
"code": null,
"e": 33179,
"s": 33072,
"text": "Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively. Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33263,
"s": 33179,
"text": "Case: Using STL Maps with both uppercase and lowercase characters in str1 and str2."
},
{
"code": null,
"e": 33324,
"s": 33263,
"text": "Approach: The operation is similar to the normal hash-array."
},
{
"code": null,
"e": 33804,
"s": 33324,
"text": "Here, the order does not matter. We just need to check if there are sufficient words in str1 to make str2. Traverse both strings str1 and str2 to store characters as key and their frequencies as value in maps freq1 and freq2. Divide the frequencies stored in map freq1 with frequencies that have a matching key in map freq2. This will give us the maximum number of cycles of str2 that can be formed. Finally return minimum frequency from map freq1 which will be the final answer."
},
{
"code": null,
"e": 33810,
"s": 33804,
"text": "C++14"
},
{
"code": null,
"e": 33821,
"s": 33810,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int countSubStr(char* str,char* substr){ unordered_map<char,int>freq1; unordered_map<char,int>freq2; int i,mn=INT_MAX; int l1=strlen(str); int l2=strlen(substr); for(i=0;i<l1;i++) freq1[str[i]]++; for(i=0;i<l2;i++) freq2[substr[i]]++; for(auto x:freq2) mn=min(mn,freq1[x.first]/x.second); return mn;} int main(){ char str1[]= \"arajjhupoot\"; char str2[]=\"rajput\"; cout<<countSubStr(str1,str2); return 0;}",
"e": 34338,
"s": 33821,
"text": null
},
{
"code": "<script>function countSubStr(str,substr){ let freq1 = new Map(); let freq2 = new Map(); let i,mn=Number.MAX_VALUE; let l1 = str.length; let l2 = substr.length; for(i = 0; i < l1; i++){ if(freq1.has(str[i]) == true){ freq1.set(str[i], freq1.get(str[i]) + 1); } else{ freq1.set(str[i], 1); } } for(i = 0; i < l2; i++){ if(freq2.has(substr[i]) == true){ freq2.set(substr[i], freq1.get(str[i]) + 1); } else{ freq2.set(substr[i], 1); } } for(let [x, y] of freq2) mn = Math.min(mn,Math.floor(freq1.get(x)/y)); return mn;} // driver codelet str1 = \"arajjhupoot\";let str2 =\"rajput\";document.write(countSubStr(str1,str2)); // This code is contributed by shinjanpatra </script>",
"e": 35165,
"s": 34338,
"text": null
},
{
"code": null,
"e": 35249,
"s": 35165,
"text": "Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively"
},
{
"code": null,
"e": 35385,
"s": 35249,
"text": "Auxiliary Space: O(1) since the total number of distinct characters in both lowercase and uppercase English alphabets is 52 (Constant)."
},
{
"code": null,
"e": 35397,
"s": 35385,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35411,
"s": 35397,
"text": "princiraj1992"
},
{
"code": null,
"e": 35417,
"s": 35411,
"text": "ukasp"
},
{
"code": null,
"e": 35428,
"s": 35417,
"text": "nidhi_biet"
},
{
"code": null,
"e": 35437,
"s": 35428,
"text": "jyoti369"
},
{
"code": null,
"e": 35458,
"s": 35437,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35470,
"s": 35458,
"text": "prophet1999"
},
{
"code": null,
"e": 35483,
"s": 35470,
"text": "shinjanpatra"
},
{
"code": null,
"e": 35507,
"s": 35483,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 35512,
"s": 35507,
"text": "Hash"
},
{
"code": null,
"e": 35517,
"s": 35512,
"text": "Hash"
},
{
"code": null,
"e": 35525,
"s": 35517,
"text": "Strings"
},
{
"code": null,
"e": 35530,
"s": 35525,
"text": "Hash"
},
{
"code": null,
"e": 35538,
"s": 35530,
"text": "Strings"
},
{
"code": null,
"e": 35636,
"s": 35538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35645,
"s": 35636,
"text": "Comments"
},
{
"code": null,
"e": 35658,
"s": 35645,
"text": "Old Comments"
},
{
"code": null,
"e": 35698,
"s": 35658,
"text": "Rearrange an array such that arr[i] = i"
},
{
"code": null,
"e": 35727,
"s": 35698,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 35743,
"s": 35727,
"text": "Hashing in Java"
},
{
"code": null,
"e": 35807,
"s": 35743,
"text": "What are Hash Functions and How to choose a good Hash Function?"
},
{
"code": null,
"e": 35848,
"s": 35807,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 35873,
"s": 35848,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35919,
"s": 35873,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35953,
"s": 35919,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 36013,
"s": 35953,
"text": "Write a program to print all permutations of a given string"
}
] |
Ionic - Cordova Geolocation | This plugin is used for adding a geolocation plugin to the Ionic app.
There is a simple way to use the geolocation plugin. We need to install this plugin from the command prompt window.
C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-geolocation
The following controller code is using two methods. The first one is the getCurrentPosition method and it will show us the current latitude and longitude of the user’s device. The second one is the watchCurrentPosition method that will return the current position of the device when the position is changed.
.controller('MyCtrl', function($scope, $cordovaGeolocation) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long)
}, function(err) {
console.log(err)
});
var watchOptions = {timeout : 3000, enableHighAccuracy: false};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
console.log(err)
},
function(position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + '' + long)
}
);
watch.clearWatch();
})
You might have also noticed the posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results, but sometimes it can lead to some errors. There is also a maximumAge option that can be used to show how an old position is accepted. It is using milliseconds, the same as timeout option.
When we start our app and open the console, it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change.
16 Lectures
2.5 hours
Frahaan Hussain
185 Lectures
46.5 hours
Nikhil Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2533,
"s": 2463,
"text": "This plugin is used for adding a geolocation plugin to the Ionic app."
},
{
"code": null,
"e": 2649,
"s": 2533,
"text": "There is a simple way to use the geolocation plugin. We need to install this plugin from the command prompt window."
},
{
"code": null,
"e": 2728,
"s": 2649,
"text": "C:\\Users\\Username\\Desktop\\MyApp>cordova plugin add cordova-plugin-geolocation\n"
},
{
"code": null,
"e": 3036,
"s": 2728,
"text": "The following controller code is using two methods. The first one is the getCurrentPosition method and it will show us the current latitude and longitude of the user’s device. The second one is the watchCurrentPosition method that will return the current position of the device when the position is changed."
},
{
"code": null,
"e": 3845,
"s": 3036,
"text": ".controller('MyCtrl', function($scope, $cordovaGeolocation) {\n var posOptions = {timeout: 10000, enableHighAccuracy: false};\n $cordovaGeolocation\n .getCurrentPosition(posOptions)\n\t\n .then(function (position) {\n var lat = position.coords.latitude\n var long = position.coords.longitude\n console.log(lat + ' ' + long)\n }, function(err) {\n console.log(err)\n });\n\n var watchOptions = {timeout : 3000, enableHighAccuracy: false};\n var watch = $cordovaGeolocation.watchPosition(watchOptions);\n\t\n watch.then(\n null,\n\t\t\n function(err) {\n console.log(err)\n },\n\t function(position) {\n var lat = position.coords.latitude\n var long = position.coords.longitude\n console.log(lat + '' + long)\n }\n );\n\n watch.clearWatch();\n})"
},
{
"code": null,
"e": 4292,
"s": 3845,
"text": "You might have also noticed the posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results, but sometimes it can lead to some errors. There is also a maximumAge option that can be used to show how an old position is accepted. It is using milliseconds, the same as timeout option."
},
{
"code": null,
"e": 4457,
"s": 4292,
"text": "When we start our app and open the console, it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change."
},
{
"code": null,
"e": 4492,
"s": 4457,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4509,
"s": 4492,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4546,
"s": 4509,
"text": "\n 185 Lectures \n 46.5 hours \n"
},
{
"code": null,
"e": 4562,
"s": 4546,
"text": " Nikhil Agarwal"
},
{
"code": null,
"e": 4569,
"s": 4562,
"text": " Print"
},
{
"code": null,
"e": 4580,
"s": 4569,
"text": " Add Notes"
}
] |
Snowflake and Dask. How to efficiently load data from... | by Hugo Shi | Towards Data Science | Snowflake is the most popular data warehouse among our Saturn users. This article will cover efficient ways to load Snowflake data into Dask so you can do non-sql operations (think machine learning) at scale. Disclaimer: I’m the CTO of Saturn Cloud — we focus on enterprise Dask.
First, some basics, the standard way to load Snowflake data into Pandas:
import snowflake.connectorimport pandas as pdctx = snowflake.connector.connect( user='YOUR_USER', password='YOUR_PASSWORD', account='YOUR_ACCOUNT')query = "SELECT * FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.CUSTOMER"pd.read_sql(query, ctx)
Snowflake recently introduced a much faster method for this operation, fetch_pandas_all, and fetch_pandas_batches which leverages Arrow
cur = ctx.cursor()cur.execute(query)df = cur.fetch_pandas_all()
fetch_pandas_batches returns an iterator, but since we’re going to focus on loading this into a distributed dataframe (pulling from multiple machines), we’re going to setup our query to shard the data, and use fetch_pandas_all on our workers.
It can be very tempting to rip all the data out of snowflake so that you can work with it in Dask. That definitely works, however, snowflake is going to be much faster at applying sql-like operations to the data. Snowflake stores the data and has highly optimized routines to get every ounce of performance out of your query. These examples will pretend like we’re loading the entire data into Dask — in your case, you will probably have some SQL query, which performs the sql-like transformations you care about, and you’ll be loading the result set into Dask, for the things that Dask is good at (possibly some types of feature engineering, and machine learning). Saturn Cloud has native integration with Dask and Snowflake, so check that out if this is interesting to you.
You can think about a Dask dataframe as a giant Pandas dataframe that has been chopped up and scattered across a bunch of computers. When we are loading data from Snowflake (assuming that the data is large), it’s not efficient to load all the data on one machine, and then scatter that out to your cluster. We are going to focus on having all machines in your Dask cluster load a partition (a small slice) of your data.
We need a way to split the data into little partitions so that we can load it into the cluster. Data in SQL doesn’t necessarily have any natural ordering. You can’t just say that you’re going to throw the first 10k rows into one partition, and the second 10k rows into another partition. That partitioning has to be based on a column of the data. For example, you can partition the data by a date field. Or you can create a row number by adding an identity column into your Snowflake table.
Once you’ve decided what column you want to partition your data on, it’s important to set up data clustering on the snowflake side. Every single worker is going to ask for a small slice of the data. Something like
select * from table where id < 20000 and id >= 10000
If you don’t set up data clustering, every single query is going to trigger a full table scan on the resulting database (I’m probably overstating the problem, but without data clustering, performance here can be quite bad)
We aren’t going to use read_sql_table from the dask library here. I prefer to have more control over how we load the data from Snowflake, and we want to call fetch_pandas_all, which is a Snowflake specific function, and therefore not supported with read_sql_table
import snowflake.connectorfrom dask.dataframe import from_delayedfrom dask.distributed import delayed@delayeddef load(connection_info, query, start, end): conn = snowflake.connector.connect(**connection_info) cur = conn.cursor() cur.execute(query, start, end) return cur.fetch_pandas_all()ddf = from_delayed(*[load(connection_info, query, st, ed) for st, ed in partitions])ddf.persist()
This code assumes that partitions is a list of starting/ending partitions, for example:
partitions = [(0, 10000), (10000, 20000), ...]
delayed is a decorator that turns a Python function into a function suitable for running on the dask cluster. When you execute it, instead of executing, it returns a delayed result that represents what the return value of the function will be. from_delayed takes a list of these delayed objects, and concatenates them into a giant dataframe.
This is advanced concepts, but I urge you to read this section, it can save you alot of time and headache from running out of memory on your workstation. Don’t assume that just because Snowflake says that a dataset is 20GB that it will be 20GB when you load it into pandas. The pandas in memory representation is always much larger, though you can get better by being good about data types.
df.memory_usage(deep=True) is a good way to understand how much memory each column is using. This can help you understand what benefit you are getting from converting your data to appropriate DTypes.
Python strings have roughly 40 bytes of overhead. That doesn’t sound like a lot, but if you have a billion strings, it can add up quickly. The new StringDType can help here.
df['column'] = df['column'].astype(pd.StringDType())
Many string and numerical fields are actually categorical. Take a column named “Household Income”. Instead of a numerical value, you usually get data in bands, like “0-$40,000” or “more than $100,000”.
As a general guideline, I usually look for columns where the ratio of the number of unique values, to the number of rows is less than 1%.
In pandas, this is the relevant code.
df['column'] = df['column'].astype("category")
However, I’m assuming that loading the entire column out of snowflake in order to compute the categorical dtype is not feasible. I recommend the following type of query to identify which columns are good candidates for categorical dtypes:
select count(distinct(col1)), count(distinct(col2)), ... from table
You can compare that result to the number of rows in your table in order to figure out which columns should be categorical.
Then to figure out the unique values
select distinct(col1) from table
Assuming you’ve done some of the memory optimizations listed above, and you’ve figured out some fields that should be converted to StringDType, some that should be categoricals. And assuming that you have a dictionary called dtypes which is a mapping of column names, to the dtype you wish to coerce the result to.
import snowflake.connectorfrom dask.dataframe import from_delayedfrom dask.distributed import delayed@delayeddef load(connection_info, query, start, end, dtypes): conn = snowflake.connector.connect(**connection_info) cur = conn.cursor() cur.execute(query, start, end) return cur.fetch_pandas_all().astype(dtypes)ddf = from_delayed(*[load(connection_info, query, st, ed) for st, ed in partitions])ddf.persist()
Thanks for reading. If you’re interested in using Dask with Snowflake, then I recommend you check out Saturn Cloud. | [
{
"code": null,
"e": 452,
"s": 172,
"text": "Snowflake is the most popular data warehouse among our Saturn users. This article will cover efficient ways to load Snowflake data into Dask so you can do non-sql operations (think machine learning) at scale. Disclaimer: I’m the CTO of Saturn Cloud — we focus on enterprise Dask."
},
{
"code": null,
"e": 525,
"s": 452,
"text": "First, some basics, the standard way to load Snowflake data into Pandas:"
},
{
"code": null,
"e": 768,
"s": 525,
"text": "import snowflake.connectorimport pandas as pdctx = snowflake.connector.connect( user='YOUR_USER', password='YOUR_PASSWORD', account='YOUR_ACCOUNT')query = \"SELECT * FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.CUSTOMER\"pd.read_sql(query, ctx)"
},
{
"code": null,
"e": 904,
"s": 768,
"text": "Snowflake recently introduced a much faster method for this operation, fetch_pandas_all, and fetch_pandas_batches which leverages Arrow"
},
{
"code": null,
"e": 968,
"s": 904,
"text": "cur = ctx.cursor()cur.execute(query)df = cur.fetch_pandas_all()"
},
{
"code": null,
"e": 1211,
"s": 968,
"text": "fetch_pandas_batches returns an iterator, but since we’re going to focus on loading this into a distributed dataframe (pulling from multiple machines), we’re going to setup our query to shard the data, and use fetch_pandas_all on our workers."
},
{
"code": null,
"e": 1987,
"s": 1211,
"text": "It can be very tempting to rip all the data out of snowflake so that you can work with it in Dask. That definitely works, however, snowflake is going to be much faster at applying sql-like operations to the data. Snowflake stores the data and has highly optimized routines to get every ounce of performance out of your query. These examples will pretend like we’re loading the entire data into Dask — in your case, you will probably have some SQL query, which performs the sql-like transformations you care about, and you’ll be loading the result set into Dask, for the things that Dask is good at (possibly some types of feature engineering, and machine learning). Saturn Cloud has native integration with Dask and Snowflake, so check that out if this is interesting to you."
},
{
"code": null,
"e": 2407,
"s": 1987,
"text": "You can think about a Dask dataframe as a giant Pandas dataframe that has been chopped up and scattered across a bunch of computers. When we are loading data from Snowflake (assuming that the data is large), it’s not efficient to load all the data on one machine, and then scatter that out to your cluster. We are going to focus on having all machines in your Dask cluster load a partition (a small slice) of your data."
},
{
"code": null,
"e": 2898,
"s": 2407,
"text": "We need a way to split the data into little partitions so that we can load it into the cluster. Data in SQL doesn’t necessarily have any natural ordering. You can’t just say that you’re going to throw the first 10k rows into one partition, and the second 10k rows into another partition. That partitioning has to be based on a column of the data. For example, you can partition the data by a date field. Or you can create a row number by adding an identity column into your Snowflake table."
},
{
"code": null,
"e": 3112,
"s": 2898,
"text": "Once you’ve decided what column you want to partition your data on, it’s important to set up data clustering on the snowflake side. Every single worker is going to ask for a small slice of the data. Something like"
},
{
"code": null,
"e": 3165,
"s": 3112,
"text": "select * from table where id < 20000 and id >= 10000"
},
{
"code": null,
"e": 3388,
"s": 3165,
"text": "If you don’t set up data clustering, every single query is going to trigger a full table scan on the resulting database (I’m probably overstating the problem, but without data clustering, performance here can be quite bad)"
},
{
"code": null,
"e": 3652,
"s": 3388,
"text": "We aren’t going to use read_sql_table from the dask library here. I prefer to have more control over how we load the data from Snowflake, and we want to call fetch_pandas_all, which is a Snowflake specific function, and therefore not supported with read_sql_table"
},
{
"code": null,
"e": 4051,
"s": 3652,
"text": "import snowflake.connectorfrom dask.dataframe import from_delayedfrom dask.distributed import delayed@delayeddef load(connection_info, query, start, end): conn = snowflake.connector.connect(**connection_info) cur = conn.cursor() cur.execute(query, start, end) return cur.fetch_pandas_all()ddf = from_delayed(*[load(connection_info, query, st, ed) for st, ed in partitions])ddf.persist()"
},
{
"code": null,
"e": 4139,
"s": 4051,
"text": "This code assumes that partitions is a list of starting/ending partitions, for example:"
},
{
"code": null,
"e": 4186,
"s": 4139,
"text": "partitions = [(0, 10000), (10000, 20000), ...]"
},
{
"code": null,
"e": 4528,
"s": 4186,
"text": "delayed is a decorator that turns a Python function into a function suitable for running on the dask cluster. When you execute it, instead of executing, it returns a delayed result that represents what the return value of the function will be. from_delayed takes a list of these delayed objects, and concatenates them into a giant dataframe."
},
{
"code": null,
"e": 4919,
"s": 4528,
"text": "This is advanced concepts, but I urge you to read this section, it can save you alot of time and headache from running out of memory on your workstation. Don’t assume that just because Snowflake says that a dataset is 20GB that it will be 20GB when you load it into pandas. The pandas in memory representation is always much larger, though you can get better by being good about data types."
},
{
"code": null,
"e": 5119,
"s": 4919,
"text": "df.memory_usage(deep=True) is a good way to understand how much memory each column is using. This can help you understand what benefit you are getting from converting your data to appropriate DTypes."
},
{
"code": null,
"e": 5293,
"s": 5119,
"text": "Python strings have roughly 40 bytes of overhead. That doesn’t sound like a lot, but if you have a billion strings, it can add up quickly. The new StringDType can help here."
},
{
"code": null,
"e": 5346,
"s": 5293,
"text": "df['column'] = df['column'].astype(pd.StringDType())"
},
{
"code": null,
"e": 5548,
"s": 5346,
"text": "Many string and numerical fields are actually categorical. Take a column named “Household Income”. Instead of a numerical value, you usually get data in bands, like “0-$40,000” or “more than $100,000”."
},
{
"code": null,
"e": 5686,
"s": 5548,
"text": "As a general guideline, I usually look for columns where the ratio of the number of unique values, to the number of rows is less than 1%."
},
{
"code": null,
"e": 5724,
"s": 5686,
"text": "In pandas, this is the relevant code."
},
{
"code": null,
"e": 5771,
"s": 5724,
"text": "df['column'] = df['column'].astype(\"category\")"
},
{
"code": null,
"e": 6010,
"s": 5771,
"text": "However, I’m assuming that loading the entire column out of snowflake in order to compute the categorical dtype is not feasible. I recommend the following type of query to identify which columns are good candidates for categorical dtypes:"
},
{
"code": null,
"e": 6082,
"s": 6010,
"text": "select count(distinct(col1)), count(distinct(col2)), ... from table"
},
{
"code": null,
"e": 6206,
"s": 6082,
"text": "You can compare that result to the number of rows in your table in order to figure out which columns should be categorical."
},
{
"code": null,
"e": 6243,
"s": 6206,
"text": "Then to figure out the unique values"
},
{
"code": null,
"e": 6276,
"s": 6243,
"text": "select distinct(col1) from table"
},
{
"code": null,
"e": 6591,
"s": 6276,
"text": "Assuming you’ve done some of the memory optimizations listed above, and you’ve figured out some fields that should be converted to StringDType, some that should be categoricals. And assuming that you have a dictionary called dtypes which is a mapping of column names, to the dtype you wish to coerce the result to."
},
{
"code": null,
"e": 7013,
"s": 6591,
"text": "import snowflake.connectorfrom dask.dataframe import from_delayedfrom dask.distributed import delayed@delayeddef load(connection_info, query, start, end, dtypes): conn = snowflake.connector.connect(**connection_info) cur = conn.cursor() cur.execute(query, start, end) return cur.fetch_pandas_all().astype(dtypes)ddf = from_delayed(*[load(connection_info, query, st, ed) for st, ed in partitions])ddf.persist()"
}
] |
Efficiently check whether n is a multiple of 4 or not - GeeksforGeeks | 28 Apr, 2021
Given a number n. The problem is to efficiently check whether n is a multiple of 4 or not without using arithmetic operators. Examples:
Input : 16
Output : Yes
Input : 14
Output : No
Approach: A multiple of 4 always has 00 as its last two digits in its binary representation. We have to check whether the last two digits of n are unset or not.How to check whether the last two bits are unset or not. If n & 3 == 0, then the last two bits are unset, else either both or one of them are set.
C++
Java
Python 3
C#
PHP
Javascript
// C++ implementation to efficiently check whether n// is a multiple of 4 or not#include <bits/stdc++.h>using namespace std; // function to check whether 'n' is// a multiple of 4 or notstring isAMultipleOf4(int n){ // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return "Yes"; // else 'n' is not a multiple of 4 return "No";} // Driver program to test aboveint main(){ int n = 16; cout << isAMultipleOf4(n); return 0;}
// Java implementation to efficiently check// whether n is a multiple of 4 or not class GFG { // method to check whether 'n' is // a multiple of 4 or not static boolean isAMultipleOf4(int n) { // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return true; // else 'n' is not a multiple of 4 return false; } // Driver method public static void main(String[] args) { int n = 16; System.out.println(isAMultipleOf4(n) ? "Yes" : "No"); }}
# Python 3 implementation to# efficiently check whether n# is a multiple of 4 or not # function to check whether 'n'# is a multiple of 4 or notdef isAMultipleOf4(n): # if true, then 'n' is # a multiple of 4 if ((n & 3) == 0): return "Yes" # else 'n' is not a # multiple of 4 return "No" # Driver Codeif __name__ == "__main__": n = 16 print (isAMultipleOf4(n)) # This code is contributed# by ChitraNayal
// C# implementation to efficiently check// whether n is a multiple of 4 or notusing System; class GFG { // method to check whether 'n' is // a multiple of 4 or not static bool isAMultipleOf4(int n) { // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return true; // else 'n' is not a multiple of 4 return false; } // Driver method public static void Main() { int n = 16; Console.WriteLine(isAMultipleOf4(n) ? "Yes" : "No"); }} // This code is contributed by vt_m.
<?php// PHP implementation to// efficiently check whether n// is a multiple of 4 or not // function to check whether 'n' is// a multiple of 4 or notfunction isAMultipleOf4($n){ // if true, then 'n' // is a multiple of 4 if (($n & 3) == 0) return "Yes"; // else 'n' is not // a multiple of 4 return "No";} // Driver Code $n = 16; echo isAMultipleOf4($n); // This code is contributed by anuj_67.?>
<script> // Javascript implementation to efficiently check// whether n is a multiple of 4 or not // method to check whether 'n' is // a multiple of 4 or not function isAMultipleOf4(n) { // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return true; // else 'n' is not a multiple of 4 return false; } // Driver method let n = 16; document.write(isAMultipleOf4(n) ? "Yes" : "No"); //This code is contributed by rag2127 </script>
Output:
Yes
Can we generalize above solution? Similarly we can check for other powers of 2. For example, a number n would be multiple of 8 if n & 7 is 0. In general we can say.
// x must be a power of 2 for below
// logic to work
if (n & (x -1) == 0)
n is a multiple of x
Else
n is NOT a multiple of x
https://youtu.be/ke
-Mai2m6Cg This article is contributed by Ayush Jauhri. 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.
vt_m
ukasp
shubhamjaiswal16
rag2127
divisibility
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Binary representation of a given number
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
Find the element that appears once
Bits manipulation (Important tactics)
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
C++ bitset and its application | [
{
"code": null,
"e": 24961,
"s": 24933,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 25099,
"s": 24961,
"text": "Given a number n. The problem is to efficiently check whether n is a multiple of 4 or not without using arithmetic operators. Examples: "
},
{
"code": null,
"e": 25147,
"s": 25099,
"text": "Input : 16\nOutput : Yes\n\nInput : 14\nOutput : No"
},
{
"code": null,
"e": 25458,
"s": 25149,
"text": "Approach: A multiple of 4 always has 00 as its last two digits in its binary representation. We have to check whether the last two digits of n are unset or not.How to check whether the last two bits are unset or not. If n & 3 == 0, then the last two bits are unset, else either both or one of them are set. "
},
{
"code": null,
"e": 25462,
"s": 25458,
"text": "C++"
},
{
"code": null,
"e": 25467,
"s": 25462,
"text": "Java"
},
{
"code": null,
"e": 25476,
"s": 25467,
"text": "Python 3"
},
{
"code": null,
"e": 25479,
"s": 25476,
"text": "C#"
},
{
"code": null,
"e": 25483,
"s": 25479,
"text": "PHP"
},
{
"code": null,
"e": 25494,
"s": 25483,
"text": "Javascript"
},
{
"code": "// C++ implementation to efficiently check whether n// is a multiple of 4 or not#include <bits/stdc++.h>using namespace std; // function to check whether 'n' is// a multiple of 4 or notstring isAMultipleOf4(int n){ // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return \"Yes\"; // else 'n' is not a multiple of 4 return \"No\";} // Driver program to test aboveint main(){ int n = 16; cout << isAMultipleOf4(n); return 0;}",
"e": 25955,
"s": 25494,
"text": null
},
{
"code": "// Java implementation to efficiently check// whether n is a multiple of 4 or not class GFG { // method to check whether 'n' is // a multiple of 4 or not static boolean isAMultipleOf4(int n) { // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return true; // else 'n' is not a multiple of 4 return false; } // Driver method public static void main(String[] args) { int n = 16; System.out.println(isAMultipleOf4(n) ? \"Yes\" : \"No\"); }}",
"e": 26479,
"s": 25955,
"text": null
},
{
"code": "# Python 3 implementation to# efficiently check whether n# is a multiple of 4 or not # function to check whether 'n'# is a multiple of 4 or notdef isAMultipleOf4(n): # if true, then 'n' is # a multiple of 4 if ((n & 3) == 0): return \"Yes\" # else 'n' is not a # multiple of 4 return \"No\" # Driver Codeif __name__ == \"__main__\": n = 16 print (isAMultipleOf4(n)) # This code is contributed# by ChitraNayal",
"e": 26916,
"s": 26479,
"text": null
},
{
"code": "// C# implementation to efficiently check// whether n is a multiple of 4 or notusing System; class GFG { // method to check whether 'n' is // a multiple of 4 or not static bool isAMultipleOf4(int n) { // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return true; // else 'n' is not a multiple of 4 return false; } // Driver method public static void Main() { int n = 16; Console.WriteLine(isAMultipleOf4(n) ? \"Yes\" : \"No\"); }} // This code is contributed by vt_m.",
"e": 27476,
"s": 26916,
"text": null
},
{
"code": "<?php// PHP implementation to// efficiently check whether n// is a multiple of 4 or not // function to check whether 'n' is// a multiple of 4 or notfunction isAMultipleOf4($n){ // if true, then 'n' // is a multiple of 4 if (($n & 3) == 0) return \"Yes\"; // else 'n' is not // a multiple of 4 return \"No\";} // Driver Code $n = 16; echo isAMultipleOf4($n); // This code is contributed by anuj_67.?>",
"e": 27917,
"s": 27476,
"text": null
},
{
"code": "<script> // Javascript implementation to efficiently check// whether n is a multiple of 4 or not // method to check whether 'n' is // a multiple of 4 or not function isAMultipleOf4(n) { // if true, then 'n' is a multiple of 4 if ((n & 3) == 0) return true; // else 'n' is not a multiple of 4 return false; } // Driver method let n = 16; document.write(isAMultipleOf4(n) ? \"Yes\" : \"No\"); //This code is contributed by rag2127 </script>",
"e": 28440,
"s": 27917,
"text": null
},
{
"code": null,
"e": 28450,
"s": 28440,
"text": "Output: "
},
{
"code": null,
"e": 28454,
"s": 28450,
"text": "Yes"
},
{
"code": null,
"e": 28621,
"s": 28454,
"text": "Can we generalize above solution? Similarly we can check for other powers of 2. For example, a number n would be multiple of 8 if n & 7 is 0. In general we can say. "
},
{
"code": null,
"e": 28752,
"s": 28621,
"text": "// x must be a power of 2 for below\n// logic to work\nif (n & (x -1) == 0)\n n is a multiple of x\nElse\n n is NOT a multiple of x"
},
{
"code": null,
"e": 28774,
"s": 28754,
"text": "https://youtu.be/ke"
},
{
"code": null,
"e": 29209,
"s": 28774,
"text": "-Mai2m6Cg This article is contributed by Ayush Jauhri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29214,
"s": 29209,
"text": "vt_m"
},
{
"code": null,
"e": 29220,
"s": 29214,
"text": "ukasp"
},
{
"code": null,
"e": 29237,
"s": 29220,
"text": "shubhamjaiswal16"
},
{
"code": null,
"e": 29245,
"s": 29237,
"text": "rag2127"
},
{
"code": null,
"e": 29258,
"s": 29245,
"text": "divisibility"
},
{
"code": null,
"e": 29268,
"s": 29258,
"text": "Bit Magic"
},
{
"code": null,
"e": 29278,
"s": 29268,
"text": "Bit Magic"
},
{
"code": null,
"e": 29376,
"s": 29278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29385,
"s": 29376,
"text": "Comments"
},
{
"code": null,
"e": 29398,
"s": 29385,
"text": "Old Comments"
},
{
"code": null,
"e": 29444,
"s": 29398,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 29474,
"s": 29444,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 29514,
"s": 29474,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 29565,
"s": 29514,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 29608,
"s": 29565,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 29643,
"s": 29608,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 29681,
"s": 29643,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 29732,
"s": 29681,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 29748,
"s": 29732,
"text": "Bit Fields in C"
}
] |
Word Distance between Word Embeddings | by Edward Ma | Towards Data Science | Word Mover’s Distance (WMD) is proposed fro distance measurement between 2 documents (or sentences). It leverages Word Embeddings power to overcome those basic distance measurement limitations.
WMD[1] was introduced by Kusner et al. in 2015. Instead of using Euclidean Distance and other bag-of-words based distance measurement, they proposed to use word embeddings to calculate the similarities. To be precise, it uses normalized Bag-of-Words and Word Embeddings to calculate the distance between documents.
After reading this article, you will understand:
Earth Mover Distance (EMD)
Word Mover’s Distance (WMD)
Relaxed Word Moving Distance (RWMD)
WMD Implementation
Take Away
Before introducing WMD, I have to share the idea of Earth Mover Distance (EMD) first because the core part of WMD is EMD.
EMD [2] solves transportation problem. For instance, we have m and n while m and n denote a set of suppliers and warehouses. The target is going to minimize transportation cost such that shipping all goods from m to n. Given that there are constraints:
Only allowing transport from m to n. Not allowing transport from n to m
Total number of sending cargoes cannot exceed total capacity of m
Total number of receiving cargoes cannot exceed total capacity of n
Maximum number of transportation is the minimum between total cargoes in m and total cargoes in n
The denotations are:
p: Set of origin
q: Set of destination
f(i,j): flow from i to j
m: Number of origin
n: Number of destination
w(i, j): Number of cargo transport from i to j
To optimal flow F, the linear formula is
In the previous blog, I shared how we can use simple way to find the “similarity” between two documents (or sentences). At that time, Euclidean Distance, Cosine Distance and Jaccard Similarity are introduced but it has some limitations. WMD is designed to overcome synonym problem.
The typical example is
Sentence 1: Obama speaks to the media in Illinois
Sentence 2: The president greets the press in Chicago
Except the stop words, there is no common words among two sentences but both of them are taking about same topic (at that time).
WMD use word embeddings to calculate the distance so that it can calculate even though there is no common word. The assumption is that similar words should have similar vectors.
First of all, lower case and removing stopwords is an essential step to reduce complexity and preventing misleading.
Sentence 1: obama speaks media illinois
Sentence 2: president greets press chicago
Retrieve vectors from any pre-trained word embeddings models. It can be GloVe, word2vec, fasttext or custom vectors. After that it using normalized bag-of-words (nBOW) to represent the weight or importance. It assumes that higher frequency implies that it is more important.
It allows transfer every word from sentence 1 to sentence 2 because algorithm does not know “obama” should transfer to “president”. At the end it will choose the minimum transportation cost to transport every word from sentence 1 to sentence 2.
The best average time of solving WMD is about O(p3 log p) while p is number of unique word. It is a little bit slow so there are two approaches to improve the reduce computation time. First one is Word Centroid Distance (WCD) which is summarizing the lower bound distance between. Second approach is Relaxed Word Moving Distance (RWMD) which is using the closet distance without considering there are multiple words transforming to single words.
Taking the previous sentence as an example. Assuming that shortest word in sentence of all word in sentence 1 is “president”, it will use summarize these score instead of pairing one by one. So that the time complexity reduce to O(p2).
By using gensim, we only need to provide two list of tokens then it will take the rest of calculation
subject_headline = news_headlines[0]subject_token = headline_tokens[0]print('Headline: ', subject_headline)print('=' * 50)print()for token, headline in zip(headline_tokens, news_headlines): print('-' * 50) print('Comparing to:', headline) distance = glove_model.wmdistance(subject_token, token) print('distance = %.4f' % distance)
Output
Headline: Elon Musk's Boring Co to build high-speed airport link in Chicago==================================================--------------------------------------------------Comparing to: Elon Musk's Boring Co to build high-speed airport link in Chicagodistance = 0.0000--------------------------------------------------Comparing to: Elon Musk's Boring Company to build high-speed Chicago airport linkdistance = 0.3589--------------------------------------------------Comparing to: Elon Musk’s Boring Company approved to build high-speed transit between downtown Chicago and O’Hare Airportdistance = 1.9456--------------------------------------------------Comparing to: Both apple and orange are fruitdistance = 5.4350
In gensim implementation, OOV will be removed so that it will not throw an exception or using random vector.
For source code, you may check out from my github repo.
The advantage of WMD are hyper-parameter free and overcoming synonym problem.
Same as those simple approaches, WMD does not consider ordering.
The time complexity is an issue. The original version is O(p3 log p) while the enhanced version is still O(p2).
Pre-train vectors may not apply to all scenario.
I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium Blog, LinkedIn or Github.
[1] Kusner Matt J., Sun Yu, Kolkin Nicholas I., Weinberger Kilian Q. From Word Embeedings To Document Distance. 2015. http://proceedings.mlr.press/v37/kusnerb15.pdf
[2] EMD Theory: https://en.wikipedia.org/wiki/Earth_mover%27s_distance | [
{
"code": null,
"e": 366,
"s": 172,
"text": "Word Mover’s Distance (WMD) is proposed fro distance measurement between 2 documents (or sentences). It leverages Word Embeddings power to overcome those basic distance measurement limitations."
},
{
"code": null,
"e": 681,
"s": 366,
"text": "WMD[1] was introduced by Kusner et al. in 2015. Instead of using Euclidean Distance and other bag-of-words based distance measurement, they proposed to use word embeddings to calculate the similarities. To be precise, it uses normalized Bag-of-Words and Word Embeddings to calculate the distance between documents."
},
{
"code": null,
"e": 730,
"s": 681,
"text": "After reading this article, you will understand:"
},
{
"code": null,
"e": 757,
"s": 730,
"text": "Earth Mover Distance (EMD)"
},
{
"code": null,
"e": 785,
"s": 757,
"text": "Word Mover’s Distance (WMD)"
},
{
"code": null,
"e": 821,
"s": 785,
"text": "Relaxed Word Moving Distance (RWMD)"
},
{
"code": null,
"e": 840,
"s": 821,
"text": "WMD Implementation"
},
{
"code": null,
"e": 850,
"s": 840,
"text": "Take Away"
},
{
"code": null,
"e": 972,
"s": 850,
"text": "Before introducing WMD, I have to share the idea of Earth Mover Distance (EMD) first because the core part of WMD is EMD."
},
{
"code": null,
"e": 1225,
"s": 972,
"text": "EMD [2] solves transportation problem. For instance, we have m and n while m and n denote a set of suppliers and warehouses. The target is going to minimize transportation cost such that shipping all goods from m to n. Given that there are constraints:"
},
{
"code": null,
"e": 1297,
"s": 1225,
"text": "Only allowing transport from m to n. Not allowing transport from n to m"
},
{
"code": null,
"e": 1363,
"s": 1297,
"text": "Total number of sending cargoes cannot exceed total capacity of m"
},
{
"code": null,
"e": 1431,
"s": 1363,
"text": "Total number of receiving cargoes cannot exceed total capacity of n"
},
{
"code": null,
"e": 1529,
"s": 1431,
"text": "Maximum number of transportation is the minimum between total cargoes in m and total cargoes in n"
},
{
"code": null,
"e": 1550,
"s": 1529,
"text": "The denotations are:"
},
{
"code": null,
"e": 1567,
"s": 1550,
"text": "p: Set of origin"
},
{
"code": null,
"e": 1589,
"s": 1567,
"text": "q: Set of destination"
},
{
"code": null,
"e": 1614,
"s": 1589,
"text": "f(i,j): flow from i to j"
},
{
"code": null,
"e": 1634,
"s": 1614,
"text": "m: Number of origin"
},
{
"code": null,
"e": 1659,
"s": 1634,
"text": "n: Number of destination"
},
{
"code": null,
"e": 1706,
"s": 1659,
"text": "w(i, j): Number of cargo transport from i to j"
},
{
"code": null,
"e": 1747,
"s": 1706,
"text": "To optimal flow F, the linear formula is"
},
{
"code": null,
"e": 2029,
"s": 1747,
"text": "In the previous blog, I shared how we can use simple way to find the “similarity” between two documents (or sentences). At that time, Euclidean Distance, Cosine Distance and Jaccard Similarity are introduced but it has some limitations. WMD is designed to overcome synonym problem."
},
{
"code": null,
"e": 2052,
"s": 2029,
"text": "The typical example is"
},
{
"code": null,
"e": 2102,
"s": 2052,
"text": "Sentence 1: Obama speaks to the media in Illinois"
},
{
"code": null,
"e": 2156,
"s": 2102,
"text": "Sentence 2: The president greets the press in Chicago"
},
{
"code": null,
"e": 2285,
"s": 2156,
"text": "Except the stop words, there is no common words among two sentences but both of them are taking about same topic (at that time)."
},
{
"code": null,
"e": 2463,
"s": 2285,
"text": "WMD use word embeddings to calculate the distance so that it can calculate even though there is no common word. The assumption is that similar words should have similar vectors."
},
{
"code": null,
"e": 2580,
"s": 2463,
"text": "First of all, lower case and removing stopwords is an essential step to reduce complexity and preventing misleading."
},
{
"code": null,
"e": 2620,
"s": 2580,
"text": "Sentence 1: obama speaks media illinois"
},
{
"code": null,
"e": 2663,
"s": 2620,
"text": "Sentence 2: president greets press chicago"
},
{
"code": null,
"e": 2938,
"s": 2663,
"text": "Retrieve vectors from any pre-trained word embeddings models. It can be GloVe, word2vec, fasttext or custom vectors. After that it using normalized bag-of-words (nBOW) to represent the weight or importance. It assumes that higher frequency implies that it is more important."
},
{
"code": null,
"e": 3183,
"s": 2938,
"text": "It allows transfer every word from sentence 1 to sentence 2 because algorithm does not know “obama” should transfer to “president”. At the end it will choose the minimum transportation cost to transport every word from sentence 1 to sentence 2."
},
{
"code": null,
"e": 3629,
"s": 3183,
"text": "The best average time of solving WMD is about O(p3 log p) while p is number of unique word. It is a little bit slow so there are two approaches to improve the reduce computation time. First one is Word Centroid Distance (WCD) which is summarizing the lower bound distance between. Second approach is Relaxed Word Moving Distance (RWMD) which is using the closet distance without considering there are multiple words transforming to single words."
},
{
"code": null,
"e": 3865,
"s": 3629,
"text": "Taking the previous sentence as an example. Assuming that shortest word in sentence of all word in sentence 1 is “president”, it will use summarize these score instead of pairing one by one. So that the time complexity reduce to O(p2)."
},
{
"code": null,
"e": 3967,
"s": 3865,
"text": "By using gensim, we only need to provide two list of tokens then it will take the rest of calculation"
},
{
"code": null,
"e": 4310,
"s": 3967,
"text": "subject_headline = news_headlines[0]subject_token = headline_tokens[0]print('Headline: ', subject_headline)print('=' * 50)print()for token, headline in zip(headline_tokens, news_headlines): print('-' * 50) print('Comparing to:', headline) distance = glove_model.wmdistance(subject_token, token) print('distance = %.4f' % distance)"
},
{
"code": null,
"e": 4317,
"s": 4310,
"text": "Output"
},
{
"code": null,
"e": 5038,
"s": 4317,
"text": "Headline: Elon Musk's Boring Co to build high-speed airport link in Chicago==================================================--------------------------------------------------Comparing to: Elon Musk's Boring Co to build high-speed airport link in Chicagodistance = 0.0000--------------------------------------------------Comparing to: Elon Musk's Boring Company to build high-speed Chicago airport linkdistance = 0.3589--------------------------------------------------Comparing to: Elon Musk’s Boring Company approved to build high-speed transit between downtown Chicago and O’Hare Airportdistance = 1.9456--------------------------------------------------Comparing to: Both apple and orange are fruitdistance = 5.4350"
},
{
"code": null,
"e": 5147,
"s": 5038,
"text": "In gensim implementation, OOV will be removed so that it will not throw an exception or using random vector."
},
{
"code": null,
"e": 5203,
"s": 5147,
"text": "For source code, you may check out from my github repo."
},
{
"code": null,
"e": 5281,
"s": 5203,
"text": "The advantage of WMD are hyper-parameter free and overcoming synonym problem."
},
{
"code": null,
"e": 5346,
"s": 5281,
"text": "Same as those simple approaches, WMD does not consider ordering."
},
{
"code": null,
"e": 5458,
"s": 5346,
"text": "The time complexity is an issue. The original version is O(p3 log p) while the enhanced version is still O(p2)."
},
{
"code": null,
"e": 5507,
"s": 5458,
"text": "Pre-train vectors may not apply to all scenario."
},
{
"code": null,
"e": 5707,
"s": 5507,
"text": "I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium Blog, LinkedIn or Github."
},
{
"code": null,
"e": 5872,
"s": 5707,
"text": "[1] Kusner Matt J., Sun Yu, Kolkin Nicholas I., Weinberger Kilian Q. From Word Embeedings To Document Distance. 2015. http://proceedings.mlr.press/v37/kusnerb15.pdf"
}
] |
Recursive Constructor Invocation in Java - GeeksforGeeks | 26 Sep, 2021
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. Here recursive constructor invocation and stack overflow error in java. It is as shown below in the example as follows:
Example
Java
// Java Program to Illustrate Recursion // Main classpublic class GFG { static int count = 0; // Method 1 // Recursive method static void function() { count = count + 1; if (count <= 5) { System.out.println("Call " + count); function(); } } // Method 2 // Main driver method public static void main(String[] args) { function(); }}
Call 1
Call 2
Call 3
Call 4
Call 5
Recursive Constructor Invocation
If a constructor calls itself, then the error message “recursive constructor invocation” occurs. The following program is not allowed by the compiler because inside the constructor we tried to call the same constructor. The compiler detects it instantly and throws an error.
Example:
Java
// Java program to Illustrate How Recursive// Constructor Invocation Error is Occurred // Main classclass GFG { // Constructor of this class // Inside we are trying to call the same constructor GFG() { // This keyword refers to same instance itself this(); } // Main driver method public static void main(String[] args) { // Creating an object of class inside main() GFG obj = new GFG(); }}
Output:
Now let us discuss what exactly we do refer to by Stack overflow error and why does it occur. Stack overflow error occurs if we do not provide the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.
Implementation:
Here we have created a GFG object inside the constructor which is initialized by calling the constructor, which then creates another GFG object which is again initialized by calling the constructor and it goes on until the stack overflows. This can be justified from the illustration as follows:
Example:
Java
// Java program to Illustrate Stack Overflow Error // Main classpublic class GFG { // Constructor of this class GFG() { // Creating an object of GFG class inside the // constructor which is initialized by calling the // constructor, which is initialized by // calling the constructor and it goes on GFG obj1 = new GFG(); } // Main driver method public static void main(String[] args) { // Creating an object of this class GFG obj = new GFG(); }}
Output:
anikaseth98
Blogathon-2021
Java-Constructors
Blogathon
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Create Table With a Primary Key
SQL Query to Convert Datetime to Date
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 24812,
"s": 24784,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 25233,
"s": 24812,
"text": "The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. Here recursive constructor invocation and stack overflow error in java. It is as shown below in the example as follows:"
},
{
"code": null,
"e": 25242,
"s": 25233,
"text": "Example "
},
{
"code": null,
"e": 25247,
"s": 25242,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Recursion // Main classpublic class GFG { static int count = 0; // Method 1 // Recursive method static void function() { count = count + 1; if (count <= 5) { System.out.println(\"Call \" + count); function(); } } // Method 2 // Main driver method public static void main(String[] args) { function(); }}",
"e": 25652,
"s": 25247,
"text": null
},
{
"code": null,
"e": 25687,
"s": 25652,
"text": "Call 1\nCall 2\nCall 3\nCall 4\nCall 5"
},
{
"code": null,
"e": 25720,
"s": 25687,
"text": "Recursive Constructor Invocation"
},
{
"code": null,
"e": 25995,
"s": 25720,
"text": "If a constructor calls itself, then the error message “recursive constructor invocation” occurs. The following program is not allowed by the compiler because inside the constructor we tried to call the same constructor. The compiler detects it instantly and throws an error."
},
{
"code": null,
"e": 26004,
"s": 25995,
"text": "Example:"
},
{
"code": null,
"e": 26009,
"s": 26004,
"text": "Java"
},
{
"code": "// Java program to Illustrate How Recursive// Constructor Invocation Error is Occurred // Main classclass GFG { // Constructor of this class // Inside we are trying to call the same constructor GFG() { // This keyword refers to same instance itself this(); } // Main driver method public static void main(String[] args) { // Creating an object of class inside main() GFG obj = new GFG(); }}",
"e": 26458,
"s": 26009,
"text": null
},
{
"code": null,
"e": 26466,
"s": 26458,
"text": "Output:"
},
{
"code": null,
"e": 26729,
"s": 26466,
"text": "Now let us discuss what exactly we do refer to by Stack overflow error and why does it occur. Stack overflow error occurs if we do not provide the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop."
},
{
"code": null,
"e": 26745,
"s": 26729,
"text": "Implementation:"
},
{
"code": null,
"e": 27041,
"s": 26745,
"text": "Here we have created a GFG object inside the constructor which is initialized by calling the constructor, which then creates another GFG object which is again initialized by calling the constructor and it goes on until the stack overflows. This can be justified from the illustration as follows:"
},
{
"code": null,
"e": 27050,
"s": 27041,
"text": "Example:"
},
{
"code": null,
"e": 27055,
"s": 27050,
"text": "Java"
},
{
"code": "// Java program to Illustrate Stack Overflow Error // Main classpublic class GFG { // Constructor of this class GFG() { // Creating an object of GFG class inside the // constructor which is initialized by calling the // constructor, which is initialized by // calling the constructor and it goes on GFG obj1 = new GFG(); } // Main driver method public static void main(String[] args) { // Creating an object of this class GFG obj = new GFG(); }}",
"e": 27578,
"s": 27055,
"text": null
},
{
"code": null,
"e": 27586,
"s": 27578,
"text": "Output:"
},
{
"code": null,
"e": 27598,
"s": 27586,
"text": "anikaseth98"
},
{
"code": null,
"e": 27613,
"s": 27598,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27631,
"s": 27613,
"text": "Java-Constructors"
},
{
"code": null,
"e": 27641,
"s": 27631,
"text": "Blogathon"
},
{
"code": null,
"e": 27646,
"s": 27641,
"text": "Java"
},
{
"code": null,
"e": 27651,
"s": 27646,
"text": "Java"
},
{
"code": null,
"e": 27749,
"s": 27651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27790,
"s": 27749,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27847,
"s": 27790,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27882,
"s": 27847,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27927,
"s": 27882,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 27965,
"s": 27927,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 27980,
"s": 27965,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28024,
"s": 27980,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28046,
"s": 28024,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28082,
"s": 28046,
"text": "Arrays.sort() in Java with examples"
}
] |
Subsets and Splits