title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Matplotlib.figure.Figure.autofmt_xdate() in Python - GeeksforGeeks
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 autofmt_xdate() method figure module of matplotlib library is used to rotate them and right align them. Syntax: autofmt_xdate(self, bottom=0.2, rotation=30, ha=’right’, which=None) Parameters: This accept the following parameters that are described below: bottom : This parameter is the bottom of the subplots for subplots_adjust(). rotation : This parameter is the rotation of the xtick labels. ha : This parameter is the horizontal alignment of the xticklabels. which : This parameter selects which ticklabels to rotate. Returns: This method does not return any value. Below examples illustrate the matplotlib.figure.Figure.autofmt_xdate() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'].view(np.recarray) fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data[:300], color ="green") ax.xaxis.set_major_locator(years) ax.format_ydata = lambda x: '$% 1.2f' % xax.grid(True) fig.autofmt_xdate() fig.suptitle('matplotlib.figure.Figure.autofmt_xdate() \function Example\n\n', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date1 = datetime.datetime(2020, 4, 2)date2 = datetime.datetime(2020, 4, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots()ax.plot_date(dates, y ** 2, 'g') ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d')) ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate() fig.suptitle('matplotlib.figure.Figure.autofmt_xdate() \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. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 26169, "s": 26141, "text": "\n30 Apr, 2020" }, { "code": null, "e": 26480, "s": 26169, "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": 26588, "s": 26480, "text": "The autofmt_xdate() method figure module of matplotlib library is used to rotate them and right align them." }, { "code": null, "e": 26665, "s": 26588, "text": "Syntax: autofmt_xdate(self, bottom=0.2, rotation=30, ha=’right’, which=None)" }, { "code": null, "e": 26740, "s": 26665, "text": "Parameters: This accept the following parameters that are described below:" }, { "code": null, "e": 26817, "s": 26740, "text": "bottom : This parameter is the bottom of the subplots for subplots_adjust()." }, { "code": null, "e": 26880, "s": 26817, "text": "rotation : This parameter is the rotation of the xtick labels." }, { "code": null, "e": 26948, "s": 26880, "text": "ha : This parameter is the horizontal alignment of the xticklabels." }, { "code": null, "e": 27007, "s": 26948, "text": "which : This parameter selects which ticklabels to rotate." }, { "code": null, "e": 27055, "s": 27007, "text": "Returns: This method does not return any value." }, { "code": null, "e": 27157, "s": 27055, "text": "Below examples illustrate the matplotlib.figure.Figure.autofmt_xdate() function in matplotlib.figure:" }, { "code": null, "e": 27168, "s": 27157, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'].view(np.recarray) fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data[:300], color =\"green\") ax.xaxis.set_major_locator(years) ax.format_ydata = lambda x: '$% 1.2f' % xax.grid(True) fig.autofmt_xdate() fig.suptitle('matplotlib.figure.Figure.autofmt_xdate() \\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 27882, "s": 27168, "text": null }, { "code": null, "e": 27890, "s": 27882, "text": "Output:" }, { "code": null, "e": 27901, "s": 27890, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date1 = datetime.datetime(2020, 4, 2)date2 = datetime.datetime(2020, 4, 6)delta = datetime.timedelta(hours = 6)dates = drange(date1, date2, delta) y = np.arange(len(dates)) fig, ax = plt.subplots()ax.plot_date(dates, y ** 2, 'g') ax.set_xlim(dates[0], dates[-1]) ax.xaxis.set_major_locator(DayLocator())ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))ax.xaxis.set_major_formatter(DateFormatter('% Y-% m-% d')) ax.fmt_xdata = DateFormatter('% Y-% m-% d % H:% M:% S')fig.autofmt_xdate() fig.suptitle('matplotlib.figure.Figure.autofmt_xdate() \\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 28704, "s": 27901, "text": null }, { "code": null, "e": 28712, "s": 28704, "text": "Output:" }, { "code": null, "e": 28736, "s": 28712, "text": "Matplotlib figure-class" }, { "code": null, "e": 28754, "s": 28736, "text": "Python-matplotlib" }, { "code": null, "e": 28761, "s": 28754, "text": "Python" }, { "code": null, "e": 28859, "s": 28761, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28877, "s": 28859, "text": "Python Dictionary" }, { "code": null, "e": 28912, "s": 28877, "text": "Read a file line by line in Python" }, { "code": null, "e": 28944, "s": 28912, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28966, "s": 28944, "text": "Enumerate() in Python" }, { "code": null, "e": 29008, "s": 28966, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29038, "s": 29008, "text": "Iterate over a list in Python" }, { "code": null, "e": 29067, "s": 29038, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29111, "s": 29067, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29148, "s": 29111, "text": "Create a Pandas DataFrame from Lists" } ]
Lex program to implement a simple Calculator - GeeksforGeeks
30 Apr, 2019 Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The commands for executing the LEX program are: lex abc.l (abc is the file name) cc lex.yy.c -efl ./a.out Let’s see LEX program to implement a simple calculator. Examples: Input : 3+3 Output : 6.0 Input : 5*4 Output : 20.0 Below is the implementation: /*lex program to implement - a simple calculator.*/ % { int op = 0,i; float a, b;% } dig [0-9]+|([0-9]*)"."([0-9]+)add "+"sub "-"mul "*"div "/"pow "^"ln \n%% /* digi() is a user defined function */{dig} {digi();} {add} {op=1;}{sub} {op=2;}{mul} {op=3;}{div} {op=4;}{pow} {op=5;}{ln} {printf("\n The Answer :%f\n\n",a);} %%digi(){ if(op==0) /* atof() is used to convert - the ASCII input to float */ a=atof(yytext); else { b=atof(yytext); switch(op) { case 1:a=a+b; break; case 2:a=a-b; break; case 3:a=a*b; break; case 4:a=a/b; break; case 5:for(i=a;b>1;b--) a=a*i; break; } op=0; }} main(int argv,char *argc[]){ yylex();} yywrap() { return 1; } Output: Lex program C Programs Compiler Design GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? How to Append a Character to a String in C Phases of a Compiler Three address code in Compiler Symbol Table in Compiler Code Optimization in Compiler Design Directed Acyclic graph in Compiler Design (with examples)
[ { "code": null, "e": 26177, "s": 26149, "text": "\n30 Apr, 2019" }, { "code": null, "e": 26373, "s": 26177, "text": "Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language." }, { "code": null, "e": 26421, "s": 26373, "text": "The commands for executing the LEX program are:" }, { "code": null, "e": 26480, "s": 26421, "text": "lex abc.l (abc is the file name)\ncc lex.yy.c -efl\n./a.out " }, { "code": null, "e": 26536, "s": 26480, "text": "Let’s see LEX program to implement a simple calculator." }, { "code": null, "e": 26546, "s": 26536, "text": "Examples:" }, { "code": null, "e": 26602, "s": 26546, "text": "Input : \n3+3\nOutput :\n6.0\n\nInput : \n5*4\nOutput : \n20.0 " }, { "code": null, "e": 26631, "s": 26602, "text": "Below is the implementation:" }, { "code": "/*lex program to implement - a simple calculator.*/ % { int op = 0,i; float a, b;% } dig [0-9]+|([0-9]*)\".\"([0-9]+)add \"+\"sub \"-\"mul \"*\"div \"/\"pow \"^\"ln \\n%% /* digi() is a user defined function */{dig} {digi();} {add} {op=1;}{sub} {op=2;}{mul} {op=3;}{div} {op=4;}{pow} {op=5;}{ln} {printf(\"\\n The Answer :%f\\n\\n\",a);} %%digi(){ if(op==0) /* atof() is used to convert - the ASCII input to float */ a=atof(yytext); else { b=atof(yytext); switch(op) { case 1:a=a+b; break; case 2:a=a-b; break; case 3:a=a*b; break; case 4:a=a/b; break; case 5:for(i=a;b>1;b--) a=a*i; break; } op=0; }} main(int argv,char *argc[]){ yylex();} yywrap() { return 1; }", "e": 27342, "s": 26631, "text": null }, { "code": null, "e": 27350, "s": 27342, "text": "Output:" }, { "code": null, "e": 27362, "s": 27350, "text": "Lex program" }, { "code": null, "e": 27373, "s": 27362, "text": "C Programs" }, { "code": null, "e": 27389, "s": 27373, "text": "Compiler Design" }, { "code": null, "e": 27395, "s": 27389, "text": "GBlog" }, { "code": null, "e": 27493, "s": 27395, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27534, "s": 27493, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27569, "s": 27534, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27613, "s": 27569, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27672, "s": 27613, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27715, "s": 27672, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 27736, "s": 27715, "text": "Phases of a Compiler" }, { "code": null, "e": 27767, "s": 27736, "text": "Three address code in Compiler" }, { "code": null, "e": 27792, "s": 27767, "text": "Symbol Table in Compiler" }, { "code": null, "e": 27829, "s": 27792, "text": "Code Optimization in Compiler Design" } ]
C program to Replace a word in a text by another given word - GeeksforGeeks
25 Jul, 2020 Given three strings ‘str’, ‘oldW’ and ‘newW’. The task is find all occurrences of the word ‘oldW’ and replace then with word ‘newW’.Examples: Input : str[] = "xxforxx xx for xx", oldW[] = "xx", newW[] = "geeks" Output : geeksforgeeks geeks for geeks The idea is to traverse the original string and count the number of times old word occurs in the string. Now make a new string of sufficient size so that new word can be replaced. Now copy original string to new string with replacement of word. // C program to search and replace// all occurrences of a word with// other word.#include <stdio.h>#include <stdlib.h>#include <string.h> // Function to replace a string with another// stringchar* replaceWord(const char* s, const char* oldW, const char* newW){ char* result; int i, cnt = 0; int newWlen = strlen(newW); int oldWlen = strlen(oldW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '\0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char*)malloc(i + cnt * (newWlen - oldWlen) + 1); i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; } else result[i++] = *s++; } result[i] = '\0'; return result;} // Driver Programint main(){ char str[] = "xxforxx xx for xx"; char c[] = "xx"; char d[] = "Geeks"; char* result = NULL; // oldW string printf("Old string: %s\n", str); result = replaceWord(str, c, d); printf("New String: %s\n", result); free(result); return 0;} Old string: xxforxx xx for xx New String: GeeksforGeeks Geeks for Geeks Method 2: This method involves inplace update of string. It is more efficient as it uses only extra space for the new characters to be inserted. #include <bits/stdc++.h>using namespace std;int main(){ // code int t; cin >> t; cin.ignore(); while (t--) { string s; getline(cin, s); string x, y; getline(cin, x); getline(cin, y); reverse(s.begin(), s.end()); reverse(x.begin(), x.end()); reverse(y.begin(), y.end()); int ls = s.length(), lx = x.length(), ly = y.length(); int d = ly - lx; int ct = 0; int i = 0, j = 0; while (i < ls) { string temp = ""; for (int k = 0; k < lx; k++) { temp += s[i + k]; } if (temp == x) { ct++; i = i + lx; } else { i = i + 1; } } for (int i = 0; i < ct * d; i++) s += ' '; i = ls - 1; j = ls + ct * d - 1; while (i >= 0 && j >= 0) { string temp = ""; for (int k = 0; k < lx; k++) { if (i < (lx - 1 - k)) break; temp += s[i - (lx - 1 - k)]; } if (temp == x) { int k = ly - 1; while (k >= 0) s[j--] = y[k--]; i = i - lx; } else { s[j--] = s[i--]; } } reverse(s.begin(), s.end()); cout << s << endl; } return 0;} 1 xxforxx xx for xx xx geeks geeksforgeeks geeks for geeks This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Didi17 sarojrana C Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? How to Append a Character to a String in C 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 Longest Common Subsequence | DP-4
[ { "code": null, "e": 25791, "s": 25763, "text": "\n25 Jul, 2020" }, { "code": null, "e": 25933, "s": 25791, "text": "Given three strings ‘str’, ‘oldW’ and ‘newW’. The task is find all occurrences of the word ‘oldW’ and replace then with word ‘newW’.Examples:" }, { "code": null, "e": 26060, "s": 25933, "text": "Input : str[] = \"xxforxx xx for xx\", \n oldW[] = \"xx\", \n newW[] = \"geeks\"\nOutput : geeksforgeeks geeks for geeks\n" }, { "code": null, "e": 26305, "s": 26060, "text": "The idea is to traverse the original string and count the number of times old word occurs in the string. Now make a new string of sufficient size so that new word can be replaced. Now copy original string to new string with replacement of word." }, { "code": "// C program to search and replace// all occurrences of a word with// other word.#include <stdio.h>#include <stdlib.h>#include <string.h> // Function to replace a string with another// stringchar* replaceWord(const char* s, const char* oldW, const char* newW){ char* result; int i, cnt = 0; int newWlen = strlen(newW); int oldWlen = strlen(oldW); // Counting the number of times old word // occur in the string for (i = 0; s[i] != '\\0'; i++) { if (strstr(&s[i], oldW) == &s[i]) { cnt++; // Jumping to index after the old word. i += oldWlen - 1; } } // Making new string of enough length result = (char*)malloc(i + cnt * (newWlen - oldWlen) + 1); i = 0; while (*s) { // compare the substring with the result if (strstr(s, oldW) == s) { strcpy(&result[i], newW); i += newWlen; s += oldWlen; } else result[i++] = *s++; } result[i] = '\\0'; return result;} // Driver Programint main(){ char str[] = \"xxforxx xx for xx\"; char c[] = \"xx\"; char d[] = \"Geeks\"; char* result = NULL; // oldW string printf(\"Old string: %s\\n\", str); result = replaceWord(str, c, d); printf(\"New String: %s\\n\", result); free(result); return 0;}", "e": 27651, "s": 26305, "text": null }, { "code": null, "e": 27724, "s": 27651, "text": "Old string: xxforxx xx for xx\nNew String: GeeksforGeeks Geeks for Geeks\n" }, { "code": null, "e": 27869, "s": 27724, "text": "Method 2: This method involves inplace update of string. It is more efficient as it uses only extra space for the new characters to be inserted." }, { "code": "#include <bits/stdc++.h>using namespace std;int main(){ // code int t; cin >> t; cin.ignore(); while (t--) { string s; getline(cin, s); string x, y; getline(cin, x); getline(cin, y); reverse(s.begin(), s.end()); reverse(x.begin(), x.end()); reverse(y.begin(), y.end()); int ls = s.length(), lx = x.length(), ly = y.length(); int d = ly - lx; int ct = 0; int i = 0, j = 0; while (i < ls) { string temp = \"\"; for (int k = 0; k < lx; k++) { temp += s[i + k]; } if (temp == x) { ct++; i = i + lx; } else { i = i + 1; } } for (int i = 0; i < ct * d; i++) s += ' '; i = ls - 1; j = ls + ct * d - 1; while (i >= 0 && j >= 0) { string temp = \"\"; for (int k = 0; k < lx; k++) { if (i < (lx - 1 - k)) break; temp += s[i - (lx - 1 - k)]; } if (temp == x) { int k = ly - 1; while (k >= 0) s[j--] = y[k--]; i = i - lx; } else { s[j--] = s[i--]; } } reverse(s.begin(), s.end()); cout << s << endl; } return 0;}", "e": 29311, "s": 27869, "text": null }, { "code": null, "e": 29341, "s": 29311, "text": "1\nxxforxx xx for xx\nxx\ngeeks\n" }, { "code": null, "e": 29372, "s": 29341, "text": "geeksforgeeks geeks for geeks\n" }, { "code": null, "e": 29672, "s": 29372, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29797, "s": 29672, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29804, "s": 29797, "text": "Didi17" }, { "code": null, "e": 29814, "s": 29804, "text": "sarojrana" }, { "code": null, "e": 29825, "s": 29814, "text": "C Programs" }, { "code": null, "e": 29833, "s": 29825, "text": "Strings" }, { "code": null, "e": 29841, "s": 29833, "text": "Strings" }, { "code": null, "e": 29939, "s": 29841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29980, "s": 29939, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30015, "s": 29980, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30059, "s": 30015, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 30118, "s": 30059, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 30161, "s": 30118, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 30207, "s": 30161, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 30232, "s": 30207, "text": "Reverse a string in Java" }, { "code": null, "e": 30292, "s": 30232, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30307, "s": 30292, "text": "C++ Data Types" } ]
How to use time input type in HTML?
The time input type is used in HTML using the <input type="time">. Using this, allow the users to select time. A time picker popup is visible whenever input field is clicked. Note: The input type time is not supported in Firefox and Internet Explorer. It works on Google Chrome. You can try to run the following code to learn how to use time input type in HTML. <!DOCTYPE html> <html> <head> <title>HTML input time</title> </head> <body> <form action = "" method = "get"> Details:<br><br> Student Name<br><input type="name" name="sname"><br> Exam Time<br><input type="time" name="etime"><br> <input type="submit" value="Submit"> </form> </body> </html>
[ { "code": null, "e": 1237, "s": 1062, "text": "The time input type is used in HTML using the <input type=\"time\">. Using this, allow the users to select time. A time picker popup is visible whenever input field is clicked." }, { "code": null, "e": 1341, "s": 1237, "text": "Note: The input type time is not supported in Firefox and Internet Explorer. It works on Google Chrome." }, { "code": null, "e": 1424, "s": 1341, "text": "You can try to run the following code to learn how to use time input type in HTML." }, { "code": null, "e": 1781, "s": 1424, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML input time</title>\n </head>\n <body>\n <form action = \"\" method = \"get\">\n Details:<br><br>\n Student Name<br><input type=\"name\" name=\"sname\"><br>\n Exam Time<br><input type=\"time\" name=\"etime\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>" } ]
Automate Youtube with Python - GeeksforGeeks
28 Feb, 2022 In this article, we are going to see how to automate Youtube using Python. Selenium: It controlling a web browser through the program pyttsx3: It is a text-to-speech conversion library in Python speech_recognition: Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc pyaudio: It is used to play and record audio on a variety of platforms Make sure that you have noted the location where the chromedriver has been downloaded (as it is used in our python script). Now After downloading extract the zip file and please note the file location of the extracted file as we have needed it later in python code. (You can find the location by clicking on properties and then details). Import the library which we have installed. Then we have to take the input search query using the speech_recognition library. we can do this by making an instance of speech_recognition library as sr.Recognizer() . After this adjusting the threshold frequency and convert the voice input into a string. Then, the main part comes into the picture, we have created a function automateYoutube() which plays the required video from Youtube. In this function create we driver instance using function webdriver.Chrome() which takes the path of chromedriver as the parameter. Finally, find the name or id or class or CSS selector of the search bar and search button by right-clicking inspect search bar and .search button. Now, just call the automateYoutube() function to see the output. Now we have to automate play/pause buttons for that we again find the CSS selector of play/pause button using selenium. Python3 from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditionsfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysimport speech_recognition as srimport pyttsx3import time def automateYoutube(searchtext): # giving the path of chromedriver to selenium webdriver path = "C:\\Users\\hp\\Downloads\\chromedriver" url = "https://www.youtube.com/" # opening the youtube in chromedriver driver = webdriver.Chrome(path) driver.get(url) # find the search bar using selenium find_element function driver.find_element_by_name("search_query").send_keys(searchtext) # clicking on the search button driver.find_element_by_css_selector( "#search-icon-legacy.ytd-searchbox").click() # For finding the right match search WebDriverWait(driver, 0).until(expected_conditions.title_contains(MyText)) # clicking on the match search having same as in searched query WebDriverWait(driver, 30).until( expected_conditions.element_to_be_clickable((By.ID, "img"))).click() # while(True): # pass speak = sr.Recognizer()try: with sr.Microphone() as speaky: # adjust the energy threshold based on # the surrounding noise level speak.adjust_for_ambient_noise(speaky, duration=0.2) print("listening...") # listens for the user's input searchquery = speak.listen(speaky) # Using google to recognize audio MyText = speak.recognize_google(searchquery) MyText = MyText.lower() except sr.RequestError as e: print("Could not request results; {0}".format(e)) except sr.UnknownValueError: print("unknown error occured") # Calling the functionautomateYoutube(MyText) Output: saurabh1990aror kashishsoda varshagumber28 nikhatkhan11 Blogathon-2021 Picked Python Selenium-Exercises Python-selenium Blogathon Python 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 Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24838, "s": 24810, "text": "\n28 Feb, 2022" }, { "code": null, "e": 24913, "s": 24838, "text": "In this article, we are going to see how to automate Youtube using Python." }, { "code": null, "e": 24972, "s": 24913, "text": "Selenium: It controlling a web browser through the program" }, { "code": null, "e": 25033, "s": 24972, "text": "pyttsx3: It is a text-to-speech conversion library in Python" }, { "code": null, "e": 25179, "s": 25033, "text": "speech_recognition: Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc" }, { "code": null, "e": 25250, "s": 25179, "text": "pyaudio: It is used to play and record audio on a variety of platforms" }, { "code": null, "e": 25588, "s": 25250, "text": "Make sure that you have noted the location where the chromedriver has been downloaded (as it is used in our python script). Now After downloading extract the zip file and please note the file location of the extracted file as we have needed it later in python code. (You can find the location by clicking on properties and then details)." }, { "code": null, "e": 25632, "s": 25588, "text": "Import the library which we have installed." }, { "code": null, "e": 25802, "s": 25632, "text": "Then we have to take the input search query using the speech_recognition library. we can do this by making an instance of speech_recognition library as sr.Recognizer() ." }, { "code": null, "e": 25890, "s": 25802, "text": "After this adjusting the threshold frequency and convert the voice input into a string." }, { "code": null, "e": 26024, "s": 25890, "text": "Then, the main part comes into the picture, we have created a function automateYoutube() which plays the required video from Youtube." }, { "code": null, "e": 26156, "s": 26024, "text": "In this function create we driver instance using function webdriver.Chrome() which takes the path of chromedriver as the parameter." }, { "code": null, "e": 26303, "s": 26156, "text": "Finally, find the name or id or class or CSS selector of the search bar and search button by right-clicking inspect search bar and .search button." }, { "code": null, "e": 26368, "s": 26303, "text": "Now, just call the automateYoutube() function to see the output." }, { "code": null, "e": 26488, "s": 26368, "text": "Now we have to automate play/pause buttons for that we again find the CSS selector of play/pause button using selenium." }, { "code": null, "e": 26496, "s": 26488, "text": "Python3" }, { "code": "from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditionsfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysimport speech_recognition as srimport pyttsx3import time def automateYoutube(searchtext): # giving the path of chromedriver to selenium webdriver path = \"C:\\\\Users\\\\hp\\\\Downloads\\\\chromedriver\" url = \"https://www.youtube.com/\" # opening the youtube in chromedriver driver = webdriver.Chrome(path) driver.get(url) # find the search bar using selenium find_element function driver.find_element_by_name(\"search_query\").send_keys(searchtext) # clicking on the search button driver.find_element_by_css_selector( \"#search-icon-legacy.ytd-searchbox\").click() # For finding the right match search WebDriverWait(driver, 0).until(expected_conditions.title_contains(MyText)) # clicking on the match search having same as in searched query WebDriverWait(driver, 30).until( expected_conditions.element_to_be_clickable((By.ID, \"img\"))).click() # while(True): # pass speak = sr.Recognizer()try: with sr.Microphone() as speaky: # adjust the energy threshold based on # the surrounding noise level speak.adjust_for_ambient_noise(speaky, duration=0.2) print(\"listening...\") # listens for the user's input searchquery = speak.listen(speaky) # Using google to recognize audio MyText = speak.recognize_google(searchquery) MyText = MyText.lower() except sr.RequestError as e: print(\"Could not request results; {0}\".format(e)) except sr.UnknownValueError: print(\"unknown error occured\") # Calling the functionautomateYoutube(MyText)", "e": 28318, "s": 26496, "text": null }, { "code": null, "e": 28326, "s": 28318, "text": "Output:" }, { "code": null, "e": 28342, "s": 28326, "text": "saurabh1990aror" }, { "code": null, "e": 28354, "s": 28342, "text": "kashishsoda" }, { "code": null, "e": 28369, "s": 28354, "text": "varshagumber28" }, { "code": null, "e": 28382, "s": 28369, "text": "nikhatkhan11" }, { "code": null, "e": 28397, "s": 28382, "text": "Blogathon-2021" }, { "code": null, "e": 28404, "s": 28397, "text": "Picked" }, { "code": null, "e": 28430, "s": 28404, "text": "Python Selenium-Exercises" }, { "code": null, "e": 28446, "s": 28430, "text": "Python-selenium" }, { "code": null, "e": 28456, "s": 28446, "text": "Blogathon" }, { "code": null, "e": 28463, "s": 28456, "text": "Python" }, { "code": null, "e": 28561, "s": 28463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28602, "s": 28561, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 28659, "s": 28602, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28694, "s": 28659, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 28739, "s": 28694, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 28777, "s": 28739, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 28805, "s": 28777, "text": "Read JSON file using Python" }, { "code": null, "e": 28855, "s": 28805, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28877, "s": 28855, "text": "Python map() function" } ]
C# - Do...While Loop
Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop checks its condition at the end of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. The syntax of a do...while loop in C# is − do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. using System; namespace Loops { class Program { static void Main(string[] args) { /* local variable definition */ int a = 10; /* do loop execution */ do { Console.WriteLine("value of a: {0}", a); a = a + 1; } while (a < 20); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2419, "s": 2270, "text": "Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop checks its condition at the end of the loop." }, { "code": null, "e": 2539, "s": 2419, "text": "A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time." }, { "code": null, "e": 2582, "s": 2539, "text": "The syntax of a do...while loop in C# is −" }, { "code": null, "e": 2627, "s": 2582, "text": "do {\n statement(s);\n} while( condition );\n" }, { "code": null, "e": 2775, "s": 2627, "text": "Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested." }, { "code": null, "e": 2952, "s": 2775, "text": "If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false." }, { "code": null, "e": 3321, "s": 2952, "text": "using System;\n\nnamespace Loops {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int a = 10;\n \n /* do loop execution */\n do {\n Console.WriteLine(\"value of a: {0}\", a);\n a = a + 1;\n } \n while (a < 20);\n Console.ReadLine();\n }\n }\n} " }, { "code": null, "e": 3402, "s": 3321, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3553, "s": 3402, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 3590, "s": 3553, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 3603, "s": 3590, "text": " Raja Biswas" }, { "code": null, "e": 3637, "s": 3603, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 3655, "s": 3637, "text": " Trevoir Williams" }, { "code": null, "e": 3688, "s": 3655, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3702, "s": 3688, "text": " Peter Jepson" }, { "code": null, "e": 3739, "s": 3702, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 3754, "s": 3739, "text": " Ebenezer Ogbu" }, { "code": null, "e": 3789, "s": 3754, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 3804, "s": 3789, "text": " Arnold Higuit" }, { "code": null, "e": 3839, "s": 3804, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3851, "s": 3839, "text": " Eric Frick" }, { "code": null, "e": 3858, "s": 3851, "text": " Print" }, { "code": null, "e": 3869, "s": 3858, "text": " Add Notes" } ]
Split one-dimensional array into two-dimensional array JavaScript
We are required to write a function that takes in a one-dimensional array as the first argument and a number n as the second argument and we have to make n subarrays inside of the parent array (**if possible) and divide elements into them accordingly. ** if the array contains 9 elements and we asked to make 4 subarrays, then dividing 2 elements in each subarray creates 5 subarrays and 3 in each creates 3, so in such cases we have to fallback to nearest lowest level (3 in this case) because our requirement is to distribute equal number of elements in each subarray except the last one in some special cases. For example − // if the input array is: const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; // and the number is 2 //then the output should be: const output = [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]; Let’s write the code for this function − const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; const splitArray = (arr, rows) => { const itemsPerRow = Math.ceil(arr.length / rows); return arr.reduce((acc, val, ind) => { const currentRow = Math.floor(ind / itemsPerRow); if(!acc[currentRow]){ acc[currentRow] = [val]; }else{ acc[currentRow].push(val); }; return acc; }, []); }; console.log(splitArray(arr, 2)); The output in the console will be − [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]
[ { "code": null, "e": 1314, "s": 1062, "text": "We are required to write a function that takes in a one-dimensional array as the first argument\nand a number n as the second argument and we have to make n subarrays inside of the parent\narray (**if possible) and divide elements into them accordingly." }, { "code": null, "e": 1675, "s": 1314, "text": "** if the array contains 9 elements and we asked to make 4 subarrays, then dividing 2 elements\nin each subarray creates 5 subarrays and 3 in each creates 3, so in such cases we have to\nfallback to nearest lowest level (3 in this case) because our requirement is to distribute equal\nnumber of elements in each subarray except the last one in some special cases." }, { "code": null, "e": 1689, "s": 1675, "text": "For example −" }, { "code": null, "e": 1898, "s": 1689, "text": "// if the input array is:\nconst arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];\n// and the number is 2\n//then the output should be:\nconst output = [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ];" }, { "code": null, "e": 1939, "s": 1898, "text": "Let’s write the code for this function −" }, { "code": null, "e": 2370, "s": 1939, "text": "const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];\nconst splitArray = (arr, rows) => {\n const itemsPerRow = Math.ceil(arr.length / rows);\n return arr.reduce((acc, val, ind) => {\n const currentRow = Math.floor(ind / itemsPerRow);\n if(!acc[currentRow]){\n acc[currentRow] = [val];\n }else{\n acc[currentRow].push(val);\n };\n return acc;\n }, []);\n};\nconsole.log(splitArray(arr, 2));" }, { "code": null, "e": 2406, "s": 2370, "text": "The output in the console will be −" }, { "code": null, "e": 2462, "s": 2406, "text": "[ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]" } ]
How do you check scroll position using selenium?
We can check scroll position using Selenium. To check the position we shall use the Javascript executor. We have to verify the value of the window.pageYOffset in the browser. While the URL is launched, the scroll is at the top the value of window.pageYOffset is 0. As we scroll to an element, the value of the window.pageYOffset shall be greater than 0. JavascriptExecutor j = (JavascriptExecutor) driver; Long v = (Long) j.executeScript("return window.pageYOffset;"); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ScrollPosition{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // get current scroll position with Javascript Executor JavascriptExecutor j = (JavascriptExecutor) driver; Long v = (Long) j.executeScript("return window.pageYOffset;"); System.out.println("Scroll position after launch: " + v); // identify element WebElement n=driver.findElement(By.xpath("//*[text()='Careers']")); // Javascript executor to scroll to the element ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", n); Thread.sleep(200); // get current scroll position with Javascript Executor JavascriptExecutor js = (JavascriptExecutor) driver; double d = (double) js.executeScript("return window.pageYOffset;"); System.out.println("Scroll position after scrolling upto an element: "+d); driver.close(); } }
[ { "code": null, "e": 1237, "s": 1062, "text": "We can check scroll position using Selenium. To check the position we shall use the Javascript executor. We have to verify the value of the window.pageYOffset in the browser." }, { "code": null, "e": 1416, "s": 1237, "text": "While the URL is launched, the scroll is at the top the value of window.pageYOffset is 0. As we scroll to an element, the value of the window.pageYOffset shall be greater than 0." }, { "code": null, "e": 1531, "s": 1416, "text": "JavascriptExecutor j = (JavascriptExecutor) driver;\nLong v = (Long) j.executeScript(\"return window.pageYOffset;\");" }, { "code": null, "e": 2964, "s": 1531, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ScrollPosition{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // get current scroll position with Javascript Executor\n JavascriptExecutor j = (JavascriptExecutor) driver;\n Long v = (Long) j.executeScript(\"return window.pageYOffset;\");\n System.out.println(\"Scroll position after launch: \" + v);\n // identify element\n WebElement n=driver.findElement(By.xpath(\"//*[text()='Careers']\"));\n // Javascript executor to scroll to the element\n ((JavascriptExecutor)driver).executeScript(\"arguments[0].scrollIntoView(true);\", n);\n Thread.sleep(200);\n // get current scroll position with Javascript Executor\n JavascriptExecutor js = (JavascriptExecutor) driver;\n double d = (double) js.executeScript(\"return window.pageYOffset;\");\n System.out.println(\"Scroll position after scrolling upto an element: \"+d);\n driver.close();\n }\n}" } ]
Find the minimum positive integer such that it is divisible by A and sum of its digits is equal to B in Python
Suppose we have two numbers A and B, we have to find the minimum positive number M so that M is divisible by A and the sum of the digits of M is same as B. So, if there is no such result, then return -1. So, if the input is like A = 50, B = 2, then the output will be 200 as this is divisible by 50 and sum of its digit = 2 + 0 + 0 = 2. To solve this, we will follow these steps − Define one element type container, that contains two numbers a and b and one string Define one element type container, that contains two numbers a and b and one string que := a new list que := a new list elem := a new element with (0, 0, blank string) elem := a new element with (0, 0, blank string) visited[0, 0] := 1 visited[0, 0] := 1 insert elem at the end of que insert elem at the end of que while size of que > 0, dotemp_elem := delete first element from queif temp_elem.a is 0 and temp_elem.b is b, thenreturn integer of temp_elem.stringfor i in range 0 to 9, dox :=(temp_elem.a * 10 + i) mod ay := temp_elem.b + iif y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into que while size of que > 0, do temp_elem := delete first element from que temp_elem := delete first element from que if temp_elem.a is 0 and temp_elem.b is b, thenreturn integer of temp_elem.string if temp_elem.a is 0 and temp_elem.b is b, then return integer of temp_elem.string return integer of temp_elem.string for i in range 0 to 9, dox :=(temp_elem.a * 10 + i) mod ay := temp_elem.b + iif y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into que for i in range 0 to 9, do x :=(temp_elem.a * 10 + i) mod a x :=(temp_elem.a * 10 + i) mod a y := temp_elem.b + i y := temp_elem.b + i if y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into que if y <= b and visited[x, y] is False, then visited[x, y] := 1 visited[x, y] := 1 insert new element with x, y and temp_elem.string concatenate i into que insert new element with x, y and temp_elem.string concatenate i into que return -1 return -1 Let us see the following implementation to get better understanding − Live Demo visited = [[0 for x in range(501)] for y in range(5001)] class Element: def __init__(self, a, b, string): self.a = a self.b = b self.string = string def get_number(a, b): que = [] elem = Element(0, 0, "") visited[0][0] = 1 que.append(elem) while len(que) > 0: temp_elem = que.pop(0) if temp_elem.a == 0 and temp_elem.b == b: return int(temp_elem.string) for i in range(0, 10): x = (temp_elem.a * 10 + i) % a y = temp_elem.b + i if y <= b and visited[x][y] == False: visited[x][y] = 1 que.append(Element(x, y, temp_elem.string + str(i))) return -1 a, b = 50, 2 print(get_number(a, b)) 50, 2 200
[ { "code": null, "e": 1266, "s": 1062, "text": "Suppose we have two numbers A and B, we have to find the minimum positive number M so that M is divisible by A and the sum of the digits of M is same as B. So, if there is no such result, then return -1." }, { "code": null, "e": 1399, "s": 1266, "text": "So, if the input is like A = 50, B = 2, then the output will be 200 as this is divisible by 50 and sum of its digit = 2 + 0 + 0 = 2." }, { "code": null, "e": 1443, "s": 1399, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1527, "s": 1443, "text": "Define one element type container, that contains two numbers a and b and one string" }, { "code": null, "e": 1611, "s": 1527, "text": "Define one element type container, that contains two numbers a and b and one string" }, { "code": null, "e": 1629, "s": 1611, "text": "que := a new list" }, { "code": null, "e": 1647, "s": 1629, "text": "que := a new list" }, { "code": null, "e": 1695, "s": 1647, "text": "elem := a new element with (0, 0, blank string)" }, { "code": null, "e": 1743, "s": 1695, "text": "elem := a new element with (0, 0, blank string)" }, { "code": null, "e": 1762, "s": 1743, "text": "visited[0, 0] := 1" }, { "code": null, "e": 1781, "s": 1762, "text": "visited[0, 0] := 1" }, { "code": null, "e": 1811, "s": 1781, "text": "insert elem at the end of que" }, { "code": null, "e": 1841, "s": 1811, "text": "insert elem at the end of que" }, { "code": null, "e": 2198, "s": 1841, "text": "while size of que > 0, dotemp_elem := delete first element from queif temp_elem.a is 0 and temp_elem.b is b, thenreturn integer of temp_elem.stringfor i in range 0 to 9, dox :=(temp_elem.a * 10 + i) mod ay := temp_elem.b + iif y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into\nque" }, { "code": null, "e": 2224, "s": 2198, "text": "while size of que > 0, do" }, { "code": null, "e": 2267, "s": 2224, "text": "temp_elem := delete first element from que" }, { "code": null, "e": 2310, "s": 2267, "text": "temp_elem := delete first element from que" }, { "code": null, "e": 2391, "s": 2310, "text": "if temp_elem.a is 0 and temp_elem.b is b, thenreturn integer of temp_elem.string" }, { "code": null, "e": 2438, "s": 2391, "text": "if temp_elem.a is 0 and temp_elem.b is b, then" }, { "code": null, "e": 2473, "s": 2438, "text": "return integer of temp_elem.string" }, { "code": null, "e": 2508, "s": 2473, "text": "return integer of temp_elem.string" }, { "code": null, "e": 2718, "s": 2508, "text": "for i in range 0 to 9, dox :=(temp_elem.a * 10 + i) mod ay := temp_elem.b + iif y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into\nque" }, { "code": null, "e": 2744, "s": 2718, "text": "for i in range 0 to 9, do" }, { "code": null, "e": 2777, "s": 2744, "text": "x :=(temp_elem.a * 10 + i) mod a" }, { "code": null, "e": 2810, "s": 2777, "text": "x :=(temp_elem.a * 10 + i) mod a" }, { "code": null, "e": 2831, "s": 2810, "text": "y := temp_elem.b + i" }, { "code": null, "e": 2852, "s": 2831, "text": "y := temp_elem.b + i" }, { "code": null, "e": 2985, "s": 2852, "text": "if y <= b and visited[x, y] is False, thenvisited[x, y] := 1insert new element with x, y and temp_elem.string concatenate i into\nque" }, { "code": null, "e": 3028, "s": 2985, "text": "if y <= b and visited[x, y] is False, then" }, { "code": null, "e": 3047, "s": 3028, "text": "visited[x, y] := 1" }, { "code": null, "e": 3066, "s": 3047, "text": "visited[x, y] := 1" }, { "code": null, "e": 3139, "s": 3066, "text": "insert new element with x, y and temp_elem.string concatenate i into\nque" }, { "code": null, "e": 3212, "s": 3139, "text": "insert new element with x, y and temp_elem.string concatenate i into\nque" }, { "code": null, "e": 3222, "s": 3212, "text": "return -1" }, { "code": null, "e": 3232, "s": 3222, "text": "return -1" }, { "code": null, "e": 3302, "s": 3232, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3313, "s": 3302, "text": " Live Demo" }, { "code": null, "e": 4015, "s": 3313, "text": "visited = [[0 for x in range(501)] for y in range(5001)]\nclass Element:\n def __init__(self, a, b, string):\n self.a = a\n self.b = b\n self.string = string\ndef get_number(a, b):\n que = []\n elem = Element(0, 0, \"\")\n visited[0][0] = 1\n que.append(elem)\n while len(que) > 0:\n temp_elem = que.pop(0)\n if temp_elem.a == 0 and temp_elem.b == b:\n return int(temp_elem.string)\n for i in range(0, 10):\n x = (temp_elem.a * 10 + i) % a\n y = temp_elem.b + i\n if y <= b and visited[x][y] == False:\n visited[x][y] = 1\n que.append(Element(x, y, temp_elem.string + str(i)))\n return -1\n\na, b = 50, 2\nprint(get_number(a, b))" }, { "code": null, "e": 4021, "s": 4015, "text": "50, 2" }, { "code": null, "e": 4025, "s": 4021, "text": "200" } ]
Scraping Specific Tweet Replies with Python | by Nicholas Resendez | Towards Data Science
Twitter is beginning to take over the social media realm. As more communities move to Twitter, we begin to see how valuable data is to advertisers, researchers, and even consumers. Data is now the next gold rush as we begin to understand how data needs to be extracted, transformed, loaded, and for full benefit, turned into Information. In theory, like gold, data is a commodity. In this article, I plan to explain how easy it is to scrape Tweets from Twitter in Python3 using Tweepy’s Twitter API. This data can be accessed by Twitter’s API and Tweepy which ended up being the most successful method. I plan to focus on scraping specific user Tweet replies, since I have not discovered any tutorials which specifically highlight how to extract Tweet replies. If you want to jump straight into the code then you can find the full code on my Github. The Python code requires your Twitter API and consumer keys, as well as the Twitter username you plan to extract replies, and the Tweet ID. Make sure you have Python installed on your machine. If you do not, I suggest using Anaconda, otherwise read the official Python documentation to find additional resources. To perform Twitter operations from your machine, I suggest using Tweepy. To install Tweepy, navigate to your environment and run: Python3: pip install tweepy If you’re using Anaconda for Python: conda install -c conda-forge tweepy If you would like to interact with Twitter from a computer or machine, you will need to apply for Twitter Developers. The application is straight forward, be honest with your intentions within the application, and you will become approved if you are deemed trustworthy from Twitter. Once approved, you will be able to create an app on the platform which provides you with credentials to authorize from Tweepy or your Python Twitter library. Twitter for Developers provides access to the Twitter API in order to Publish and analyze Tweets, optimize ads, and create unique customer experiences. Check out the Twitter API documentation here. Before you are able to use the Twitter API endpoints, create a developer account and generate your API keys. You can apply for a developer account directly here. You must answer questions on how you plan to use the API and accept the Twitter Developer Agreement, and then you will be granted access to the Developer Dashboard. Once you are approved access to the Developers for Twitter, log in to the developer site and create your App. This step will automatically generate your consumer API keys and access tokens, remember, you should keep them secret: The developer account should be linked to the Twitter account where you want to have the bot active. From the Twitter Development platform, you are able to edit the app permissions. In my example, I have granted my app permission to read, write and send direct messages. We must import Tweepy then OAuth interface to collect data as well as csv, and ssl. import csvimport tweepyimport sslssl._create_default_https_context = ssl._create_unverified_context# Oauth keysconsumer_key = "YOUR_CONSUMER_KEY"consumer_secret = "YOUR_CONSUMER_SECRET"access_token = "YOUR_ACCESS_TOKEN"access_token_secret = "YOUR_ACCESS_SECRET"# Authentication with Twitterauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth) To collect tweet replies for a specific user and tweet, we must list the username of the user being scraped, as well as the Tweet ID which can be found by copying from the URL. # update these for whatever tweet you want to process replies toname = 'LunarCRUSH'tweet_id = '1270923526690664448'replies=[]for tweet in tweepy.Cursor(api.search,q='to:'+name, result_type='recent', timeout=999999).items(1000): if hasattr(tweet, 'in_reply_to_status_id_str'): if (tweet.in_reply_to_status_id_str==tweet_id): replies.append(tweet) Since I was hoping to analyze the responses, I decided to export all replies to a .csv file format which can be opened in Microsoft Excel or Google Sheets. Here’s a brief glimpse of the returned csv: user,textCryptoEntuziast,@LunarCRUSH @zilliqa ofcourse 🚀🚀🚀😎😎😎ecossexrp1,@LunarCRUSH $VET $XRP 👌🏻crypto19711,@LunarCRUSH @DAPScoin the best privacy coin in this world! https://t.co/xFHs3cYFmKlacryptohero,@LunarCRUSH @Theta_NetworkGreenmi74576867,@LunarCRUSH https://t.co/vwmznwu77VSplendidMite,@LunarCRUSH #VeChain $VETDAPS_CLimaDelta,"@LunarCRUSH Because I am judging a project for the best technology, transparency, reliable team and dedicated commu... https://t.co/6xS9vdx1oY"DigiBur,@LunarCRUSH #digibyteM_SRHI,@LunarCRUSH $ICX 💎 $ELA 💎❤️ $NOIA💎SURAJ_041,@LunarCRUSH @electroneum #ETN .GbhoyDownUnder,@LunarCRUSH @maticnetworkjodibreeze86,@LunarCRUSH Zilliqa and Vechainghurabar1,@LunarCRUSH $EWTSamManzi,@LunarCRUSH @NoiaNetwork @NoiaFr $NOIAIamDavidGC,@LunarCRUSH Proud of DigiByte community and technology. $dgbholder2017,@LunarCRUSH @Falcon_SBS #FNT token traded on #exchanges. #Anonymous coin #FNC is not traded anywhere. connected b... https://t.co/0mz7bmaG1kLilt8888,@LunarCRUSH It would have to be $ICXCreeptwo_guy13,@LunarCRUSH That question is way too easy. Absolutely its $ICX #ICON.BitStreetSheep,@LunarCRUSH #VeChain without questionjms3333333,@LunarCRUSH LInk UBT KNC EWT SOLVEeinnorka,@LunarCRUSH DigibyteHamishDonalds0n,@LunarCRUSH $icx $vet $zil $ada $eth $linkamity3013,@LunarCRUSH $zil you know itelianhuesca,"@LunarCRUSH @decredproject by far: hybrid PoW/PoS blockchain, formal governance in place, Treasury with 10% of bloc... https://t.co/oRnMc4UD5P"AaronMilo,@LunarCRUSH #digibyte https://t.co/000HoTfLqBmajjjubu,@LunarCRUSH ChzBenjy25680913,@LunarCRUSH $LUNARCRUSHItchyTommi,@LunarCRUSH https://t.co/y8l2WwP3qK Stakenet. The one and onlysiggebaskero,@LunarCRUSH #PIVX thanks to @PIVX_Community who's doing a great job 💜 Engaging with a growing community like... https://t.co/CBlhJm7gZjDanXrp,@LunarCRUSH $VET no doubtcrypto1618,@LunarCRUSH #icxthelionshire,@LunarCRUSH ICON $icxChillMa27939777,@LunarCRUSH #Zilliqa #ZIL ✌😎BeholdTheBeard,@LunarCRUSH Tezos $XTZ Theta $THETAlennyshots,@LunarCRUSH #DigiByteShatochzi,@LunarCRUSH $CHZ #chilizRonDalton01,@LunarCRUSH #VETRealmikeleonard,@LunarCRUSH #XMR no doubt about itIncognitor00st1,@LunarCRUSH $DGB 🔥Cryptowhale10,@LunarCRUSH $ICX https://t.co/WQTbyPkpEBXxVegetta,@LunarCRUSH We are DAPS soliders I have been dedicated to our project for 2 years and I think for many years to co... https://t.co/QLk7kKJkhkCaliCryptoCo,@LunarCRUSH $ICX manMoonShotCaller,@LunarCRUSH #VeChain 💙 $VETDominic_LTC_DGB,@LunarCRUSH @DigiByteCoinGrowlerGregg,@LunarCRUSH $LINKadflondon,@LunarCRUSH We all know its $ICXSajawalOnTech,@LunarCRUSH To many projects but I guess $Wan $link $Zil $IcxIconPilipinas,@LunarCRUSH $ICXjonade,@LunarCRUSH $ZILtwills2,@LunarCRUSH Do we really have to say it...... $zil 🚀 You can view all of the code to get this working by visiting this link. import csvimport tweepyimport sslssl._create_default_https_context = ssl._create_unverified_context# Oauth keysconsumer_key = "XXX"consumer_secret = "XXX"access_token = "XXX"access_token_secret = "XXX"# Authentication with Twitterauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)# update these for the tweet you want to process replies to 'name' = the account username and you can find the tweet id within the tweet URLname = 'LunarCRUSH'tweet_id = '1270923526690664448'replies=[]for tweet in tweepy.Cursor(api.search,q='to:'+name, result_type='recent', timeout=999999).items(1000): if hasattr(tweet, 'in_reply_to_status_id_str'): if (tweet.in_reply_to_status_id_str==tweet_id): replies.append(tweet)with open('replies_clean.csv', 'w') as f: csv_writer = csv.DictWriter(f, fieldnames=('user', 'text')) csv_writer.writeheader() for tweet in replies: row = {'user': tweet.user.screen_name, 'text': tweet.text.replace('\n', ' ')} csv_writer.writerow(row) Within a few lines of code, your configurable Twitter reply scraper now pulls data from Twitter and automatically saved Tweet replies to your machine. There are a few things that can be done to improve the code, such as mapping multiple replies, or getting the responses from those that replied to the original post. Please let me know in the comments if you have any questions or suggestions. Knowledge is Power! Share your knowledge, open source your projects, participate in a community (any community!), and maybe just maybe publish a blog post about it. Thank you For Reading Constructive criticism and feedback are welcomed. Nicholas Resendez can be reached on Instagram @nirholas, on LinkedIn, and Twitter @nickresendez for updates on new articles.
[ { "code": null, "e": 353, "s": 172, "text": "Twitter is beginning to take over the social media realm. As more communities move to Twitter, we begin to see how valuable data is to advertisers, researchers, and even consumers." }, { "code": null, "e": 553, "s": 353, "text": "Data is now the next gold rush as we begin to understand how data needs to be extracted, transformed, loaded, and for full benefit, turned into Information. In theory, like gold, data is a commodity." }, { "code": null, "e": 933, "s": 553, "text": "In this article, I plan to explain how easy it is to scrape Tweets from Twitter in Python3 using Tweepy’s Twitter API. This data can be accessed by Twitter’s API and Tweepy which ended up being the most successful method. I plan to focus on scraping specific user Tweet replies, since I have not discovered any tutorials which specifically highlight how to extract Tweet replies." }, { "code": null, "e": 1162, "s": 933, "text": "If you want to jump straight into the code then you can find the full code on my Github. The Python code requires your Twitter API and consumer keys, as well as the Twitter username you plan to extract replies, and the Tweet ID." }, { "code": null, "e": 1335, "s": 1162, "text": "Make sure you have Python installed on your machine. If you do not, I suggest using Anaconda, otherwise read the official Python documentation to find additional resources." }, { "code": null, "e": 1465, "s": 1335, "text": "To perform Twitter operations from your machine, I suggest using Tweepy. To install Tweepy, navigate to your environment and run:" }, { "code": null, "e": 1474, "s": 1465, "text": "Python3:" }, { "code": null, "e": 1493, "s": 1474, "text": "pip install tweepy" }, { "code": null, "e": 1530, "s": 1493, "text": "If you’re using Anaconda for Python:" }, { "code": null, "e": 1566, "s": 1530, "text": "conda install -c conda-forge tweepy" }, { "code": null, "e": 2007, "s": 1566, "text": "If you would like to interact with Twitter from a computer or machine, you will need to apply for Twitter Developers. The application is straight forward, be honest with your intentions within the application, and you will become approved if you are deemed trustworthy from Twitter. Once approved, you will be able to create an app on the platform which provides you with credentials to authorize from Tweepy or your Python Twitter library." }, { "code": null, "e": 2205, "s": 2007, "text": "Twitter for Developers provides access to the Twitter API in order to Publish and analyze Tweets, optimize ads, and create unique customer experiences. Check out the Twitter API documentation here." }, { "code": null, "e": 2532, "s": 2205, "text": "Before you are able to use the Twitter API endpoints, create a developer account and generate your API keys. You can apply for a developer account directly here. You must answer questions on how you plan to use the API and accept the Twitter Developer Agreement, and then you will be granted access to the Developer Dashboard." }, { "code": null, "e": 2761, "s": 2532, "text": "Once you are approved access to the Developers for Twitter, log in to the developer site and create your App. This step will automatically generate your consumer API keys and access tokens, remember, you should keep them secret:" }, { "code": null, "e": 3032, "s": 2761, "text": "The developer account should be linked to the Twitter account where you want to have the bot active. From the Twitter Development platform, you are able to edit the app permissions. In my example, I have granted my app permission to read, write and send direct messages." }, { "code": null, "e": 3116, "s": 3032, "text": "We must import Tweepy then OAuth interface to collect data as well as csv, and ssl." }, { "code": null, "e": 3542, "s": 3116, "text": "import csvimport tweepyimport sslssl._create_default_https_context = ssl._create_unverified_context# Oauth keysconsumer_key = \"YOUR_CONSUMER_KEY\"consumer_secret = \"YOUR_CONSUMER_SECRET\"access_token = \"YOUR_ACCESS_TOKEN\"access_token_secret = \"YOUR_ACCESS_SECRET\"# Authentication with Twitterauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)" }, { "code": null, "e": 3719, "s": 3542, "text": "To collect tweet replies for a specific user and tweet, we must list the username of the user being scraped, as well as the Tweet ID which can be found by copying from the URL." }, { "code": null, "e": 4086, "s": 3719, "text": "# update these for whatever tweet you want to process replies toname = 'LunarCRUSH'tweet_id = '1270923526690664448'replies=[]for tweet in tweepy.Cursor(api.search,q='to:'+name, result_type='recent', timeout=999999).items(1000): if hasattr(tweet, 'in_reply_to_status_id_str'): if (tweet.in_reply_to_status_id_str==tweet_id): replies.append(tweet)" }, { "code": null, "e": 4242, "s": 4086, "text": "Since I was hoping to analyze the responses, I decided to export all replies to a .csv file format which can be opened in Microsoft Excel or Google Sheets." }, { "code": null, "e": 4286, "s": 4242, "text": "Here’s a brief glimpse of the returned csv:" }, { "code": null, "e": 7056, "s": 4286, "text": "user,textCryptoEntuziast,@LunarCRUSH @zilliqa ofcourse 🚀🚀🚀😎😎😎ecossexrp1,@LunarCRUSH $VET $XRP 👌🏻crypto19711,@LunarCRUSH @DAPScoin the best privacy coin in this world! https://t.co/xFHs3cYFmKlacryptohero,@LunarCRUSH @Theta_NetworkGreenmi74576867,@LunarCRUSH https://t.co/vwmznwu77VSplendidMite,@LunarCRUSH #VeChain $VETDAPS_CLimaDelta,\"@LunarCRUSH Because I am judging a project for the best technology, transparency, reliable team and dedicated commu... https://t.co/6xS9vdx1oY\"DigiBur,@LunarCRUSH #digibyteM_SRHI,@LunarCRUSH $ICX 💎 $ELA 💎❤️ $NOIA💎SURAJ_041,@LunarCRUSH @electroneum #ETN .GbhoyDownUnder,@LunarCRUSH @maticnetworkjodibreeze86,@LunarCRUSH Zilliqa and Vechainghurabar1,@LunarCRUSH $EWTSamManzi,@LunarCRUSH @NoiaNetwork @NoiaFr $NOIAIamDavidGC,@LunarCRUSH Proud of DigiByte community and technology. $dgbholder2017,@LunarCRUSH @Falcon_SBS #FNT token traded on #exchanges. #Anonymous coin #FNC is not traded anywhere. connected b... https://t.co/0mz7bmaG1kLilt8888,@LunarCRUSH It would have to be $ICXCreeptwo_guy13,@LunarCRUSH That question is way too easy. Absolutely its $ICX #ICON.BitStreetSheep,@LunarCRUSH #VeChain without questionjms3333333,@LunarCRUSH LInk UBT KNC EWT SOLVEeinnorka,@LunarCRUSH DigibyteHamishDonalds0n,@LunarCRUSH $icx $vet $zil $ada $eth $linkamity3013,@LunarCRUSH $zil you know itelianhuesca,\"@LunarCRUSH @decredproject by far: hybrid PoW/PoS blockchain, formal governance in place, Treasury with 10% of bloc... https://t.co/oRnMc4UD5P\"AaronMilo,@LunarCRUSH #digibyte https://t.co/000HoTfLqBmajjjubu,@LunarCRUSH ChzBenjy25680913,@LunarCRUSH $LUNARCRUSHItchyTommi,@LunarCRUSH https://t.co/y8l2WwP3qK Stakenet. The one and onlysiggebaskero,@LunarCRUSH #PIVX thanks to @PIVX_Community who's doing a great job 💜 Engaging with a growing community like... https://t.co/CBlhJm7gZjDanXrp,@LunarCRUSH $VET no doubtcrypto1618,@LunarCRUSH #icxthelionshire,@LunarCRUSH ICON $icxChillMa27939777,@LunarCRUSH #Zilliqa #ZIL ✌😎BeholdTheBeard,@LunarCRUSH Tezos $XTZ Theta $THETAlennyshots,@LunarCRUSH #DigiByteShatochzi,@LunarCRUSH $CHZ #chilizRonDalton01,@LunarCRUSH #VETRealmikeleonard,@LunarCRUSH #XMR no doubt about itIncognitor00st1,@LunarCRUSH $DGB 🔥Cryptowhale10,@LunarCRUSH $ICX https://t.co/WQTbyPkpEBXxVegetta,@LunarCRUSH We are DAPS soliders I have been dedicated to our project for 2 years and I think for many years to co... https://t.co/QLk7kKJkhkCaliCryptoCo,@LunarCRUSH $ICX manMoonShotCaller,@LunarCRUSH #VeChain 💙 $VETDominic_LTC_DGB,@LunarCRUSH @DigiByteCoinGrowlerGregg,@LunarCRUSH $LINKadflondon,@LunarCRUSH We all know its $ICXSajawalOnTech,@LunarCRUSH To many projects but I guess $Wan $link $Zil $IcxIconPilipinas,@LunarCRUSH $ICXjonade,@LunarCRUSH $ZILtwills2,@LunarCRUSH Do we really have to say it...... $zil 🚀" }, { "code": null, "e": 7128, "s": 7056, "text": "You can view all of the code to get this working by visiting this link." }, { "code": null, "e": 8210, "s": 7128, "text": "import csvimport tweepyimport sslssl._create_default_https_context = ssl._create_unverified_context# Oauth keysconsumer_key = \"XXX\"consumer_secret = \"XXX\"access_token = \"XXX\"access_token_secret = \"XXX\"# Authentication with Twitterauth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)# update these for the tweet you want to process replies to 'name' = the account username and you can find the tweet id within the tweet URLname = 'LunarCRUSH'tweet_id = '1270923526690664448'replies=[]for tweet in tweepy.Cursor(api.search,q='to:'+name, result_type='recent', timeout=999999).items(1000): if hasattr(tweet, 'in_reply_to_status_id_str'): if (tweet.in_reply_to_status_id_str==tweet_id): replies.append(tweet)with open('replies_clean.csv', 'w') as f: csv_writer = csv.DictWriter(f, fieldnames=('user', 'text')) csv_writer.writeheader() for tweet in replies: row = {'user': tweet.user.screen_name, 'text': tweet.text.replace('\\n', ' ')} csv_writer.writerow(row)" }, { "code": null, "e": 8361, "s": 8210, "text": "Within a few lines of code, your configurable Twitter reply scraper now pulls data from Twitter and automatically saved Tweet replies to your machine." }, { "code": null, "e": 8604, "s": 8361, "text": "There are a few things that can be done to improve the code, such as mapping multiple replies, or getting the responses from those that replied to the original post. Please let me know in the comments if you have any questions or suggestions." }, { "code": null, "e": 8769, "s": 8604, "text": "Knowledge is Power! Share your knowledge, open source your projects, participate in a community (any community!), and maybe just maybe publish a blog post about it." }, { "code": null, "e": 8791, "s": 8769, "text": "Thank you For Reading" } ]
PyQt - QMessageBox
QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number. Important methods and enumerations associated with QMessageBox class are given in the following table − setIcon() Displays predefined icon corresponding to severity of the message Question Information Warning Critical setText() Sets the text of the main message to be displayed setInformativeText() Displays additional information setDetailText() Dialog shows a Details button. This text appears on clicking it setTitle() Displays the custom title of dialog setStandardButtons() List of standard buttons to be displayed. Each button is associated with QMessageBox.Ok 0x00000400 QMessageBox.Open 0x00002000 QMessageBox.Save 0x00000800 QMessageBox.Cancel 0x00400000 QMessageBox.Close 0x00200000 QMessageBox.Yes 0x00004000 QMessageBox.No 0x00010000 QMessageBox.Abort 0x00040000 QMessageBox.Retry 0x00080000 QMessageBox.Ignore 0x00100000 setDefaultButton() Sets the button as default. It emits the clicked signal if Enter is pressed setEscapeButton() Sets the button to be treated as clicked if the escape key is pressed In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog. msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("This is a message box") msg.setInformativeText("This is additional information") msg.setWindowTitle("MessageBox demo") msg.setDetailedText("The details are as follows:") setStandardButton() function displays desired buttons. msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal. msg.buttonClicked.connect(msgbtn) The complete code for the example is as follows − import sys from PyQt4.QtGui import * from PyQt4.QtCore import * def window(): app = QApplication(sys.argv) w = QWidget() b = QPushButton(w) b.setText("Show message!") b.move(50,50) b.clicked.connect(showdialog) w.setWindowTitle("PyQt Dialog demo") w.show() sys.exit(app.exec_()) def showdialog(): msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("This is a message box") msg.setInformativeText("This is additional information") msg.setWindowTitle("MessageBox demo") msg.setDetailedText("The details are as follows:") msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msg.buttonClicked.connect(msgbtn) retval = msg.exec_() print "value of pressed message box button:", retval def msgbtn(i): print "Button pressed is:",i.text() if __name__ == '__main__': window() The above code produces the following output − 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2197, "s": 1926, "text": "QMessageBox is a commonly used modal dialog to display some informational message and optionally ask the user to respond by clicking any one of the standard buttons on it. Each standard button has a predefined caption, a role and returns a predefined hexadecimal number." }, { "code": null, "e": 2301, "s": 2197, "text": "Important methods and enumerations associated with QMessageBox class are given in the following table −" }, { "code": null, "e": 2311, "s": 2301, "text": "setIcon()" }, { "code": null, "e": 2377, "s": 2311, "text": "Displays predefined icon corresponding to severity of the message" }, { "code": null, "e": 2387, "s": 2377, "text": " Question" }, { "code": null, "e": 2400, "s": 2387, "text": " Information" }, { "code": null, "e": 2409, "s": 2400, "text": " Warning" }, { "code": null, "e": 2419, "s": 2409, "text": " Critical" }, { "code": null, "e": 2429, "s": 2419, "text": "setText()" }, { "code": null, "e": 2479, "s": 2429, "text": "Sets the text of the main message to be displayed" }, { "code": null, "e": 2500, "s": 2479, "text": "setInformativeText()" }, { "code": null, "e": 2532, "s": 2500, "text": "Displays additional information" }, { "code": null, "e": 2548, "s": 2532, "text": "setDetailText()" }, { "code": null, "e": 2612, "s": 2548, "text": "Dialog shows a Details button. This text appears on clicking it" }, { "code": null, "e": 2623, "s": 2612, "text": "setTitle()" }, { "code": null, "e": 2659, "s": 2623, "text": "Displays the custom title of dialog" }, { "code": null, "e": 2680, "s": 2659, "text": "setStandardButtons()" }, { "code": null, "e": 2753, "s": 2680, "text": "List of standard buttons to be displayed. Each button is associated with" }, { "code": null, "e": 2779, "s": 2753, "text": "QMessageBox.Ok 0x00000400" }, { "code": null, "e": 2807, "s": 2779, "text": "QMessageBox.Open 0x00002000" }, { "code": null, "e": 2835, "s": 2807, "text": "QMessageBox.Save 0x00000800" }, { "code": null, "e": 2865, "s": 2835, "text": "QMessageBox.Cancel 0x00400000" }, { "code": null, "e": 2894, "s": 2865, "text": "QMessageBox.Close 0x00200000" }, { "code": null, "e": 2921, "s": 2894, "text": "QMessageBox.Yes 0x00004000" }, { "code": null, "e": 2947, "s": 2921, "text": "QMessageBox.No 0x00010000" }, { "code": null, "e": 2976, "s": 2947, "text": "QMessageBox.Abort 0x00040000" }, { "code": null, "e": 3005, "s": 2976, "text": "QMessageBox.Retry 0x00080000" }, { "code": null, "e": 3035, "s": 3005, "text": "QMessageBox.Ignore 0x00100000" }, { "code": null, "e": 3054, "s": 3035, "text": "setDefaultButton()" }, { "code": null, "e": 3130, "s": 3054, "text": "Sets the button as default. It emits the clicked signal if Enter is pressed" }, { "code": null, "e": 3148, "s": 3130, "text": "setEscapeButton()" }, { "code": null, "e": 3218, "s": 3148, "text": "Sets the button to be treated as clicked if the escape key is pressed" }, { "code": null, "e": 3351, "s": 3218, "text": "In the following example, click signal of the button on the top level window, the connected function displays the messagebox dialog." }, { "code": null, "e": 3592, "s": 3351, "text": "msg = QMessageBox()\nmsg.setIcon(QMessageBox.Information)\nmsg.setText(\"This is a message box\")\nmsg.setInformativeText(\"This is additional information\")\nmsg.setWindowTitle(\"MessageBox demo\")\nmsg.setDetailedText(\"The details are as follows:\")\n" }, { "code": null, "e": 3647, "s": 3592, "text": "setStandardButton() function displays desired buttons." }, { "code": null, "e": 3708, "s": 3647, "text": "msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n" }, { "code": null, "e": 3818, "s": 3708, "text": "buttonClicked() signal is connected to a slot function, which identifies the caption of source of the signal." }, { "code": null, "e": 3853, "s": 3818, "text": "msg.buttonClicked.connect(msgbtn)\n" }, { "code": null, "e": 3903, "s": 3853, "text": "The complete code for the example is as follows −" }, { "code": null, "e": 4770, "s": 3903, "text": "import sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\ndef window():\n app = QApplication(sys.argv)\n w = QWidget()\n b = QPushButton(w)\n b.setText(\"Show message!\")\n\n b.move(50,50)\n b.clicked.connect(showdialog)\n w.setWindowTitle(\"PyQt Dialog demo\")\n w.show()\n sys.exit(app.exec_())\n\t\ndef showdialog():\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n\n msg.setText(\"This is a message box\")\n msg.setInformativeText(\"This is additional information\")\n msg.setWindowTitle(\"MessageBox demo\")\n msg.setDetailedText(\"The details are as follows:\")\n msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n msg.buttonClicked.connect(msgbtn)\n\t\n retval = msg.exec_()\n print \"value of pressed message box button:\", retval\n\t\ndef msgbtn(i):\n print \"Button pressed is:\",i.text()\n\t\nif __name__ == '__main__': \n window()" }, { "code": null, "e": 4817, "s": 4770, "text": "The above code produces the following output −" }, { "code": null, "e": 4854, "s": 4817, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 4864, "s": 4854, "text": " ALAA EID" }, { "code": null, "e": 4871, "s": 4864, "text": " Print" }, { "code": null, "e": 4882, "s": 4871, "text": " Add Notes" } ]
Why do we use $rootScope.$broadcast in AngularJS? - GeeksforGeeks
30 Jan, 2020 $rootScope.$broadcast is used to broadcast a “global” event which can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.$on. Syntax: $rootScope.$broadcast(name, args) $scope.$on(name, listener); where listener specifies the function to call when the event is caught. Approach: Create a ParentController from which you would want to raise/broadcast an event. Use $rootScope.$broadcast in AngularJS to broadcast the event from the ParentController. Create a ChildController or an ExternalController (i.e., not a direct descendant of the ParentController) to catch and handle the event. Use $scope.$on in AngularJS to catch the respective event. Example: This program uses $rootScope.$broadcast to raise an event using the approach discussed above. <!DOCTYPE html><html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.js"> </script> <script type="text/javascript"> var app = angular.module('app', []); app.controller('ParentController', function( $rootScope, $scope) { $scope.broadcastMessage = function() { $rootScope.$broadcast('newEvent', { message: $scope.parentMessage }); }; }); app.controller('ChildController', function($scope) { $scope.$on('newEvent', function(event, args) { $scope.message = args.message; }); }); app.controller('ExternalController', function($scope) { $scope.$on('newEvent', function(event, args) { $scope.message = args.message; }); }); </script> <style type="text/css"> h1, code { color: green; } p { color: green; display: inline-block; } div { border-color: black; border-style: solid; padding: 10px; } </style></head> <body ng-app="app"> <div ng-controller="ParentController"> <h1>Parent Controller</h1> <input ng-model="parentMessage"> <button ng-click="broadcastMessage()"> Broadcast Message </button> <br> <br> <div ng-controller="ChildController"> <h1>Child Controller</h1> <p>Message :</p> <code>{{message}}</code> </div> </div> <br> <br> <div ng-controller="ExternalController"> <h1>External Controller</h1> <p>Message :</p> <code>{{message}}</code> </div></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. Top 10 Angular Libraries For Web Developers Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25109, "s": 25081, "text": "\n30 Jan, 2020" }, { "code": null, "e": 25306, "s": 25109, "text": "$rootScope.$broadcast is used to broadcast a “global” event which can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.$on." }, { "code": null, "e": 25314, "s": 25306, "text": "Syntax:" }, { "code": null, "e": 25378, "s": 25314, "text": "$rootScope.$broadcast(name, args)\n\n$scope.$on(name, listener);\n" }, { "code": null, "e": 25450, "s": 25378, "text": "where listener specifies the function to call when the event is caught." }, { "code": null, "e": 25460, "s": 25450, "text": "Approach:" }, { "code": null, "e": 25541, "s": 25460, "text": "Create a ParentController from which you would want to raise/broadcast an event." }, { "code": null, "e": 25630, "s": 25541, "text": "Use $rootScope.$broadcast in AngularJS to broadcast the event from the ParentController." }, { "code": null, "e": 25767, "s": 25630, "text": "Create a ChildController or an ExternalController (i.e., not a direct descendant of the ParentController) to catch and handle the event." }, { "code": null, "e": 25826, "s": 25767, "text": "Use $scope.$on in AngularJS to catch the respective event." }, { "code": null, "e": 25929, "s": 25826, "text": "Example: This program uses $rootScope.$broadcast to raise an event using the approach discussed above." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"http://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.js\"> </script> <script type=\"text/javascript\"> var app = angular.module('app', []); app.controller('ParentController', function( $rootScope, $scope) { $scope.broadcastMessage = function() { $rootScope.$broadcast('newEvent', { message: $scope.parentMessage }); }; }); app.controller('ChildController', function($scope) { $scope.$on('newEvent', function(event, args) { $scope.message = args.message; }); }); app.controller('ExternalController', function($scope) { $scope.$on('newEvent', function(event, args) { $scope.message = args.message; }); }); </script> <style type=\"text/css\"> h1, code { color: green; } p { color: green; display: inline-block; } div { border-color: black; border-style: solid; padding: 10px; } </style></head> <body ng-app=\"app\"> <div ng-controller=\"ParentController\"> <h1>Parent Controller</h1> <input ng-model=\"parentMessage\"> <button ng-click=\"broadcastMessage()\"> Broadcast Message </button> <br> <br> <div ng-controller=\"ChildController\"> <h1>Child Controller</h1> <p>Message :</p> <code>{{message}}</code> </div> </div> <br> <br> <div ng-controller=\"ExternalController\"> <h1>External Controller</h1> <p>Message :</p> <code>{{message}}</code> </div></body> </html>", "e": 27738, "s": 25929, "text": null }, { "code": null, "e": 27746, "s": 27738, "text": "Output:" }, { "code": null, "e": 27761, "s": 27746, "text": "AngularJS-Misc" }, { "code": null, "e": 27768, "s": 27761, "text": "Picked" }, { "code": null, "e": 27778, "s": 27768, "text": "AngularJS" }, { "code": null, "e": 27795, "s": 27778, "text": "Web Technologies" }, { "code": null, "e": 27893, "s": 27795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27937, "s": 27893, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 27972, "s": 27937, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27996, "s": 27972, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28049, "s": 27996, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28098, "s": 28049, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 28140, "s": 28098, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28173, "s": 28140, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28216, "s": 28173, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28278, "s": 28216, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Aurelia - Component Lifecycle
Aurelia uses component lifecycle methods to manipulate the component lifecycle. In this chapter, we will show you those methods and explain the component lifecycle. constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used. constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used. created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView). created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView). bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties. bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties. attached() − Attached method is invoked once the component is attached to the DOM. attached() − Attached method is invoked once the component is attached to the DOM. detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM. detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM. unbind() − The last lifecycle method is unbind. It is called when the component is unbound. unbind() − The last lifecycle method is unbind. It is called when the component is unbound. The lifecycle methods are useful when you want to have higher control over your component. You can use them when you need to trigger some functionalities at certain point of component lifecycle. All lifecycle methods are shown below. export class App { constructor(argument) { // Create and initialize your class object here... } created(owningView, myView) { // Invoked once the component is created... } bind(bindingContext, overrideContext) { // Invoked once the databinding is activated... } attached(argument) { // Invoked once the component is attached to the DOM... } detached(argument) { // Invoked when component is detached from the dom } unbind(argument) { // Invoked when component is unbound... } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2330, "s": 2165, "text": "Aurelia uses component lifecycle methods to manipulate the component lifecycle. In this chapter, we will show you those methods and explain the component lifecycle." }, { "code": null, "e": 2523, "s": 2330, "text": "constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used." }, { "code": null, "e": 2716, "s": 2523, "text": "constructor() − Constructor method is used for initializing an object created with a class. This method is called first. If you don't specify this method, the default constructor will be used." }, { "code": null, "e": 2987, "s": 2716, "text": "created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView)." }, { "code": null, "e": 3258, "s": 2987, "text": "created(owningView, myView) − This is called once the view and view-model are created and connected to the controller. This method takes two arguments. The first one is the view where the component is declared (owningView). The second one is the component view (myView)." }, { "code": null, "e": 3516, "s": 3258, "text": "bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties." }, { "code": null, "e": 3774, "s": 3516, "text": "bind(bindingContext, overrideContext) − At this point of time, the binding has started. The first argument represents the binding context of the component. The second one is overrideContext. This argument is used for adding additional contextual properties." }, { "code": null, "e": 3857, "s": 3774, "text": "attached() − Attached method is invoked once the component is attached to the DOM." }, { "code": null, "e": 3940, "s": 3857, "text": "attached() − Attached method is invoked once the component is attached to the DOM." }, { "code": null, "e": 4048, "s": 3940, "text": "detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM." }, { "code": null, "e": 4156, "s": 4048, "text": "detached() − This method is opposite to attached. It is invoked when the component is removed from the DOM." }, { "code": null, "e": 4248, "s": 4156, "text": "unbind() − The last lifecycle method is unbind. It is called when the component is unbound." }, { "code": null, "e": 4340, "s": 4248, "text": "unbind() − The last lifecycle method is unbind. It is called when the component is unbound." }, { "code": null, "e": 4535, "s": 4340, "text": "The lifecycle methods are useful when you want to have higher control over your component. You can use them when you need to trigger some functionalities at certain point of component lifecycle." }, { "code": null, "e": 4574, "s": 4535, "text": "All lifecycle methods are shown below." }, { "code": null, "e": 5129, "s": 4574, "text": "export class App {\n constructor(argument) {\n // Create and initialize your class object here...\n }\n\n created(owningView, myView) {\n // Invoked once the component is created...\n }\n\n bind(bindingContext, overrideContext) {\n // Invoked once the databinding is activated...\n }\n\n attached(argument) {\n // Invoked once the component is attached to the DOM...\n }\n\n detached(argument) {\n // Invoked when component is detached from the dom\n }\n\n unbind(argument) {\n // Invoked when component is unbound...\n }\n}" }, { "code": null, "e": 5136, "s": 5129, "text": " Print" }, { "code": null, "e": 5147, "s": 5136, "text": " Add Notes" } ]
How to use Python object in C++?
Here is an example in which a simple Python object is wrapped and embedded. We are using .c for this, c++ has similar steps − class PyClass(object): def __init__(self): self.data = [] def add(self, val): self.data.append(val) def __str__(self): return "Data: " + str(self.data) cdef public object createPyClass(): return PyClass() cdef public void addData(object p, int val): p.add(val) cdef public char* printCls(object p): return bytes(str(p), encoding = 'utf-8') We compile with cython pycls.pyx (use --cplus for c++) to generate a .c and .h file containing the source and the function declarations respectively. We now create a main.c file that starts up Python and we are ready to call these functions − #include "Python.h" // Python.h always gets included first. #include "pycls.h" // Include your header file. int main(int argc, char *argv[]){ Py_Initialize(); // initialize Python PyInit_pycls(); // initialize module (initpycls(); in Py2) PyObject *obj = createPyClass(); for(int i=0; i<10; i++){ addData(obj, i); } printf("%s\n", printCls(obj)); Py_Finalize(); return 0; } Compiling this with the proper flags (which you can obtain from python3.5-config of python-config [Py2]) − gcc pycls.c main.c -L$(python3.5-config --cflags) -I$(python3.5-config --ldflags) -std=c99 will create our executable which interacts with our object − ./a.out Data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] All this was done by using Cython along with the public keyword that generates the .h header file. We could alternatively just compile a python module with Cython and create the header/handle the additional boilerplate ourself.
[ { "code": null, "e": 1189, "s": 1062, "text": "Here is an example in which a simple Python object is wrapped and embedded. We are using .c for this, c++ has similar steps −" }, { "code": null, "e": 1577, "s": 1189, "text": "class PyClass(object):\n def __init__(self):\n self.data = []\n def add(self, val):\n self.data.append(val)\n def __str__(self):\n return \"Data: \" + str(self.data)\ncdef public object createPyClass():\n return PyClass()\ncdef public void addData(object p, int val):\n p.add(val)\ncdef public char* printCls(object p):\n return bytes(str(p), encoding = 'utf-8')" }, { "code": null, "e": 1820, "s": 1577, "text": "We compile with cython pycls.pyx (use --cplus for c++) to generate a .c and .h file containing the source and the function declarations respectively. We now create a main.c file that starts up Python and we are ready to call these functions −" }, { "code": null, "e": 2244, "s": 1820, "text": "#include \"Python.h\" // Python.h always gets included first.\n#include \"pycls.h\" // Include your header file.\nint main(int argc, char *argv[]){\n Py_Initialize(); // initialize Python\n PyInit_pycls(); // initialize module (initpycls(); in Py2)\n PyObject *obj = createPyClass();\n for(int i=0; i<10; i++){\n addData(obj, i);\n }\n printf(\"%s\\n\", printCls(obj));\n Py_Finalize();\n return 0;\n}" }, { "code": null, "e": 2351, "s": 2244, "text": "Compiling this with the proper flags (which you can obtain from python3.5-config of python-config [Py2]) −" }, { "code": null, "e": 2442, "s": 2351, "text": "gcc pycls.c main.c -L$(python3.5-config --cflags) -I$(python3.5-config --ldflags) -std=c99" }, { "code": null, "e": 2503, "s": 2442, "text": "will create our executable which interacts with our object −" }, { "code": null, "e": 2548, "s": 2503, "text": "./a.out\nData: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" }, { "code": null, "e": 2776, "s": 2548, "text": "All this was done by using Cython along with the public keyword that generates the .h header file. We could alternatively just compile a python module with Cython and create the header/handle the additional boilerplate ourself." } ]
Programmatic Transaction Management
Programmatic transaction management approach allows you to manage the transaction with the help of programming in your source code. That gives you extreme flexibility, but it is difficult to maintain. Before we begin, it is important to have at least two database tables on which we can perform various CRUD operations with the help of transactions. Let us consider a Student table, which can be created in MySQL TEST database with the following DDL − CREATE TABLE Student( ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID) ); Second table is Marks in which we will maintain marks for students based on years. Here SID is the foreign key for Student table. CREATE TABLE Marks( SID INT NOT NULL, MARKS INT NOT NULL, YEAR INT NOT NULL ); Let us use PlatformTransactionManager directly to implement the programmatic approach to implement transactions. To start a new transaction, you need to have a instance of TransactionDefinition with the appropriate transaction attributes. For this example, we will simply create an instance ofDefaultTransactionDefinition to use the default transaction attributes. Once the TransactionDefinition is created, you can start your transaction by calling getTransaction() method, which returns an instance of TransactionStatus. The TransactionStatus objects helps in tracking the current status of the transaction and finally, if everything goes fine, you can use commit() method of PlatformTransactionManager to commit the transaction, otherwise you can use rollback() to rollback the complete operation. Now, let us write our Spring JDBC application which will implement simple operations on Student and Marks tables. Let us have a working Eclipse IDE in place and take 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 create * a record in the Student and Marks tables. */ public void create(String name, Integer age, Integer marks, Integer year); /** * This is the method to be used to list down * all the records from the Student and Marks tables. */ public List<StudentMarks> listStudents(); } Following is the content of the StudentMarks.java file package com.tutorialspoint; public class StudentMarks { private Integer age; private String name; private Integer id; private Integer marks; private Integer year; private Integer sid; 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; } public void setMarks(Integer marks) { this.marks = marks; } public Integer getMarks() { return marks; } public void setYear(Integer year) { this.year = year; } public Integer getYear() { return year; } public void setSid(Integer sid) { this.sid = sid; } public Integer getSid() { return sid; } } Following is the content of the StudentMarksMapper.java file package com.tutorialspoint; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class StudentMarksMapper implements RowMapper<StudentMarks> { public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException { StudentMarks studentMarks = new StudentMarks(); studentMarks.setId(rs.getInt("id")); studentMarks.setName(rs.getString("name")); studentMarks.setAge(rs.getInt("age")); studentMarks.setSid(rs.getInt("sid")); studentMarks.setMarks(rs.getInt("marks")); studentMarks.setYear(rs.getInt("year")); return studentMarks; } } 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.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; public class StudentJDBCTemplate implements StudentDAO { private DataSource dataSource; private JdbcTemplate jdbcTemplateObject; private PlatformTransactionManager transactionManager; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplateObject = new JdbcTemplate(dataSource); } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public void create(String name, Integer age, Integer marks, Integer year){ TransactionDefinition def = new DefaultTransactionDefinition(); TransactionStatus status = transactionManager.getTransaction(def); try { String SQL1 = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL1, name, age); // Get the latest student id to be used in Marks table String SQL2 = "select max(id) from Student"; int sid = jdbcTemplateObject.queryForInt( SQL2 ); String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)"; jdbcTemplateObject.update( SQL3, sid, marks, year); System.out.println("Created Name = " + name + ", Age = " + age); transactionManager.commit(status); } catch (DataAccessException e) { System.out.println("Error in creating record, rolling back"); transactionManager.rollback(status); throw e; } return; } public List<StudentMarks> listStudents() { String SQL = "select * from Student, Marks where Student.id=Marks.sid"; List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, new StudentMarksMapper()); return studentMarks; } } Now let us move with the main application file MainApp.java, which is as follows − 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("------Records creation--------" ); studentJDBCTemplate.create("Zara", 11, 99, 2010); studentJDBCTemplate.create("Nuha", 20, 97, 2010); studentJDBCTemplate.create("Ayan", 25, 100, 2011); System.out.println("------Listing all the records--------" ); List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents(); for (StudentMarks record : studentMarks) { System.out.print("ID : " + record.getId() ); System.out.print(", Name : " + record.getName() ); System.out.print(", Marks : " + record.getMarks()); System.out.print(", Year : " + record.getYear()); System.out.println(", Age : " + record.getAge()); } } } Following is the configuration file Beans.xml <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <!-- Initialization for data source --> <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/> <property name = "username" value = "root"/> <property name = "password" value = "password"/> </bean> <!-- Initialization for TransactionManager --> <bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name = "dataSource" ref = "dataSource" /> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id = "studentJDBCTemplate" class = "com.tutorialspoint.StudentJDBCTemplate"> <property name = "dataSource" ref = "dataSource" /> <property name = "transactionManager" ref = "transactionManager" /> </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 − ------Records creation-------- Created Name = Zara, Age = 11 Created Name = Nuha, Age = 20 Created Name = Ayan, Age = 25 ------Listing all the records-------- ID : 1, Name : Zara, Marks : 99, Year : 2010, Age : 11 ID : 2, Name : Nuha, Marks : 97, Year : 2010, Age : 20 ID : 3, Name : Ayan, Marks : 100, Year : 2011, Age : 25 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2493, "s": 2292, "text": "Programmatic transaction management approach allows you to manage the transaction with the help of programming in your source code. That gives you extreme flexibility, but it is difficult to maintain." }, { "code": null, "e": 2744, "s": 2493, "text": "Before we begin, it is important to have at least two database tables on which we can perform various CRUD operations with the help of transactions. Let us consider a Student table, which can be created in MySQL TEST database with the following DDL −" }, { "code": null, "e": 2878, "s": 2744, "text": "CREATE TABLE Student(\n ID INT NOT NULL AUTO_INCREMENT,\n NAME VARCHAR(20) NOT NULL,\n AGE INT NOT NULL,\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 3008, "s": 2878, "text": "Second table is Marks in which we will maintain marks for students based on years. Here SID is the foreign key for Student table." }, { "code": null, "e": 3099, "s": 3008, "text": "CREATE TABLE Marks(\n SID INT NOT NULL,\n MARKS INT NOT NULL,\n YEAR INT NOT NULL\n);" }, { "code": null, "e": 3464, "s": 3099, "text": "Let us use PlatformTransactionManager directly to implement the programmatic approach to implement transactions. To start a new transaction, you need to have a instance of TransactionDefinition with the appropriate transaction attributes. For this example, we will simply create an instance ofDefaultTransactionDefinition to use the default transaction attributes." }, { "code": null, "e": 3900, "s": 3464, "text": "Once the TransactionDefinition is created, you can start your transaction by calling getTransaction() method, which returns an instance of TransactionStatus. The TransactionStatus objects helps in tracking the current status of the transaction and finally, if everything goes fine, you can use commit() method of PlatformTransactionManager to commit the transaction, otherwise you can use rollback() to rollback the complete operation." }, { "code": null, "e": 4119, "s": 3900, "text": "Now, let us write our Spring JDBC application which will implement simple operations on Student and Marks tables. Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −" }, { "code": null, "e": 4201, "s": 4119, "text": "Following is the content of the Data Access Object interface file StudentDAO.java" }, { "code": null, "e": 4836, "s": 4201, "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 create\n * a record in the Student and Marks tables.\n */\n public void create(String name, Integer age, Integer marks, Integer year);\n \n /** \n * This is the method to be used to list down\n * all the records from the Student and Marks tables.\n */\n public List<StudentMarks> listStudents();\n}" }, { "code": null, "e": 4891, "s": 4836, "text": "Following is the content of the StudentMarks.java file" }, { "code": null, "e": 5809, "s": 4891, "text": "package com.tutorialspoint;\n\npublic class StudentMarks {\n private Integer age;\n private String name;\n private Integer id;\n private Integer marks;\n private Integer year;\n private Integer sid;\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 public void setMarks(Integer marks) {\n this.marks = marks;\n }\n public Integer getMarks() {\n return marks;\n }\n public void setYear(Integer year) {\n this.year = year;\n }\n public Integer getYear() {\n return year;\n }\n public void setSid(Integer sid) {\n this.sid = sid;\n }\n public Integer getSid() {\n return sid;\n }\n}" }, { "code": null, "e": 5870, "s": 5809, "text": "Following is the content of the StudentMarksMapper.java file" }, { "code": null, "e": 6520, "s": 5870, "text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMarksMapper implements RowMapper<StudentMarks> {\n public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {\n StudentMarks studentMarks = new StudentMarks();\n studentMarks.setId(rs.getInt(\"id\"));\n studentMarks.setName(rs.getString(\"name\"));\n studentMarks.setAge(rs.getInt(\"age\"));\n studentMarks.setSid(rs.getInt(\"sid\"));\n studentMarks.setMarks(rs.getInt(\"marks\"));\n studentMarks.setYear(rs.getInt(\"year\"));\n\n return studentMarks;\n }\n}" }, { "code": null, "e": 6629, "s": 6520, "text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO" }, { "code": null, "e": 8858, "s": 6629, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\nimport org.springframework.dao.DataAccessException;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.transaction.PlatformTransactionManager;\nimport org.springframework.transaction.TransactionDefinition;\nimport org.springframework.transaction.TransactionStatus;\nimport org.springframework.transaction.support.DefaultTransactionDefinition;\n\npublic class StudentJDBCTemplate implements StudentDAO {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n private PlatformTransactionManager transactionManager;\n\n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n }\n public void setTransactionManager(PlatformTransactionManager transactionManager) {\n this.transactionManager = transactionManager;\n }\n public void create(String name, Integer age, Integer marks, Integer year){\n TransactionDefinition def = new DefaultTransactionDefinition();\n TransactionStatus status = transactionManager.getTransaction(def);\n\n try {\n String SQL1 = \"insert into Student (name, age) values (?, ?)\";\n jdbcTemplateObject.update( SQL1, name, age);\n\n // Get the latest student id to be used in Marks table\n String SQL2 = \"select max(id) from Student\";\n int sid = jdbcTemplateObject.queryForInt( SQL2 );\n\n String SQL3 = \"insert into Marks(sid, marks, year) \" + \"values (?, ?, ?)\";\n jdbcTemplateObject.update( SQL3, sid, marks, year);\n\n System.out.println(\"Created Name = \" + name + \", Age = \" + age);\n transactionManager.commit(status);\n } \n catch (DataAccessException e) {\n System.out.println(\"Error in creating record, rolling back\");\n transactionManager.rollback(status);\n throw e;\n }\n return;\n }\n public List<StudentMarks> listStudents() {\n String SQL = \"select * from Student, Marks where Student.id=Marks.sid\";\n List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, \n new StudentMarksMapper());\n \n return studentMarks;\n }\n}" }, { "code": null, "e": 8941, "s": 8858, "text": "Now let us move with the main application file MainApp.java, which is as follows −" }, { "code": null, "e": 10187, "s": 8941, "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 = \n (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n \n System.out.println(\"------Records creation--------\" );\n studentJDBCTemplate.create(\"Zara\", 11, 99, 2010);\n studentJDBCTemplate.create(\"Nuha\", 20, 97, 2010);\n studentJDBCTemplate.create(\"Ayan\", 25, 100, 2011);\n\n System.out.println(\"------Listing all the records--------\" );\n List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();\n \n for (StudentMarks record : studentMarks) {\n System.out.print(\"ID : \" + record.getId() );\n System.out.print(\", Name : \" + record.getName() );\n System.out.print(\", Marks : \" + record.getMarks());\n System.out.print(\", Year : \" + record.getYear());\n System.out.println(\", Age : \" + record.getAge());\n }\n }\n}" }, { "code": null, "e": 10233, "s": 10187, "text": "Following is the configuration file Beans.xml" }, { "code": null, "e": 11503, "s": 10233, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"password\"/>\n </bean>\n\n <!-- Initialization for TransactionManager -->\n <bean id = \"transactionManager\" \n class = \"org.springframework.jdbc.datasource.DataSourceTransactionManager\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\"\n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" />\n <property name = \"transactionManager\" ref = \"transactionManager\" /> \n </bean>\n \n</beans>" }, { "code": null, "e": 11682, "s": 11503, "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": 12008, "s": 11682, "text": "------Records creation--------\nCreated Name = Zara, Age = 11\nCreated Name = Nuha, Age = 20\nCreated Name = Ayan, Age = 25\n------Listing all the records--------\nID : 1, Name : Zara, Marks : 99, Year : 2010, Age : 11\nID : 2, Name : Nuha, Marks : 97, Year : 2010, Age : 20\nID : 3, Name : Ayan, Marks : 100, Year : 2011, Age : 25\n" }, { "code": null, "e": 12042, "s": 12008, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 12056, "s": 12042, "text": " Karthikeya T" }, { "code": null, "e": 12089, "s": 12056, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 12104, "s": 12089, "text": " Chaand Sheikh" }, { "code": null, "e": 12139, "s": 12104, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12151, "s": 12139, "text": " Senol Atac" }, { "code": null, "e": 12186, "s": 12151, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12198, "s": 12186, "text": " Senol Atac" }, { "code": null, "e": 12233, "s": 12198, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12245, "s": 12233, "text": " Senol Atac" }, { "code": null, "e": 12278, "s": 12245, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 12290, "s": 12278, "text": " Senol Atac" }, { "code": null, "e": 12297, "s": 12290, "text": " Print" }, { "code": null, "e": 12308, "s": 12297, "text": " Add Notes" } ]
How to connect to Derby database using a JDBC program?
Apache Derby is a Relational Database Management System which is fully based on (written/implemented in) Java programming language. It is an open source database developed by Apache Software Foundation. Follow the steps given below to install derby: Visit the home page of Apache Derby home page https://db.apache.org/derby/. Click the Download tab. Visit the home page of Apache Derby home page https://db.apache.org/derby/. Click the Download tab. Select and click on the link of the latest version of Apache Derby. Select and click on the link of the latest version of Apache Derby. On clicking the selected link, you will be redirected to the Distributions page of apache derby. If you observe here, derby provides distributions namely, db-derby-bin, db-derbylib.zip, db-derby-lib-debug.zip, and db-derby-src.zip. On clicking the selected link, you will be redirected to the Distributions page of apache derby. If you observe here, derby provides distributions namely, db-derby-bin, db-derbylib.zip, db-derby-lib-debug.zip, and db-derby-src.zip. Download the db-derby-bin folder. Copy its contents to a separate folder where you wanted to install Apache Derby. (for example, say C:\Derby) Download the db-derby-bin folder. Copy its contents to a separate folder where you wanted to install Apache Derby. (for example, say C:\Derby) Now, to work with Derby, Make sure that you already have set the JAVA_HOME variable by passing the location of bin folder of Java Installation folder, and include the JAVA_HOME/bin in the PATH variable. Create a new environment variable, DERBY_HOME with value C:\Derby. The bin folder of db-derby-bin distributions (we changed it as C:\Derby\bin) contains all the required jar files. Following JDBC program establishes connection with Apache derby database, creates a table named employeedata, inserts records into it, retrieves and displays the contents of the table. public class InsertData { public static void main(String args[]) throws Exception { //Registering the driver Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); //Getting the Connection object String URL = "jdbc:derby:mydatabs;create=true"; Connection conn = DriverManager.getConnection(URL); //Creating the Statement object Statement stmt = conn.createStatement(); //Creating a table in Derby database String query = "CREATE TABLE EmployeeData( " + "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, " + "Name VARCHAR(255), " + "Salary INT NOT NULL, " + "Location VARCHAR(255), " + "PRIMARY KEY (Id))"; stmt.execute(query); System.out.println("Table created"); //Inserting data query = "INSERT INTO EmployeeData(" + "Name, Salary, Location) VALUES " + "('Amit', 30000, 'Hyderabad'), " + "('Kalyan', 40000, 'Vishakhapatnam'), " + "('Renuka', 50000, 'Delhi'), " + "('Archana', 15000, 'Mumbai'), " + "('Trupthi', 45000, 'Kochin'), " + "('Suchatra', 33000, 'Pune'), " + "('Rahul', 39000, 'Lucknow'), " + "('Trupthi', 45000, 'Kochin')"; stmt.execute(query); System.out.println("Values inserted"); //Retrieving data ResultSet rs = stmt.executeQuery("Select * from EmployeeData"); System.out.println("Contents of the table EmployeeData table:"); while(rs.next()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("Name")+", "); System.out.print("Salary: "+rs.getInt("Salary")+", "); System.out.print("Location: "+rs.getString("Location")); System.out.println(); } } } Table created Values inserted Contents of the table EmployeeData table: ID: 1, Name: Amit, Salary: 30000, Location: Hyderabad ID: 2, Name: Kalyan, Salary: 40000, Location: Vishakhapatnam ID: 3, Name: Renuka, Salary: 50000, Location: Delhi ID: 4, Name: Archana, Salary: 15000, Location: Mumbai ID: 5, Name: Trupthi, Salary: 45000, Location: Kochin ID: 6, Name: Suchatra, Salary: 33000, Location: Pune ID: 7, Name: Rahul, Salary: 39000, Location: Lucknow ID: 8, Name: Trupthi, Salary: 45000, Location: Kochin
[ { "code": null, "e": 1265, "s": 1062, "text": "Apache Derby is a Relational Database Management System which is fully based on (written/implemented in) Java programming language. It is an open source database developed by Apache Software Foundation." }, { "code": null, "e": 1312, "s": 1265, "text": "Follow the steps given below to install derby:" }, { "code": null, "e": 1412, "s": 1312, "text": "Visit the home page of Apache Derby home page https://db.apache.org/derby/. Click the Download tab." }, { "code": null, "e": 1512, "s": 1412, "text": "Visit the home page of Apache Derby home page https://db.apache.org/derby/. Click the Download tab." }, { "code": null, "e": 1580, "s": 1512, "text": "Select and click on the link of the latest version of Apache Derby." }, { "code": null, "e": 1648, "s": 1580, "text": "Select and click on the link of the latest version of Apache Derby." }, { "code": null, "e": 1880, "s": 1648, "text": "On clicking the selected link, you will be redirected to the Distributions page of apache derby. If you observe here, derby provides distributions namely, db-derby-bin, db-derbylib.zip, db-derby-lib-debug.zip, and db-derby-src.zip." }, { "code": null, "e": 2112, "s": 1880, "text": "On clicking the selected link, you will be redirected to the Distributions page of apache derby. If you observe here, derby provides distributions namely, db-derby-bin, db-derbylib.zip, db-derby-lib-debug.zip, and db-derby-src.zip." }, { "code": null, "e": 2255, "s": 2112, "text": "Download the db-derby-bin folder. Copy its contents to a separate folder where you wanted to install Apache Derby. (for example, say C:\\Derby)" }, { "code": null, "e": 2398, "s": 2255, "text": "Download the db-derby-bin folder. Copy its contents to a separate folder where you wanted to install Apache Derby. (for example, say C:\\Derby)" }, { "code": null, "e": 2423, "s": 2398, "text": "Now, to work with Derby," }, { "code": null, "e": 2601, "s": 2423, "text": "Make sure that you already have set the JAVA_HOME variable by passing the location of bin folder of Java Installation folder, and include the JAVA_HOME/bin in the PATH variable." }, { "code": null, "e": 2668, "s": 2601, "text": "Create a new environment variable, DERBY_HOME with value C:\\Derby." }, { "code": null, "e": 2782, "s": 2668, "text": "The bin folder of db-derby-bin distributions (we changed it as C:\\Derby\\bin) contains all the required jar files." }, { "code": null, "e": 2967, "s": 2782, "text": "Following JDBC program establishes connection with Apache derby database, creates a table named employeedata, inserts records into it, retrieves and displays the contents of the table." }, { "code": null, "e": 4763, "s": 2967, "text": "public class InsertData {\n public static void main(String args[]) throws Exception {\n //Registering the driver\n Class.forName(\"org.apache.derby.jdbc.EmbeddedDriver\");\n //Getting the Connection object\n String URL = \"jdbc:derby:mydatabs;create=true\";\n Connection conn = DriverManager.getConnection(URL);\n //Creating the Statement object\n Statement stmt = conn.createStatement();\n //Creating a table in Derby database\n String query = \"CREATE TABLE EmployeeData( \"\n + \"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, \"\n + \"Name VARCHAR(255), \"\n + \"Salary INT NOT NULL, \"\n + \"Location VARCHAR(255), \"\n + \"PRIMARY KEY (Id))\";\n stmt.execute(query);\n System.out.println(\"Table created\");\n //Inserting data\n query = \"INSERT INTO EmployeeData(\"\n + \"Name, Salary, Location) VALUES \"\n + \"('Amit', 30000, 'Hyderabad'), \"\n + \"('Kalyan', 40000, 'Vishakhapatnam'), \"\n + \"('Renuka', 50000, 'Delhi'), \"\n + \"('Archana', 15000, 'Mumbai'), \"\n + \"('Trupthi', 45000, 'Kochin'), \"\n + \"('Suchatra', 33000, 'Pune'), \"\n + \"('Rahul', 39000, 'Lucknow'), \"\n + \"('Trupthi', 45000, 'Kochin')\";\n stmt.execute(query);\n System.out.println(\"Values inserted\");\n //Retrieving data\n ResultSet rs = stmt.executeQuery(\"Select * from EmployeeData\");\n System.out.println(\"Contents of the table EmployeeData table:\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"Name\")+\", \");\n System.out.print(\"Salary: \"+rs.getInt(\"Salary\")+\", \");\n System.out.print(\"Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 5270, "s": 4763, "text": "Table created\nValues inserted\nContents of the table EmployeeData table:\nID: 1, Name: Amit, Salary: 30000, Location: Hyderabad\nID: 2, Name: Kalyan, Salary: 40000, Location: Vishakhapatnam\nID: 3, Name: Renuka, Salary: 50000, Location: Delhi\nID: 4, Name: Archana, Salary: 15000, Location: Mumbai\nID: 5, Name: Trupthi, Salary: 45000, Location: Kochin\nID: 6, Name: Suchatra, Salary: 33000, Location: Pune\nID: 7, Name: Rahul, Salary: 39000, Location: Lucknow\nID: 8, Name: Trupthi, Salary: 45000, Location: Kochin" } ]
Building and deploying a machine learning model with automated ML on Azure. | by Robbert Brouwers | Towards Data Science
This article goes through the basics of using Azure’s Automated Machine learning functionality. We will train and deploy a machine learning model that is operational. After this article you will be able to build an end to end solution for deploying a machine learning model, without writing a single line of code. The goal is to help you understand what goes into the basics of building and deploying machine learning models. It won’t cover concepts such as modelling techniques/ best practices, security/authorisation, but functions as a starting point for those who: (1) want to build ML models without coding or (2) want to understand what is possible with automated machine learning and how this can be of value to you and your organisation. We will use Microsoft Azure’s Automated Machine Learning platform for this exercise. We set up the environment/resources, train multiple models on the dataset and deploy this model on Azure so we can actually use it. This article is set up in three sections:1. The “Boring Stuff” (Setting up the resources in Azure)2. The “Cool Stuff” (training the model)3. The “I-Can-Show-My-Friends-Now” (deploying the model) So without further ado, let’s build some cool things (aka on to the Boring Stuff)! Using services on Azure cost money. There’s ways to get free credits or trial periods (for example: through this link.) The whole experiment costed me €3.02 (without using any free credits): At the end of this article we’ll go through how to clean up so we won’t incur any unexpected costs. Let’s get to it! (sign up here if you don’t have an azure account yet and make sure you have a payment method set up, should be part of the registration process). Once signed up, you should see you default Azure Home Page: A resource group is ‘a container that holds related resources for an Azure Solution’. It will help us to easily distinguish the resources that belong to our ML model and deployment (and will help us easily remove it afterwards). From the Azure Home page, click “Resource Groups” in the left menu and create a new resource group: The regions are not important for this exercise: pick the one based on where you are in this world. Azure Machine Learning services are a collection of resources to help you create, test and deploy machine learning models. Automated ML is a part of this collection and that’s what we are using here. Make sure to allocate the new resource to the above created “autoML” resource group. The regions are not that important for this exercise: pick the one based on where you are in this world. In this article, we will build a regression model that predicts the correct price for an AirBnB place in New York City. The data comes from Kaggle and is available via this link. We can save this file locally for now: we will upload it to Azure in the next section. We have created an account for Azure, set up a resource group to organize our resources related to this exercise and created an Azure Machine Learning Service Workspace, which we can see from our home page: Congrats! We’ve done the boring stuff! Let’s quickly head over to do some actual data related work. On our Azure home page, we can click on the “autoML” resource to go the resource page. We will use the new interface by clicking on the “Launch Preview Now” banner, or go there directly through this link. All the training steps will be executed from the new Azure Machine Learning Interface. Select the recently created subscription and Azure Machine Learning Resource: Upload DatasetUpload the unzipped dataset “Output.csv” by navigating to “Datasets” (left menu), then click “Create Dataset”. Select the file from local machine. All the other settings can remain as they are. After clicking done, the dataset will upload: Our dataset will be visible from the “Datasets” page now: From the menu, head over to “Automated ML” and click on the blue “Create Experiment” button: In the next screen we have to provide a name and training compute. You might wonder what the “training compute” means. The models we want to train need a computer to run on. Azure provides virtual computers, which are located in massive datacenters all around the world. This allows us to basically spin up any size of computer when needed and spin it down again when done, only using what we need. For this exercise, we’re going to spin up a small compute resource (a virtual machine). Click “create a new compute” and give it a name such as autoML. We’ll use the default STANDARD_DS12_V2 — — 4 vCPUs, 28 GB memory, 56 GB storage (leave additional settings as is): When we picked an experiment name (I went with -surprise!- “autoML”) and, the new compute is created, make sure to select the training compute we just created and hit next. Next we select the dataset we previously uploaded and we will be asked for a couple more pieces of input. Now for our use case, the goal is to predict the price (Target Column), based on other information in the dataset. We can check the profile tab to do a bit of data exploration, but for the sake of brevity, we are going straight to picking columns to include, the prediction task and Target Column: First we exclude columns we don’t want/need in our model. You might explore/include other columns in the future, but to follow along with this tutorial: pick the same columns as I have done. The columns we include are: neighbourhood_group, neighbourhood, room_type, price (target column), minimum_nights, number_of_reviews, last_review, reviews_per_month. We are predicting a quantity (price per night), so our prediction task is regression and the Target Column is price. We could play around with the advanced settings, and you probably will for future experiments, but for now we’re leaving most of it as is.This means we pick ‘Spearman Correlation’ as the primary metric to measure and compare the models on. Let’s set the training job time to 30 minutes. Scroll down, hit start and congratulate yourself! You are now a data scientist!* Azure will now spin up the right resources. After that the actual ‘automated’ part of ML begins: Azure will try and fit different models and settings to find the best fit for our data and type of exercise (regression). We will start seeing different models and their accuracy scores soon. Also, we don’t have to stay on any specific page during the run; so feel free to browse around the Azure ML interface. Bear in mind, it will take some time for Azure to spin up the resources and for the results of the first models to come in so the whole process takes longer than the 30 minutes we have picked as our training time. *but don’t tell your actual data scientist friends and colleagues because they probably won’t agree. During and after the experiment run, we can see the results of each run by going to the leaderboard: By clicking on any of the completed iterations we can see a more extensive set of result metrics and graphs: Once the experiment has finished we can look around a bit and see what type of models have been ran, how they have performed etc. Afterwards we are heading to the next section: deployment Cool! We have a leaderboard and a winning model. Now what? We can’t really show off anything yet: we want to give our model input columns (such as the neighbourhood, number of reviews and average reviews per month) and then receive an estimate for the price per night. On to the “I-Can-Show-My-Friends-Now” part of this tutorial! To receive an estimate for the price per night, we need to “deploy” the model. This will become a “container” that is able to run our model code (the winning model) on a specified environment (python) and handle incoming requests. Azure Machine Learning Services has a pretty awesome functionality included in automated machine learning services that does all the work for us when deploying: “Deploy Best Model”. It’s on the leaderboard page we previously looked at to see how different models are performing. Use any deployment name and description you’d like and leave the Scoring Script and Environment Script to “Auto Generate”. Hit Deploy, this will take around 20 mins to complete. When our model is deployed, the model will appear on the “Model” page. A model includes an endpoint. An API endpoint is commonly defined as ‘the end of a communication channel’. That definition by itself doesn’t really help us (at all), but think about it this way: we have a model and we want to communicate with this model by sending input (the columns we included in our model) and getting output (an estimation of the price per night) in return. We can’t just throw anything at our model/endpoint and expect a correct response, so next up is to find our endpoint and send a HTTP request to our model! When we deployed the model, Azure ML services created a python script that has been deployed in a ‘container’. This container runs somewhere it the Azure cloud and is now ready to receive HTTP requests from us. For this to work, we’ll need to do three things: The endpoint is available in the Azure ML interface by going to “Endpoints” from the left menu We click on our newly deployed model and will find see a list of attributes, of which the relevant one is the “Scoring URI”. Remember talking about API endpoints? This Scoring URI is our endpoint for the model we have created, meaning we can send (“do a request”) something to this endpoint (input) and will receive a response (output). And if we format the request correctly, we will get back what we want: a price per night estimate given our input columns. This part might get a bit confusing for those who have no experience working with HTTP requests, but just keep following the steps and you’ll get it to work! Functionally, what we want to do is send a http request where we input values for the columns we have included in the model (except the target column, which is the one column we want back of course). That means we want to send information about: “neighbourhood_group”, “neighbourhood”, “room_type”, “minimum_nights”,“number_of_reviews”, “last_review”, “reviews_per_month”. This information is referred to as the “body” of our http request and Azure describes in their documentation how we should format this information to be interpretable by the model: The REST API expects the body of the request to be a JSON document with the following structure: { "data": [ <model-specific-data-structure> ]} where (an example of) our “model specific data structure” looks like this: { "data": [ { "neighbourhood_group": "Queens", "neighbourhood": "Ridgewood", "room_type": "Entire home/apt", "minimum_nights": 3, "number_of_reviews": 9, "last_review": "2019-06-26T00:00:00.000Z", "reviews_per_month": 2.1 } ]} A HTTP request also includes one or more “Headers”, and according to the documentation, we need to add a “Content-Type” header: “Content-Type” : “application/json” To summarise, based on: (1) the endpoint/Scoring URI, (2) the body (input) and (3) the headers, we can create a request that will give us back (if everything works correct) an estimated price per night! Let’s put it to the test! For the curious ones (which I assume is all of you who made it this far): here’s the complete request: POST /score HTTP/1.1Host: <scoring-uri>Content-Type: application/jsonUser-Agent: PostmanRuntime/7.17.1Accept: */*Cache-Control: no-cachePostman-Token: <token-value>Host: <scoring-uri>Accept-Encoding: gzip, deflateContent-Length: 335Connection: keep-alivecache-control: no-cache{ "data": [ { "neighbourhood_group": "Queens", "neighbourhood": "Ridgewood", "room_type": "Entire home/apt", "minimum_nights": 3, "number_of_reviews": 9, "last_review": "2019-06-26T00:00:00.000Z", "reviews_per_month": 2.1 } ]} There is some information in there that we haven’t covered; don’t worry about it, as it’s not essential for understanding our end to end workflow. On to the last part! At this moment, you have a deployed model that is ‘callable’ by means of an API endpoint (the scoring URI). Anyone (quite literally anyone since we haven’t enforced any authorization on the API) can use your beautiful model in their apps, notebooks or other (business) applications by utilising the API endpoint. When I send the request from two paragraphs up, I get the following result: "{\"result\": [125.5851758821278]}" Awesome! So this tells us that given the model input (Queens, Ridgewood, Entire home/apt, 3 nights, 9 reviews, last review on the 26th of June 2019 and an average of 2.1 reviews per month) estimates that the price per night would be $125.58 Easy peasy! Obviously you want to see this to believe it, so here we go: Download Postman, a free app for API development. We will use his to send our HTTP request to our model. Once installed. We’ll repeat the three steps of: setting the URL (scoring URI), adding the Content-Type Header and adding the body: Open up Postman and select “Request” from the “Create New” tab: Provide a name and create a collection/folder and hit Save: You’ll see a new screen where we can create API requests. Set the “http method” to POST, and copy the scoring URI where the “enter request URL” placeholder is placed: When we go to the “Body” tab in postman, we take two actions:1. Set body type to “raw” and the type to JSON2. Copy the request column and values from previously shown request into the body field: { "data": [ { "neighbourhood_group": "Queens", "neighbourhood": "Ridgewood", "room_type": "Entire home/apt", "minimum_nights": 3, "number_of_reviews": 9, "last_review": "2019-06-26T00:00:00.000Z", "reviews_per_month": 2.1 } ]} The header we talked about before (“Content-Type”) is automatically added by postman because we set the type of raw body to “JSON”. You can see this on the header tab. This means we have covered all parts of the request! Time to hit that big blue send button and do our first request! You’ve done it! Give yourself a high-five, put on your favorite jam (I recommend DMX — Party Up (Up In Here) for the occasion) and shoot a couple more requests to your very own deployed automated machine learning model! When you are ready, make sure to delete the resource group so you won’t incur any unexpected charges on Azure: As you may have noticed by going through this tutorial, there’s quite a bit of work that is not necessarily data science related when it comes to making data science operational. I strongly believe that it is valuable for any data worker to experiment. We have an amazing set of cloud service providers, (open source) frameworks to quickly and easily start testing new ideas. The most important thing is to get started! There seems to be an ongoing debate about automated machine learning, where people are roughly divided between “That’s not data science!” and “We don’t need data scientists anymore at all!”. The truth is probably somewhere in the middle, but requires a certain amount of nuance. It will always depend on your specific requirements and available capabilities, but given the amount of options you have when picking autoML vendors/frameworks and the amount of attention it’s getting, we can probably safely assume that it’s here to stay. I think knowing about and possibly applying automated ML will help organisations leverage new technology, which can be valuable especially when: You don’t have a data science team or want to leverage the scarce data science resources by automating the ‘simpler’ data science tasks.You want to iterate over the complete end to end process for rapid development of analytics use cases. We should allocate time to all parts of the process and not just the modelling part to ensure we end up with a solution that is not only accurate but also works (operational).You want to establish a ‘baseline model’. The automated ML model doesn’t have to be the final model. You don’t have a data science team or want to leverage the scarce data science resources by automating the ‘simpler’ data science tasks. You want to iterate over the complete end to end process for rapid development of analytics use cases. We should allocate time to all parts of the process and not just the modelling part to ensure we end up with a solution that is not only accurate but also works (operational). You want to establish a ‘baseline model’. The automated ML model doesn’t have to be the final model. I hope this has been a useful tutorial for you to get started with automated machine learning! Leave your thoughts/suggestions in the replies! (Feel free to reach out on LinkedIn as well). Different automated ML solutions — https://medium.com/@santiagof/auto-is-the-new-black-google-automl-microsoft-automated-ml-autokeras-and-auto-sklearn-80d1d3c3005c Data Science methodology — https://medium.com/towards-artificial-intelligence/the-data-science-methodology-50d60175a06a
[ { "code": null, "e": 486, "s": 172, "text": "This article goes through the basics of using Azure’s Automated Machine learning functionality. We will train and deploy a machine learning model that is operational. After this article you will be able to build an end to end solution for deploying a machine learning model, without writing a single line of code." }, { "code": null, "e": 918, "s": 486, "text": "The goal is to help you understand what goes into the basics of building and deploying machine learning models. It won’t cover concepts such as modelling techniques/ best practices, security/authorisation, but functions as a starting point for those who: (1) want to build ML models without coding or (2) want to understand what is possible with automated machine learning and how this can be of value to you and your organisation." }, { "code": null, "e": 1135, "s": 918, "text": "We will use Microsoft Azure’s Automated Machine Learning platform for this exercise. We set up the environment/resources, train multiple models on the dataset and deploy this model on Azure so we can actually use it." }, { "code": null, "e": 1330, "s": 1135, "text": "This article is set up in three sections:1. The “Boring Stuff” (Setting up the resources in Azure)2. The “Cool Stuff” (training the model)3. The “I-Can-Show-My-Friends-Now” (deploying the model)" }, { "code": null, "e": 1413, "s": 1330, "text": "So without further ado, let’s build some cool things (aka on to the Boring Stuff)!" }, { "code": null, "e": 1533, "s": 1413, "text": "Using services on Azure cost money. There’s ways to get free credits or trial periods (for example: through this link.)" }, { "code": null, "e": 1604, "s": 1533, "text": "The whole experiment costed me €3.02 (without using any free credits):" }, { "code": null, "e": 1704, "s": 1604, "text": "At the end of this article we’ll go through how to clean up so we won’t incur any unexpected costs." }, { "code": null, "e": 1721, "s": 1704, "text": "Let’s get to it!" }, { "code": null, "e": 1867, "s": 1721, "text": "(sign up here if you don’t have an azure account yet and make sure you have a payment method set up, should be part of the registration process)." }, { "code": null, "e": 1927, "s": 1867, "text": "Once signed up, you should see you default Azure Home Page:" }, { "code": null, "e": 2156, "s": 1927, "text": "A resource group is ‘a container that holds related resources for an Azure Solution’. It will help us to easily distinguish the resources that belong to our ML model and deployment (and will help us easily remove it afterwards)." }, { "code": null, "e": 2256, "s": 2156, "text": "From the Azure Home page, click “Resource Groups” in the left menu and create a new resource group:" }, { "code": null, "e": 2356, "s": 2256, "text": "The regions are not important for this exercise: pick the one based on where you are in this world." }, { "code": null, "e": 2641, "s": 2356, "text": "Azure Machine Learning services are a collection of resources to help you create, test and deploy machine learning models. Automated ML is a part of this collection and that’s what we are using here. Make sure to allocate the new resource to the above created “autoML” resource group." }, { "code": null, "e": 2746, "s": 2641, "text": "The regions are not that important for this exercise: pick the one based on where you are in this world." }, { "code": null, "e": 2925, "s": 2746, "text": "In this article, we will build a regression model that predicts the correct price for an AirBnB place in New York City. The data comes from Kaggle and is available via this link." }, { "code": null, "e": 3012, "s": 2925, "text": "We can save this file locally for now: we will upload it to Azure in the next section." }, { "code": null, "e": 3219, "s": 3012, "text": "We have created an account for Azure, set up a resource group to organize our resources related to this exercise and created an Azure Machine Learning Service Workspace, which we can see from our home page:" }, { "code": null, "e": 3319, "s": 3219, "text": "Congrats! We’ve done the boring stuff! Let’s quickly head over to do some actual data related work." }, { "code": null, "e": 3611, "s": 3319, "text": "On our Azure home page, we can click on the “autoML” resource to go the resource page. We will use the new interface by clicking on the “Launch Preview Now” banner, or go there directly through this link. All the training steps will be executed from the new Azure Machine Learning Interface." }, { "code": null, "e": 3689, "s": 3611, "text": "Select the recently created subscription and Azure Machine Learning Resource:" }, { "code": null, "e": 3814, "s": 3689, "text": "Upload DatasetUpload the unzipped dataset “Output.csv” by navigating to “Datasets” (left menu), then click “Create Dataset”." }, { "code": null, "e": 3943, "s": 3814, "text": "Select the file from local machine. All the other settings can remain as they are. After clicking done, the dataset will upload:" }, { "code": null, "e": 4001, "s": 3943, "text": "Our dataset will be visible from the “Datasets” page now:" }, { "code": null, "e": 4094, "s": 4001, "text": "From the menu, head over to “Automated ML” and click on the blue “Create Experiment” button:" }, { "code": null, "e": 4493, "s": 4094, "text": "In the next screen we have to provide a name and training compute. You might wonder what the “training compute” means. The models we want to train need a computer to run on. Azure provides virtual computers, which are located in massive datacenters all around the world. This allows us to basically spin up any size of computer when needed and spin it down again when done, only using what we need." }, { "code": null, "e": 4760, "s": 4493, "text": "For this exercise, we’re going to spin up a small compute resource (a virtual machine). Click “create a new compute” and give it a name such as autoML. We’ll use the default STANDARD_DS12_V2 — — 4 vCPUs, 28 GB memory, 56 GB storage (leave additional settings as is):" }, { "code": null, "e": 4933, "s": 4760, "text": "When we picked an experiment name (I went with -surprise!- “autoML”) and, the new compute is created, make sure to select the training compute we just created and hit next." }, { "code": null, "e": 5154, "s": 4933, "text": "Next we select the dataset we previously uploaded and we will be asked for a couple more pieces of input. Now for our use case, the goal is to predict the price (Target Column), based on other information in the dataset." }, { "code": null, "e": 5337, "s": 5154, "text": "We can check the profile tab to do a bit of data exploration, but for the sake of brevity, we are going straight to picking columns to include, the prediction task and Target Column:" }, { "code": null, "e": 5693, "s": 5337, "text": "First we exclude columns we don’t want/need in our model. You might explore/include other columns in the future, but to follow along with this tutorial: pick the same columns as I have done. The columns we include are: neighbourhood_group, neighbourhood, room_type, price (target column), minimum_nights, number_of_reviews, last_review, reviews_per_month." }, { "code": null, "e": 5810, "s": 5693, "text": "We are predicting a quantity (price per night), so our prediction task is regression and the Target Column is price." }, { "code": null, "e": 6097, "s": 5810, "text": "We could play around with the advanced settings, and you probably will for future experiments, but for now we’re leaving most of it as is.This means we pick ‘Spearman Correlation’ as the primary metric to measure and compare the models on. Let’s set the training job time to 30 minutes." }, { "code": null, "e": 6178, "s": 6097, "text": "Scroll down, hit start and congratulate yourself! You are now a data scientist!*" }, { "code": null, "e": 6586, "s": 6178, "text": "Azure will now spin up the right resources. After that the actual ‘automated’ part of ML begins: Azure will try and fit different models and settings to find the best fit for our data and type of exercise (regression). We will start seeing different models and their accuracy scores soon. Also, we don’t have to stay on any specific page during the run; so feel free to browse around the Azure ML interface." }, { "code": null, "e": 6800, "s": 6586, "text": "Bear in mind, it will take some time for Azure to spin up the resources and for the results of the first models to come in so the whole process takes longer than the 30 minutes we have picked as our training time." }, { "code": null, "e": 6901, "s": 6800, "text": "*but don’t tell your actual data scientist friends and colleagues because they probably won’t agree." }, { "code": null, "e": 7002, "s": 6901, "text": "During and after the experiment run, we can see the results of each run by going to the leaderboard:" }, { "code": null, "e": 7111, "s": 7002, "text": "By clicking on any of the completed iterations we can see a more extensive set of result metrics and graphs:" }, { "code": null, "e": 7299, "s": 7111, "text": "Once the experiment has finished we can look around a bit and see what type of models have been ran, how they have performed etc. Afterwards we are heading to the next section: deployment" }, { "code": null, "e": 7629, "s": 7299, "text": "Cool! We have a leaderboard and a winning model. Now what? We can’t really show off anything yet: we want to give our model input columns (such as the neighbourhood, number of reviews and average reviews per month) and then receive an estimate for the price per night. On to the “I-Can-Show-My-Friends-Now” part of this tutorial!" }, { "code": null, "e": 8139, "s": 7629, "text": "To receive an estimate for the price per night, we need to “deploy” the model. This will become a “container” that is able to run our model code (the winning model) on a specified environment (python) and handle incoming requests. Azure Machine Learning Services has a pretty awesome functionality included in automated machine learning services that does all the work for us when deploying: “Deploy Best Model”. It’s on the leaderboard page we previously looked at to see how different models are performing." }, { "code": null, "e": 8317, "s": 8139, "text": "Use any deployment name and description you’d like and leave the Scoring Script and Environment Script to “Auto Generate”. Hit Deploy, this will take around 20 mins to complete." }, { "code": null, "e": 8922, "s": 8317, "text": "When our model is deployed, the model will appear on the “Model” page. A model includes an endpoint. An API endpoint is commonly defined as ‘the end of a communication channel’. That definition by itself doesn’t really help us (at all), but think about it this way: we have a model and we want to communicate with this model by sending input (the columns we included in our model) and getting output (an estimation of the price per night) in return. We can’t just throw anything at our model/endpoint and expect a correct response, so next up is to find our endpoint and send a HTTP request to our model!" }, { "code": null, "e": 9133, "s": 8922, "text": "When we deployed the model, Azure ML services created a python script that has been deployed in a ‘container’. This container runs somewhere it the Azure cloud and is now ready to receive HTTP requests from us." }, { "code": null, "e": 9182, "s": 9133, "text": "For this to work, we’ll need to do three things:" }, { "code": null, "e": 9277, "s": 9182, "text": "The endpoint is available in the Azure ML interface by going to “Endpoints” from the left menu" }, { "code": null, "e": 9402, "s": 9277, "text": "We click on our newly deployed model and will find see a list of attributes, of which the relevant one is the “Scoring URI”." }, { "code": null, "e": 9737, "s": 9402, "text": "Remember talking about API endpoints? This Scoring URI is our endpoint for the model we have created, meaning we can send (“do a request”) something to this endpoint (input) and will receive a response (output). And if we format the request correctly, we will get back what we want: a price per night estimate given our input columns." }, { "code": null, "e": 9895, "s": 9737, "text": "This part might get a bit confusing for those who have no experience working with HTTP requests, but just keep following the steps and you’ll get it to work!" }, { "code": null, "e": 10141, "s": 9895, "text": "Functionally, what we want to do is send a http request where we input values for the columns we have included in the model (except the target column, which is the one column we want back of course). That means we want to send information about:" }, { "code": null, "e": 10268, "s": 10141, "text": "“neighbourhood_group”, “neighbourhood”, “room_type”, “minimum_nights”,“number_of_reviews”, “last_review”, “reviews_per_month”." }, { "code": null, "e": 10449, "s": 10268, "text": "This information is referred to as the “body” of our http request and Azure describes in their documentation how we should format this information to be interpretable by the model:" }, { "code": null, "e": 10546, "s": 10449, "text": "The REST API expects the body of the request to be a JSON document with the following structure:" }, { "code": null, "e": 10621, "s": 10546, "text": "{ \"data\": [ <model-specific-data-structure> ]}" }, { "code": null, "e": 10696, "s": 10621, "text": "where (an example of) our “model specific data structure” looks like this:" }, { "code": null, "e": 11020, "s": 10696, "text": "{ \"data\": [ { \"neighbourhood_group\": \"Queens\", \"neighbourhood\": \"Ridgewood\", \"room_type\": \"Entire home/apt\", \"minimum_nights\": 3, \"number_of_reviews\": 9, \"last_review\": \"2019-06-26T00:00:00.000Z\", \"reviews_per_month\": 2.1 } ]}" }, { "code": null, "e": 11148, "s": 11020, "text": "A HTTP request also includes one or more “Headers”, and according to the documentation, we need to add a “Content-Type” header:" }, { "code": null, "e": 11184, "s": 11148, "text": "“Content-Type” : “application/json”" }, { "code": null, "e": 11413, "s": 11184, "text": "To summarise, based on: (1) the endpoint/Scoring URI, (2) the body (input) and (3) the headers, we can create a request that will give us back (if everything works correct) an estimated price per night! Let’s put it to the test!" }, { "code": null, "e": 11516, "s": 11413, "text": "For the curious ones (which I assume is all of you who made it this far): here’s the complete request:" }, { "code": null, "e": 12117, "s": 11516, "text": "POST /score HTTP/1.1Host: <scoring-uri>Content-Type: application/jsonUser-Agent: PostmanRuntime/7.17.1Accept: */*Cache-Control: no-cachePostman-Token: <token-value>Host: <scoring-uri>Accept-Encoding: gzip, deflateContent-Length: 335Connection: keep-alivecache-control: no-cache{ \"data\": [ { \"neighbourhood_group\": \"Queens\", \"neighbourhood\": \"Ridgewood\", \"room_type\": \"Entire home/apt\", \"minimum_nights\": 3, \"number_of_reviews\": 9, \"last_review\": \"2019-06-26T00:00:00.000Z\", \"reviews_per_month\": 2.1 } ]}" }, { "code": null, "e": 12285, "s": 12117, "text": "There is some information in there that we haven’t covered; don’t worry about it, as it’s not essential for understanding our end to end workflow. On to the last part!" }, { "code": null, "e": 12674, "s": 12285, "text": "At this moment, you have a deployed model that is ‘callable’ by means of an API endpoint (the scoring URI). Anyone (quite literally anyone since we haven’t enforced any authorization on the API) can use your beautiful model in their apps, notebooks or other (business) applications by utilising the API endpoint. When I send the request from two paragraphs up, I get the following result:" }, { "code": null, "e": 12710, "s": 12674, "text": "\"{\\\"result\\\": [125.5851758821278]}\"" }, { "code": null, "e": 12951, "s": 12710, "text": "Awesome! So this tells us that given the model input (Queens, Ridgewood, Entire home/apt, 3 nights, 9 reviews, last review on the 26th of June 2019 and an average of 2.1 reviews per month) estimates that the price per night would be $125.58" }, { "code": null, "e": 13024, "s": 12951, "text": "Easy peasy! Obviously you want to see this to believe it, so here we go:" }, { "code": null, "e": 13261, "s": 13024, "text": "Download Postman, a free app for API development. We will use his to send our HTTP request to our model. Once installed. We’ll repeat the three steps of: setting the URL (scoring URI), adding the Content-Type Header and adding the body:" }, { "code": null, "e": 13325, "s": 13261, "text": "Open up Postman and select “Request” from the “Create New” tab:" }, { "code": null, "e": 13385, "s": 13325, "text": "Provide a name and create a collection/folder and hit Save:" }, { "code": null, "e": 13443, "s": 13385, "text": "You’ll see a new screen where we can create API requests." }, { "code": null, "e": 13552, "s": 13443, "text": "Set the “http method” to POST, and copy the scoring URI where the “enter request URL” placeholder is placed:" }, { "code": null, "e": 13748, "s": 13552, "text": "When we go to the “Body” tab in postman, we take two actions:1. Set body type to “raw” and the type to JSON2. Copy the request column and values from previously shown request into the body field:" }, { "code": null, "e": 14072, "s": 13748, "text": "{ \"data\": [ { \"neighbourhood_group\": \"Queens\", \"neighbourhood\": \"Ridgewood\", \"room_type\": \"Entire home/apt\", \"minimum_nights\": 3, \"number_of_reviews\": 9, \"last_review\": \"2019-06-26T00:00:00.000Z\", \"reviews_per_month\": 2.1 } ]}" }, { "code": null, "e": 14240, "s": 14072, "text": "The header we talked about before (“Content-Type”) is automatically added by postman because we set the type of raw body to “JSON”. You can see this on the header tab." }, { "code": null, "e": 14357, "s": 14240, "text": "This means we have covered all parts of the request! Time to hit that big blue send button and do our first request!" }, { "code": null, "e": 14577, "s": 14357, "text": "You’ve done it! Give yourself a high-five, put on your favorite jam (I recommend DMX — Party Up (Up In Here) for the occasion) and shoot a couple more requests to your very own deployed automated machine learning model!" }, { "code": null, "e": 14688, "s": 14577, "text": "When you are ready, make sure to delete the resource group so you won’t incur any unexpected charges on Azure:" }, { "code": null, "e": 15108, "s": 14688, "text": "As you may have noticed by going through this tutorial, there’s quite a bit of work that is not necessarily data science related when it comes to making data science operational. I strongly believe that it is valuable for any data worker to experiment. We have an amazing set of cloud service providers, (open source) frameworks to quickly and easily start testing new ideas. The most important thing is to get started!" }, { "code": null, "e": 15387, "s": 15108, "text": "There seems to be an ongoing debate about automated machine learning, where people are roughly divided between “That’s not data science!” and “We don’t need data scientists anymore at all!”. The truth is probably somewhere in the middle, but requires a certain amount of nuance." }, { "code": null, "e": 15643, "s": 15387, "text": "It will always depend on your specific requirements and available capabilities, but given the amount of options you have when picking autoML vendors/frameworks and the amount of attention it’s getting, we can probably safely assume that it’s here to stay." }, { "code": null, "e": 15788, "s": 15643, "text": "I think knowing about and possibly applying automated ML will help organisations leverage new technology, which can be valuable especially when:" }, { "code": null, "e": 16303, "s": 15788, "text": "You don’t have a data science team or want to leverage the scarce data science resources by automating the ‘simpler’ data science tasks.You want to iterate over the complete end to end process for rapid development of analytics use cases. We should allocate time to all parts of the process and not just the modelling part to ensure we end up with a solution that is not only accurate but also works (operational).You want to establish a ‘baseline model’. The automated ML model doesn’t have to be the final model." }, { "code": null, "e": 16440, "s": 16303, "text": "You don’t have a data science team or want to leverage the scarce data science resources by automating the ‘simpler’ data science tasks." }, { "code": null, "e": 16719, "s": 16440, "text": "You want to iterate over the complete end to end process for rapid development of analytics use cases. We should allocate time to all parts of the process and not just the modelling part to ensure we end up with a solution that is not only accurate but also works (operational)." }, { "code": null, "e": 16820, "s": 16719, "text": "You want to establish a ‘baseline model’. The automated ML model doesn’t have to be the final model." }, { "code": null, "e": 16963, "s": 16820, "text": "I hope this has been a useful tutorial for you to get started with automated machine learning! Leave your thoughts/suggestions in the replies!" }, { "code": null, "e": 17009, "s": 16963, "text": "(Feel free to reach out on LinkedIn as well)." }, { "code": null, "e": 17173, "s": 17009, "text": "Different automated ML solutions — https://medium.com/@santiagof/auto-is-the-new-black-google-automl-microsoft-automated-ml-autokeras-and-auto-sklearn-80d1d3c3005c" } ]
How to find the number of times array is rotated in the sorted array by recursion using C#?
Find index of mid element (minimum element) Apply Binary Search on the subarray based on following conditions − If number lies between start element and element at mid1 position. If number lies between start element and element at mid1 position. Then find number in array start to mid-1 using binary search Then find number in array start to mid-1 using binary search Else if number lies between mid and last element, then find number in array mid to last element using binary search. Else if number lies between mid and last element, then find number in array mid to last element using binary search. Live Demo using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace ConsoleApplication{ public class Arrays{ public int FindNumberRotated(int[] array, int start, int end, int value){ if (start > end){ return -1; } int mid = (start + end) / 2; if (array[mid] == value){ return mid; } if (array[start] <= array[mid]){ if (value >= array[start] && value <= array[mid]){ return FindNumberRotated(array, start, mid - 1, value); } return FindNumberRotated(array, mid + 1, end, value); } if (value >= array[mid] && value <= array[end]){ return FindNumberRotated(array, mid + 1, end, value); } return FindNumberRotated(array, start, mid - 1, value); } } class Program{ static void Main(string[] args){ Arrays a = new Arrays(); int[] arr = { 3, 4, 5, 6, 7, 8, 9, 10, 1, 2 }; int res = a.FindNumberRotated(arr, 0, arr.Length - 1, 1); Console.WriteLine(res); } } } 8
[ { "code": null, "e": 1174, "s": 1062, "text": "Find index of mid element (minimum element) Apply Binary Search on the subarray based on following conditions −" }, { "code": null, "e": 1241, "s": 1174, "text": "If number lies between start element and element at mid1 position." }, { "code": null, "e": 1308, "s": 1241, "text": "If number lies between start element and element at mid1 position." }, { "code": null, "e": 1369, "s": 1308, "text": "Then find number in array start to mid-1 using binary search" }, { "code": null, "e": 1430, "s": 1369, "text": "Then find number in array start to mid-1 using binary search" }, { "code": null, "e": 1547, "s": 1430, "text": "Else if number lies between mid and last element, then find number in array mid to last element using binary search." }, { "code": null, "e": 1664, "s": 1547, "text": "Else if number lies between mid and last element, then find number in array mid to last element using binary search." }, { "code": null, "e": 1675, "s": 1664, "text": " Live Demo" }, { "code": null, "e": 2806, "s": 1675, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Linq;\nnamespace ConsoleApplication{\n public class Arrays{\n public int FindNumberRotated(int[] array, int start, int end, int value){\n if (start > end){\n return -1;\n }\n int mid = (start + end) / 2;\n if (array[mid] == value){\n return mid;\n }\n if (array[start] <= array[mid]){\n if (value >= array[start] && value <= array[mid]){\n return FindNumberRotated(array, start, mid - 1, value);\n }\n return FindNumberRotated(array, mid + 1, end, value);\n }\n if (value >= array[mid] && value <= array[end]){\n return FindNumberRotated(array, mid + 1, end, value);\n }\n return FindNumberRotated(array, start, mid - 1, value);\n }\n }\n class Program{\n static void Main(string[] args){\n Arrays a = new Arrays();\n int[] arr = { 3, 4, 5, 6, 7, 8, 9, 10, 1, 2 };\n int res = a.FindNumberRotated(arr, 0, arr.Length - 1, 1);\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 2808, "s": 2806, "text": "8" } ]
Python Tips and Tricks for Competitive Programming - GeeksforGeeks
19 Aug, 2021 Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips: Converting a number into a List of digits using map() Function: Below is the implementation to convert a given number into a list of digits: Python3 # Python program to convert a# number to a list of digits # Given numbern = 123456 # Stores the list of digitslis = list(map(int, str(n))) # Print the digitsprint(lis) [1, 2, 3, 4, 5, 6] Converting a sentence into a List of words using split() Function: Below is the implementation to convert a sentence into a list of words: Python3 # Python program to convert# a sentence to a list of words # Given sentencesentence = "GeeksforGeeks is the computer science portal for geeks" # Convert the sentence# into a list of wordslis = list(sentence.split()) # Print the list of wordsprint(lis) ['GeeksforGeeks', 'is', 'the', 'computer', 'science', 'portal', 'for', 'geeks'] Take newline-separated integers as a List: Newline-separated input from the console can be taken in the form of a List using List Comprehension. Below is the implementation to take input of newline-separated integers as a list: Python3 # Python program to take# newline-separated input# in the form of a list # Given inputn = int(input()) lis = [int(input()) for _ in range(n)] Calculating GCD/HCF of two numbers: Gcd of two numbers can be computed in python using a built-in function gcd() offered by the Python Math Module. Below is the implementation to demonstrate gcd() function: Python3 # Python program to demonstrate gcd() functionimport matha = 8b = 24 # Print the GCD of a and bprint(math.gcd(a, b)) 8 Print permutations of array: All permutations of an array can be efficiently generated using built-in permutations() method from itertools package. This method takes a List as input and returns an object List of Tuples that contains all permutations. Below is the implementation of the approach: Python3 # Python program to print all# permutations using library functionfrom itertools import permutations # Get all permutations of [1, 2, 3]perm = permutations([1, 2, 3]) # Print the obtained permutationsfor i in list(perm): print (i) (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) Printing a string multiple times without Loop: Below is the implementation to print a string multiple times without loop using string multiplication technique: Python3 # Python program to print# a string given number of times # Given stringstr ="India" # Print the string 2 timesprint(str * 2) IndiaIndia To print a list with spaces without loop: A list can be printed without running the loop by using the * operator in Python. Below is the implementation to print a list with spaces without loop: Python3 # Python program to print a list with spaces without looplis = [1, 2, 3, 4] # Printing list elements with spacesprint(*lis) 1 2 3 4 Convert binary string to decimal: A binary string can be converted to its decimal equivalent using built-in int() function. Below is the implementation of the above approach: Python3 # Python program to convert a# binary string to its decimal# equivalent using int() function # Given stringbinary = "1010" # Print decimal equivalentprint(int(binary, 2)) 10 To print sorted list with spaces: Sorting any sequence is very easy in Python using a built-in method sorted() and using * symbol to print list with spaces. Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence. Below is the implementation to print a sorted list with spaces: Python3 # Python program to print a sorted list with# spaces using sorted() functionlis = [6, 2, 7, 3, 4] # Print the sorted sequenceprint(*sorted(lis)) 2 3 4 6 7 To find common elements in two arrays: The common elements in 2 arrays/lists can be done in a much simpler way using sets. The intersection() function in Python gives the common elements in both arrays/lists. Below is the implementation to demonstrate intersection() function: Python3 # Python program to print common elements in# both the list using intersection() functionarray1 = [4, 5, 6, 7, 8]array2 = [3, 4, 5, 1, 72] # Print the common elementsprint(set(array1).intersection(set(array2))) {4, 5} abhishek0719kadiyan Python-itertools Python-Library python-list Python-list-of-lists python-map Competitive Programming Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Breadth First Traversal ( BFS ) on a 2D array Runtime Errors Multistage Graph (Shortest Path) Most important type of Algorithms Shortest path in a directed graph by Dijkstra’s algorithm Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 24658, "s": 24630, "text": "\n19 Aug, 2021" }, { "code": null, "e": 24951, "s": 24658, "text": "Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips:" }, { "code": null, "e": 25016, "s": 24951, "text": "Converting a number into a List of digits using map() Function: " }, { "code": null, "e": 25093, "s": 25016, "text": "Below is the implementation to convert a given number into a list of digits:" }, { "code": null, "e": 25101, "s": 25093, "text": "Python3" }, { "code": "# Python program to convert a# number to a list of digits # Given numbern = 123456 # Stores the list of digitslis = list(map(int, str(n))) # Print the digitsprint(lis)", "e": 25269, "s": 25101, "text": null }, { "code": null, "e": 25288, "s": 25269, "text": "[1, 2, 3, 4, 5, 6]" }, { "code": null, "e": 25429, "s": 25290, "text": "Converting a sentence into a List of words using split() Function: Below is the implementation to convert a sentence into a list of words:" }, { "code": null, "e": 25437, "s": 25429, "text": "Python3" }, { "code": "# Python program to convert# a sentence to a list of words # Given sentencesentence = \"GeeksforGeeks is the computer science portal for geeks\" # Convert the sentence# into a list of wordslis = list(sentence.split()) # Print the list of wordsprint(lis)", "e": 25689, "s": 25437, "text": null }, { "code": null, "e": 25769, "s": 25689, "text": "['GeeksforGeeks', 'is', 'the', 'computer', 'science', 'portal', 'for', 'geeks']" }, { "code": null, "e": 25999, "s": 25771, "text": "Take newline-separated integers as a List: Newline-separated input from the console can be taken in the form of a List using List Comprehension. Below is the implementation to take input of newline-separated integers as a list:" }, { "code": null, "e": 26007, "s": 25999, "text": "Python3" }, { "code": "# Python program to take# newline-separated input# in the form of a list # Given inputn = int(input()) lis = [int(input()) for _ in range(n)]", "e": 26149, "s": 26007, "text": null }, { "code": null, "e": 26297, "s": 26149, "text": "Calculating GCD/HCF of two numbers: Gcd of two numbers can be computed in python using a built-in function gcd() offered by the Python Math Module." }, { "code": null, "e": 26357, "s": 26297, "text": "Below is the implementation to demonstrate gcd() function: " }, { "code": null, "e": 26365, "s": 26357, "text": "Python3" }, { "code": "# Python program to demonstrate gcd() functionimport matha = 8b = 24 # Print the GCD of a and bprint(math.gcd(a, b))", "e": 26482, "s": 26365, "text": null }, { "code": null, "e": 26484, "s": 26482, "text": "8" }, { "code": null, "e": 26737, "s": 26486, "text": "Print permutations of array: All permutations of an array can be efficiently generated using built-in permutations() method from itertools package. This method takes a List as input and returns an object List of Tuples that contains all permutations." }, { "code": null, "e": 26782, "s": 26737, "text": "Below is the implementation of the approach:" }, { "code": null, "e": 26790, "s": 26782, "text": "Python3" }, { "code": "# Python program to print all# permutations using library functionfrom itertools import permutations # Get all permutations of [1, 2, 3]perm = permutations([1, 2, 3]) # Print the obtained permutationsfor i in list(perm): print (i)", "e": 27024, "s": 26790, "text": null }, { "code": null, "e": 27084, "s": 27024, "text": "(1, 2, 3)\n(1, 3, 2)\n(2, 1, 3)\n(2, 3, 1)\n(3, 1, 2)\n(3, 2, 1)" }, { "code": null, "e": 27246, "s": 27086, "text": "Printing a string multiple times without Loop: Below is the implementation to print a string multiple times without loop using string multiplication technique:" }, { "code": null, "e": 27254, "s": 27246, "text": "Python3" }, { "code": "# Python program to print# a string given number of times # Given stringstr =\"India\" # Print the string 2 timesprint(str * 2)", "e": 27380, "s": 27254, "text": null }, { "code": null, "e": 27391, "s": 27380, "text": "IndiaIndia" }, { "code": null, "e": 27517, "s": 27393, "text": "To print a list with spaces without loop: A list can be printed without running the loop by using the * operator in Python." }, { "code": null, "e": 27588, "s": 27517, "text": "Below is the implementation to print a list with spaces without loop: " }, { "code": null, "e": 27596, "s": 27588, "text": "Python3" }, { "code": "# Python program to print a list with spaces without looplis = [1, 2, 3, 4] # Printing list elements with spacesprint(*lis)", "e": 27720, "s": 27596, "text": null }, { "code": null, "e": 27728, "s": 27720, "text": "1 2 3 4" }, { "code": null, "e": 27854, "s": 27730, "text": "Convert binary string to decimal: A binary string can be converted to its decimal equivalent using built-in int() function." }, { "code": null, "e": 27906, "s": 27854, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27914, "s": 27906, "text": "Python3" }, { "code": "# Python program to convert a# binary string to its decimal# equivalent using int() function # Given stringbinary = \"1010\" # Print decimal equivalentprint(int(binary, 2))", "e": 28085, "s": 27914, "text": null }, { "code": null, "e": 28088, "s": 28085, "text": "10" }, { "code": null, "e": 28392, "s": 28088, "text": "To print sorted list with spaces: Sorting any sequence is very easy in Python using a built-in method sorted() and using * symbol to print list with spaces. Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence." }, { "code": null, "e": 28457, "s": 28392, "text": "Below is the implementation to print a sorted list with spaces: " }, { "code": null, "e": 28465, "s": 28457, "text": "Python3" }, { "code": "# Python program to print a sorted list with# spaces using sorted() functionlis = [6, 2, 7, 3, 4] # Print the sorted sequenceprint(*sorted(lis))", "e": 28610, "s": 28465, "text": null }, { "code": null, "e": 28620, "s": 28610, "text": "2 3 4 6 7" }, { "code": null, "e": 28831, "s": 28622, "text": "To find common elements in two arrays: The common elements in 2 arrays/lists can be done in a much simpler way using sets. The intersection() function in Python gives the common elements in both arrays/lists." }, { "code": null, "e": 28899, "s": 28831, "text": "Below is the implementation to demonstrate intersection() function:" }, { "code": null, "e": 28907, "s": 28899, "text": "Python3" }, { "code": "# Python program to print common elements in# both the list using intersection() functionarray1 = [4, 5, 6, 7, 8]array2 = [3, 4, 5, 1, 72] # Print the common elementsprint(set(array1).intersection(set(array2)))", "e": 29118, "s": 28907, "text": null }, { "code": null, "e": 29125, "s": 29118, "text": "{4, 5}" }, { "code": null, "e": 29147, "s": 29127, "text": "abhishek0719kadiyan" }, { "code": null, "e": 29164, "s": 29147, "text": "Python-itertools" }, { "code": null, "e": 29179, "s": 29164, "text": "Python-Library" }, { "code": null, "e": 29191, "s": 29179, "text": "python-list" }, { "code": null, "e": 29212, "s": 29191, "text": "Python-list-of-lists" }, { "code": null, "e": 29223, "s": 29212, "text": "python-map" }, { "code": null, "e": 29247, "s": 29223, "text": "Competitive Programming" }, { "code": null, "e": 29263, "s": 29247, "text": "Python Programs" }, { "code": null, "e": 29275, "s": 29263, "text": "python-list" }, { "code": null, "e": 29373, "s": 29275, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29382, "s": 29373, "text": "Comments" }, { "code": null, "e": 29395, "s": 29382, "text": "Old Comments" }, { "code": null, "e": 29441, "s": 29395, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 29456, "s": 29441, "text": "Runtime Errors" }, { "code": null, "e": 29489, "s": 29456, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 29523, "s": 29489, "text": "Most important type of Algorithms" }, { "code": null, "e": 29581, "s": 29523, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 29624, "s": 29581, "text": "Python program to convert a list to string" }, { "code": null, "e": 29646, "s": 29624, "text": "Defaultdict in Python" }, { "code": null, "e": 29685, "s": 29646, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29731, "s": 29685, "text": "Python | Split string into list of characters" } ]
CSS - text-transform
The text-transform property changes the capitalization of text within an element, or else directs the user agent to leave the capitalization "as is." capitalize − The first letter of each word in the element's text should be capitalized. capitalize − The first letter of each word in the element's text should be capitalized. uppercase − All of the characters in the element's text should be uppercase (capital letters). uppercase − All of the characters in the element's text should be uppercase (capital letters). lowercase − All of the characters in the element's text should be lowercase. lowercase − All of the characters in the element's text should be lowercase. none - The capitalization of the element's text should not be altered. none - The capitalization of the element's text should not be altered. All the HTML elements. object.style.textTransform = "uppercase"; Following is the example which demonstrates how to set the cases for a text using text-transform property. <html> <head> </head> <body> <p style = "text-transform:capitalize;"> This will be capitalized </p> <p style = "text-transform:uppercase;"> This will be in uppercase </p> <p style = "text-transform:lowercase;"> This will be in lowercase </p> </body> </html> This will produce following result − This will be capitalized This will be in uppercase This will be in lowercase 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2777, "s": 2626, "text": "The text-transform property changes the capitalization of text within an element, or else directs the user agent to leave the capitalization \"as is.\"" }, { "code": null, "e": 2865, "s": 2777, "text": "capitalize − The first letter of each word in the element's text should be capitalized." }, { "code": null, "e": 2953, "s": 2865, "text": "capitalize − The first letter of each word in the element's text should be capitalized." }, { "code": null, "e": 3048, "s": 2953, "text": "uppercase − All of the characters in the element's text should be uppercase (capital letters)." }, { "code": null, "e": 3143, "s": 3048, "text": "uppercase − All of the characters in the element's text should be uppercase (capital letters)." }, { "code": null, "e": 3220, "s": 3143, "text": "lowercase − All of the characters in the element's text should be lowercase." }, { "code": null, "e": 3297, "s": 3220, "text": "lowercase − All of the characters in the element's text should be lowercase." }, { "code": null, "e": 3368, "s": 3297, "text": "none - The capitalization of the element's text should not be altered." }, { "code": null, "e": 3439, "s": 3368, "text": "none - The capitalization of the element's text should not be altered." }, { "code": null, "e": 3462, "s": 3439, "text": "All the HTML elements." }, { "code": null, "e": 3505, "s": 3462, "text": "object.style.textTransform = \"uppercase\";\n" }, { "code": null, "e": 3612, "s": 3505, "text": "Following is the example which demonstrates how to set the cases for a text using text-transform property." }, { "code": null, "e": 3961, "s": 3612, "text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"text-transform:capitalize;\">\n This will be capitalized\n </p>\n \n <p style = \"text-transform:uppercase;\">\n This will be in uppercase\n </p>\n \n <p style = \"text-transform:lowercase;\">\n This will be in lowercase\n </p>\n </body>\n</html> " }, { "code": null, "e": 3998, "s": 3961, "text": "This will produce following result −" }, { "code": null, "e": 4028, "s": 3998, "text": "\n This will be capitalized\n" }, { "code": null, "e": 4059, "s": 4028, "text": "\n This will be in uppercase\n" }, { "code": null, "e": 4090, "s": 4059, "text": "\n This will be in lowercase\n" }, { "code": null, "e": 4125, "s": 4090, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4139, "s": 4125, "text": " Anadi Sharma" }, { "code": null, "e": 4174, "s": 4139, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4191, "s": 4174, "text": " Frahaan Hussain" }, { "code": null, "e": 4226, "s": 4191, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4257, "s": 4226, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4292, "s": 4257, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4323, "s": 4292, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4358, "s": 4323, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4389, "s": 4358, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4422, "s": 4389, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 4453, "s": 4422, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4460, "s": 4453, "text": " Print" }, { "code": null, "e": 4471, "s": 4460, "text": " Add Notes" } ]
Creating a linked list using Javascript
Let's start by defining a simple class with a constructor that initializes the head to null. We'll also define another structure on the prototype of the LinkedList class that'll represent each node in the linked list. class LinkedList { constructor() { this.head = null; this.length = 0; } } LinkedList.prototype.Node = class { constructor(data) { this.data = data; this.next = null; } } Let's also create a display function that'll help us see how our list looks like. This function works as follows. It starts from the head. It iterates over the list using currElem = currElem.next till currElem doesn't become null, ie, we've not reached the end. It prints data for each of the iterations. Here is an illustration for the same − Now let's have a look at how we'll implement this − display() { let currNode = this.head; while (currNode != null) { console.log(currNode.data + " -> "); currNode = currNode.next; } }
[ { "code": null, "e": 1280, "s": 1062, "text": "Let's start by defining a simple class with a constructor that initializes the head to null. We'll also define another structure on the prototype of the LinkedList class that'll represent each node in the linked list." }, { "code": null, "e": 1481, "s": 1280, "text": "class LinkedList {\n constructor() {\n this.head = null;\n this.length = 0;\n }\n}\nLinkedList.prototype.Node = class {\n constructor(data) {\n this.data = data; this.next = null;\n }\n}" }, { "code": null, "e": 1595, "s": 1481, "text": "Let's also create a display function that'll help us see how our list looks like. This function works as follows." }, { "code": null, "e": 1620, "s": 1595, "text": "It starts from the head." }, { "code": null, "e": 1743, "s": 1620, "text": "It iterates over the list using currElem = currElem.next till currElem doesn't become null, ie, we've not reached the end." }, { "code": null, "e": 1786, "s": 1743, "text": "It prints data for each of the iterations." }, { "code": null, "e": 1825, "s": 1786, "text": "Here is an illustration for the same −" }, { "code": null, "e": 1877, "s": 1825, "text": "Now let's have a look at how we'll implement this −" }, { "code": null, "e": 2030, "s": 1877, "text": "display() {\n let currNode = this.head;\n while (currNode != null) {\n console.log(currNode.data + \" -> \");\n currNode = currNode.next;\n }\n}" } ]
How to implement endless list with RecyclerView in Android?
This example demonstrates how do I implement an endless list with RecyclerView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Add the following dependency in build gradle (Module app) − implementation 'com.android.support:cardview-v7:28.0.0' implementation 'com.android.support:recyclerview-v7:28.0.0' Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; RecyclerViewAdapter recyclerViewAdapter; ArrayList<String>rowsArrayList = new ArrayList<>(); boolean isLoading = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerView); populateData(); initAdapter(); initScrollListener(); } private void populateData() { for (int i = 0; i < 10; i++) { rowsArrayList.add("Number " + i); } } private void initAdapter() { recyclerViewAdapter = new RecyclerViewAdapter(rowsArrayList); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); recyclerView.setAdapter(recyclerViewAdapter); } private void initScrollListener() { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); if (!isLoading) { if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size() - 1) { //bottom of list! loadMore(); isLoading = true; } } } }); } private void loadMore() { rowsArrayList.add(null); recyclerViewAdapter.notifyItemInserted(rowsArrayList.size() - 1); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { rowsArrayList.remove(rowsArrayList.size() - 1); int scrollPosition = rowsArrayList.size(); recyclerViewAdapter.notifyItemRemoved(scrollPosition); int currentSize = scrollPosition; int nextLimit = currentSize + 10; while (currentSize - 1 < nextLimit) { rowsArrayList.add("Number " + currentSize); currentSize++; } recyclerViewAdapter.notifyDataSetChanged(); isLoading = false; } }, 2000); } } Step 4 − Create a new Java Class (RecyclerViewAdapter.java) and add the following code − package app.com.sample; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final int VIEW_TYPE_ITEM = 0; private List<String> mItemList; RecyclerViewAdapter(List<String> itemList) { mItemList = itemList; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { if (viewType == VIEW_TYPE_ITEM) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false); return new ItemViewHolder(view); } else { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false); return new LoadingViewHolder(view); } } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { if (viewHolder instanceof ItemViewHolder) { populateItemRows((ItemViewHolder) viewHolder, position); } else if (viewHolder instanceof LoadingViewHolder) { showLoadingView((LoadingViewHolder) viewHolder, position); } } @Override public int getItemCount() { return mItemList == null ? 0 : mItemList.size(); } @Override public int getItemViewType(int position) { int VIEW_TYPE_LOADING = 1; return mItemList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM; } private class ItemViewHolder extends RecyclerView.ViewHolder { TextView tvItem; ItemViewHolder(@NonNull View itemView) { super(itemView); tvItem = itemView.findViewById(R.id.textViewItem); } } private class LoadingViewHolder extends RecyclerView.ViewHolder { ProgressBar progressBar; LoadingViewHolder(@NonNull View itemView) { super(itemView); progressBar = itemView.findViewById(R.id.progressBar); } } private void showLoadingView(LoadingViewHolder viewHolder, int position) { } private void populateItemRows(ItemViewHolder viewHolder, int position) { String item = mItemList.get(position); viewHolder.tvItem.setText(item); } } Step 5 − Create a new Layout resource file(item_row.xml) and add the following code − <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" app:cardElevation="2dp" app:cardUseCompatPadding="true"> <TextView android:id="@+id/textViewItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" /> </androidx.cardview.widget.CardView> Step 6 − Create a new Layout resource file(item_loading.xml) and add the following code − <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:indeterminate="true" android:paddingLeft="8dp" android:paddingRight="8dp" /> </LinearLayout> Step 7 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrates how do I implement an endless list with RecyclerView in android." }, { "code": null, "e": 1282, "s": 1153, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1342, "s": 1282, "text": "Add the following dependency in build gradle (Module app) −" }, { "code": null, "e": 1458, "s": 1342, "text": "implementation 'com.android.support:cardview-v7:28.0.0'\nimplementation 'com.android.support:recyclerview-v7:28.0.0'" }, { "code": null, "e": 1523, "s": 1458, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2019, "s": 1523, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\">\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/recyclerView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2076, "s": 2019, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4929, "s": 2076, "text": "import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n RecyclerView recyclerView;\n RecyclerViewAdapter recyclerViewAdapter;\n ArrayList<String>rowsArrayList = new ArrayList<>();\n boolean isLoading = false;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n recyclerView = findViewById(R.id.recyclerView);\n populateData();\n initAdapter();\n initScrollListener();\n }\n private void populateData() {\n for (int i = 0; i < 10; i++) {\n rowsArrayList.add(\"Number \" + i);\n }\n }\n private void initAdapter() {\n recyclerViewAdapter = new RecyclerViewAdapter(rowsArrayList);\n recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));\n recyclerView.setAdapter(recyclerViewAdapter);\n }\n private void initScrollListener() {\n recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n @Override\n public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {\n super.onScrollStateChanged(recyclerView, newState);\n }\n @Override\n public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();\n if (!isLoading) {\n if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == rowsArrayList.size() - 1) {\n //bottom of list!\n loadMore();\n isLoading = true;\n }\n }\n }\n });\n }\n private void loadMore() {\n rowsArrayList.add(null);\n recyclerViewAdapter.notifyItemInserted(rowsArrayList.size() - 1);\n Handler handler = new Handler();\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n rowsArrayList.remove(rowsArrayList.size() - 1);\n int scrollPosition = rowsArrayList.size();\n recyclerViewAdapter.notifyItemRemoved(scrollPosition);\n int currentSize = scrollPosition;\n int nextLimit = currentSize + 10;\n while (currentSize - 1 < nextLimit) {\n rowsArrayList.add(\"Number \" + currentSize);\n currentSize++;\n }\n recyclerViewAdapter.notifyDataSetChanged();\n isLoading = false;\n }\n }, 2000);\n }\n}" }, { "code": null, "e": 5018, "s": 4929, "text": "Step 4 − Create a new Java Class (RecyclerViewAdapter.java) and add the following code −" }, { "code": null, "e": 7445, "s": 5018, "text": "package app.com.sample;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\nimport java.util.List;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\npublic class RecyclerViewAdapter extends\nRecyclerView.Adapter<RecyclerView.ViewHolder> {\n private final int VIEW_TYPE_ITEM = 0;\n private List<String> mItemList;\n RecyclerViewAdapter(List<String> itemList) {\n mItemList = itemList;\n }\n @NonNull\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n if (viewType == VIEW_TYPE_ITEM) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);\n return new ItemViewHolder(view);\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);\n return new LoadingViewHolder(view);\n }\n }\n @Override\n public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {\n if (viewHolder instanceof ItemViewHolder) {\n populateItemRows((ItemViewHolder) viewHolder, position);\n }\n else if (viewHolder instanceof LoadingViewHolder) {\n showLoadingView((LoadingViewHolder) viewHolder, position);\n }\n }\n @Override\n public int getItemCount() {\n return mItemList == null ? 0 : mItemList.size();\n }\n @Override\n public int getItemViewType(int position) {\n int VIEW_TYPE_LOADING = 1;\n return mItemList.get(position) == null ? VIEW_TYPE_LOADING :\n VIEW_TYPE_ITEM;\n }\n private class ItemViewHolder extends RecyclerView.ViewHolder {\n TextView tvItem;\n ItemViewHolder(@NonNull View itemView) {\n super(itemView);\n tvItem = itemView.findViewById(R.id.textViewItem);\n }\n }\n private class LoadingViewHolder extends RecyclerView.ViewHolder {\n ProgressBar progressBar;\n LoadingViewHolder(@NonNull View itemView) {\n super(itemView);\n progressBar = itemView.findViewById(R.id.progressBar);\n }\n }\n private void showLoadingView(LoadingViewHolder viewHolder, int position) {\n }\n private void populateItemRows(ItemViewHolder viewHolder, int position) {\n String item = mItemList.get(position);\n viewHolder.tvItem.setText(item);\n }\n}" }, { "code": null, "e": 7531, "s": 7445, "text": "Step 5 − Create a new Layout resource file(item_row.xml) and add the following code −" }, { "code": null, "e": 8065, "s": 7531, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.cardview.widget.CardView\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n app:cardElevation=\"2dp\"\n app:cardUseCompatPadding=\"true\">\n <TextView\n android:id=\"@+id/textViewItem\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"16dp\" />\n</androidx.cardview.widget.CardView>" }, { "code": null, "e": 8155, "s": 8065, "text": "Step 6 − Create a new Layout resource file(item_loading.xml) and add the following code −" }, { "code": null, "e": 8686, "s": 8155, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\">\n <ProgressBar\n android:id=\"@+id/progressBar\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center_horizontal\"\n android:indeterminate=\"true\"\n android:paddingLeft=\"8dp\"\n android:paddingRight=\"8dp\" />\n</LinearLayout>" }, { "code": null, "e": 8741, "s": 8686, "text": "Step 7 − Add the following code to androidManifest.xml" }, { "code": null, "e": 9412, "s": 8741, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>\n" }, { "code": null, "e": 9763, "s": 9412, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 9804, "s": 9763, "text": "Click here to download the project code." } ]
C++ Basics: Understanding Lambda. A convenient way to define a functor... | by Debby Nirwan | Towards Data Science
One of the new features introduced in Modern C++ starting from C++11 is Lambda Expression. It is a convenient way to define an anonymous function object or functor. It is convenient because we can define it locally where we want to call it or pass it to a function as an argument. Lambda is easy to read too because we can keep everything in the same place. In this post, we’ll look at what a lambda is, compare it with a function object (functor), and more importantly understand what it actually is and how to think about it when coding in C++. This is how we define a lambda in C++: plus_one in this code is a functor under the hood. Let’s now first see what a functor is. According to Wikipedia, A function object or usually referred to as a functor is a construct that allows an object to be called as if it were an ordinary function. The keyword here is the “ordinary function”. In C++ we can overload operator () to implement a functor. Here is a functor that behaves the same as our lambda: One example of the advantages of using a functor over an ordinary function is that it can access the internal member variables and functions of that object. It will be clearer when we want to create functions “plus one”, “plus two”, etc. By using a functor we don’t have to define multiple functions with unique names. As you can see, at the caller side it looks like a call to an ordinary function. How does it look like at the machine level? Well, a functor is an object so it has member variables and member functions. The ordinary function is as follows: int plus_one(const int value){ return value + 1;} whereas a functor is as follows: int PlusOne::operator()(const PlusOne* this, const int value){ return value + this->data;} If we already have a functor which in some scenarios is better than an ordinary function, why do we need lambda? Lambda offers a simpler way to write a functor. It is a syntactic sugar for an anonymous functor. It reduces the boilerplate that we need to write in a functor. To see how lambda simplifies a functor, we create a lambda for our Plus class above. We can remove a lot of boilerplate code from our functor above. We know that our functor looks like this: int PlusOne::operator()(const PlusOne* this, const int value){ return value + this->data;} What about our lambda? By assuming we define our lambda inside our main function this is how it looks like: int main::lambda::operator()(const lambda* hidden, const int value){ return value + hidden->data;} It’s very much similar to our functor other than the name. So now we know that our lambda is just a functor, without a name and with a simplified form. Another thing that you may notice is the hidden pointer’s name isn’t called this because the this keyword is used for the outer scope’s object. Both functors and lambdas are often used for writing callback functions. They are very useful when we deal with STL algorithms. For example when we want to transform our data stored in a std::vector. With a functor we can write it as follows: After calling std::transform, we’ll get {2, 3, 4, 5}. With lambda this is how we write it: We can see that it is much neater with a lambda where we can read the code without having to jump to another place to see what operation is done to transform our test_data. We should think about a lambda as an object, to create and initialize member variables we use the capture ‘[]’ mechanism. To create and initialize a variable we can simply write it in ‘[]’: auto return_one = [value=1](){ return value; }; We can also make a copy of another object in the scope: void func(){ int a = 1; // by value auto return_one = [value=a](){ return value; };}void func(){ int a = 1; // by reference auto return_one = [&value=a](){ return value; };} Some other things that are important to know about lambdas are: It can be converted to a raw function pointer if it doesn’t capture The code above won’t compile because the lambda is not convertible to a function pointer according to the standard, the most obvious reason is that there is a hidden parameter in the operator(). But it is convertible if it doesn’t capture, so the following compiles: This is because there exists a user-defined conversion function for capture-less lambdas. int(*GetValue)() = [](){return 1;} By default the overloaded operator() is const This code won’t compile because we are trying to modify a member variable in a const function. Remember that it looks like this under the hood: int main::lambda::operator()(const lambda* hidden){ return hidden->value++;} The hidden pointer points to a constant lambda object hence the error. To modify the captured variable, we add a mutable keyword as follows: We have seen one way to pass a lambda as an argument above, via conversion to a raw function pointer. But that only works for capture-less lambdas. There are two ways to pass lambdas as arguments of functions: The STL way, with template Use std::function We have seen that lambda is just a convenient way to write a functor, therefore we should always think about it as a functor when coding in C++. We should use lambdas where we can improve the readability of and simplify our code such as when writing callback functions. I hope this post is useful for you because starting from the basics will help us in the long term. Here are some useful references:
[ { "code": null, "e": 263, "s": 172, "text": "One of the new features introduced in Modern C++ starting from C++11 is Lambda Expression." }, { "code": null, "e": 453, "s": 263, "text": "It is a convenient way to define an anonymous function object or functor. It is convenient because we can define it locally where we want to call it or pass it to a function as an argument." }, { "code": null, "e": 530, "s": 453, "text": "Lambda is easy to read too because we can keep everything in the same place." }, { "code": null, "e": 719, "s": 530, "text": "In this post, we’ll look at what a lambda is, compare it with a function object (functor), and more importantly understand what it actually is and how to think about it when coding in C++." }, { "code": null, "e": 758, "s": 719, "text": "This is how we define a lambda in C++:" }, { "code": null, "e": 848, "s": 758, "text": "plus_one in this code is a functor under the hood. Let’s now first see what a functor is." }, { "code": null, "e": 1012, "s": 848, "text": "According to Wikipedia, A function object or usually referred to as a functor is a construct that allows an object to be called as if it were an ordinary function." }, { "code": null, "e": 1171, "s": 1012, "text": "The keyword here is the “ordinary function”. In C++ we can overload operator () to implement a functor. Here is a functor that behaves the same as our lambda:" }, { "code": null, "e": 1328, "s": 1171, "text": "One example of the advantages of using a functor over an ordinary function is that it can access the internal member variables and functions of that object." }, { "code": null, "e": 1490, "s": 1328, "text": "It will be clearer when we want to create functions “plus one”, “plus two”, etc. By using a functor we don’t have to define multiple functions with unique names." }, { "code": null, "e": 1571, "s": 1490, "text": "As you can see, at the caller side it looks like a call to an ordinary function." }, { "code": null, "e": 1730, "s": 1571, "text": "How does it look like at the machine level? Well, a functor is an object so it has member variables and member functions. The ordinary function is as follows:" }, { "code": null, "e": 1781, "s": 1730, "text": "int plus_one(const int value){ return value + 1;}" }, { "code": null, "e": 1814, "s": 1781, "text": "whereas a functor is as follows:" }, { "code": null, "e": 1906, "s": 1814, "text": "int PlusOne::operator()(const PlusOne* this, const int value){ return value + this->data;}" }, { "code": null, "e": 2019, "s": 1906, "text": "If we already have a functor which in some scenarios is better than an ordinary function, why do we need lambda?" }, { "code": null, "e": 2180, "s": 2019, "text": "Lambda offers a simpler way to write a functor. It is a syntactic sugar for an anonymous functor. It reduces the boilerplate that we need to write in a functor." }, { "code": null, "e": 2265, "s": 2180, "text": "To see how lambda simplifies a functor, we create a lambda for our Plus class above." }, { "code": null, "e": 2371, "s": 2265, "text": "We can remove a lot of boilerplate code from our functor above. We know that our functor looks like this:" }, { "code": null, "e": 2463, "s": 2371, "text": "int PlusOne::operator()(const PlusOne* this, const int value){ return value + this->data;}" }, { "code": null, "e": 2571, "s": 2463, "text": "What about our lambda? By assuming we define our lambda inside our main function this is how it looks like:" }, { "code": null, "e": 2671, "s": 2571, "text": "int main::lambda::operator()(const lambda* hidden, const int value){ return value + hidden->data;}" }, { "code": null, "e": 2823, "s": 2671, "text": "It’s very much similar to our functor other than the name. So now we know that our lambda is just a functor, without a name and with a simplified form." }, { "code": null, "e": 2967, "s": 2823, "text": "Another thing that you may notice is the hidden pointer’s name isn’t called this because the this keyword is used for the outer scope’s object." }, { "code": null, "e": 3210, "s": 2967, "text": "Both functors and lambdas are often used for writing callback functions. They are very useful when we deal with STL algorithms. For example when we want to transform our data stored in a std::vector. With a functor we can write it as follows:" }, { "code": null, "e": 3301, "s": 3210, "text": "After calling std::transform, we’ll get {2, 3, 4, 5}. With lambda this is how we write it:" }, { "code": null, "e": 3474, "s": 3301, "text": "We can see that it is much neater with a lambda where we can read the code without having to jump to another place to see what operation is done to transform our test_data." }, { "code": null, "e": 3664, "s": 3474, "text": "We should think about a lambda as an object, to create and initialize member variables we use the capture ‘[]’ mechanism. To create and initialize a variable we can simply write it in ‘[]’:" }, { "code": null, "e": 3712, "s": 3664, "text": "auto return_one = [value=1](){ return value; };" }, { "code": null, "e": 3768, "s": 3712, "text": "We can also make a copy of another object in the scope:" }, { "code": null, "e": 3948, "s": 3768, "text": "void func(){ int a = 1; // by value auto return_one = [value=a](){ return value; };}void func(){ int a = 1; // by reference auto return_one = [&value=a](){ return value; };}" }, { "code": null, "e": 4012, "s": 3948, "text": "Some other things that are important to know about lambdas are:" }, { "code": null, "e": 4080, "s": 4012, "text": "It can be converted to a raw function pointer if it doesn’t capture" }, { "code": null, "e": 4347, "s": 4080, "text": "The code above won’t compile because the lambda is not convertible to a function pointer according to the standard, the most obvious reason is that there is a hidden parameter in the operator(). But it is convertible if it doesn’t capture, so the following compiles:" }, { "code": null, "e": 4437, "s": 4347, "text": "This is because there exists a user-defined conversion function for capture-less lambdas." }, { "code": null, "e": 4472, "s": 4437, "text": "int(*GetValue)() = [](){return 1;}" }, { "code": null, "e": 4518, "s": 4472, "text": "By default the overloaded operator() is const" }, { "code": null, "e": 4662, "s": 4518, "text": "This code won’t compile because we are trying to modify a member variable in a const function. Remember that it looks like this under the hood:" }, { "code": null, "e": 4740, "s": 4662, "text": "int main::lambda::operator()(const lambda* hidden){ return hidden->value++;}" }, { "code": null, "e": 4881, "s": 4740, "text": "The hidden pointer points to a constant lambda object hence the error. To modify the captured variable, we add a mutable keyword as follows:" }, { "code": null, "e": 5029, "s": 4881, "text": "We have seen one way to pass a lambda as an argument above, via conversion to a raw function pointer. But that only works for capture-less lambdas." }, { "code": null, "e": 5091, "s": 5029, "text": "There are two ways to pass lambdas as arguments of functions:" }, { "code": null, "e": 5118, "s": 5091, "text": "The STL way, with template" }, { "code": null, "e": 5136, "s": 5118, "text": "Use std::function" }, { "code": null, "e": 5281, "s": 5136, "text": "We have seen that lambda is just a convenient way to write a functor, therefore we should always think about it as a functor when coding in C++." }, { "code": null, "e": 5406, "s": 5281, "text": "We should use lambdas where we can improve the readability of and simplify our code such as when writing callback functions." }, { "code": null, "e": 5505, "s": 5406, "text": "I hope this post is useful for you because starting from the basics will help us in the long term." } ]
Java Examples - Edit Table
How to edit(Add or update) columns of a Table and how to delete a table? Following example uses create, alter & drop SQL commands to create, edit or delete table. import java.sql.*; public class jdbcConn { public static void main(String[] args) throws Exception { Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con = DriverManager.getConnection( "jdbc:derby://localhost:1527/testDb","username", "password"); Statement stmt = con.createStatement(); String query ="CREATE TABLE employees(id INTEGER PRIMARY KEY, first_name CHAR(50), last_name CHAR(75))"; stmt.execute(query); System.out.println("Employee table created"); String query1 = "aLTER TABLE employees ADD address CHAR(100) "; String query2 = "ALTER TABLE employees DROP COLUMN last_name"; stmt.execute(query1); stmt.execute(query2); System.out.println("Address column added to the table & last_name column removed from the table"); String query3 = "drop table employees"; stmt.execute(query3); System.out.println("Employees table removed"); } } The above code sample will produce the following result. The result may vary. Employee table created Address column added to the table & last_name column removed from the table Employees table removed from the database Print Add Notes Bookmark this page
[ { "code": null, "e": 2141, "s": 2068, "text": "How to edit(Add or update) columns of a Table and how to delete a table?" }, { "code": null, "e": 2231, "s": 2141, "text": "Following example uses create, alter & drop SQL commands to create, edit or delete table." }, { "code": null, "e": 3218, "s": 2231, "text": "import java.sql.*;\n\npublic class jdbcConn {\n public static void main(String[] args) throws Exception { \n Class.forName(\"org.apache.derby.jdbc.ClientDriver\");\n Connection con = DriverManager.getConnection(\n \"jdbc:derby://localhost:1527/testDb\",\"username\", \"password\");\n \n Statement stmt = con.createStatement();\n String query =\"CREATE TABLE employees(id INTEGER PRIMARY KEY, first_name CHAR(50), last_name CHAR(75))\";\n \n stmt.execute(query);\n System.out.println(\"Employee table created\");\n String query1 = \"aLTER TABLE employees ADD address CHAR(100) \";\n String query2 = \"ALTER TABLE employees DROP COLUMN last_name\";\n \n stmt.execute(query1);\n stmt.execute(query2);\n System.out.println(\"Address column added to the table & last_name column removed from the table\");\n \n String query3 = \"drop table employees\";\n stmt.execute(query3);\n System.out.println(\"Employees table removed\");\n }\t\n}" }, { "code": null, "e": 3296, "s": 3218, "text": "The above code sample will produce the following result. The result may vary." }, { "code": null, "e": 3439, "s": 3296, "text": "Employee table created\nAddress column added to the table & last_name \ncolumn removed from the table\nEmployees table removed from the database\n" }, { "code": null, "e": 3446, "s": 3439, "text": " Print" }, { "code": null, "e": 3457, "s": 3446, "text": " Add Notes" } ]
MySQL - SET PASSWORD Statement
You can password to an existing user using the MySQL SET PASSWORD Statement. Using this you can Set a specific password to a user account. Set a random password. Replace the current password with a new one. Retain the current password as its secondary password. Following is the syntax of the MySQL SET PASSWORD Statement − SET PASSWORD [FOR user_name] new_password [REPLACE 'current_password_string'] [RETAIN CURRENT PASSWORD] Where, user_name is the name of the user for which you need to change the password. Assume we have created a user named sample (without any password) using the CREATE USER Statement as shown below − mysql> CREATE USER 'tp'@'localhost'; Query OK, 0 rows affected (0.34 sec) To login as the above created user. Open command prompt, browse through the bin folder of MySQL installation folder and execute the command mysql -u user_name -p as − MySQL_Installation_Directorybin>mysql -u tp Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 35 Server version: 8.0.22 MySQL Community Server - GPL Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MySQL SET PASSWORD Statement mysql> Now you can assign a password of the current user account as shown below − mysql> SET PASSWORD ='mypassword123'; Query OK, 0 rows affected (0.59 sec) You set/assign password to a specific user using the FOR clause in the SET PASSWORD Statement − SET PASSWORD FOR user_name password_string Assume we have created a user named test using the CREATE USER statement. mysql> CREATE USER 'test'@'localhost'; Query OK, 0 rows affected (0.27 sec) Following query assigns password for the above created user − mysql> SET PASSWORD FOR 'test'@'localhost' = 'mypassword'; Query OK, 0 rows affected (0.21 sec) You can replace the existing password using the REPLACE clause along with the SET PASSWORD statement. SET PASSWORD = new_password REPLACE old_password; Assume we have created a user named test along with a password, using the CREATE USER statement. mysql> CREATE USER test@localhost IDENTIFIED BY 'test12345'; Query OK, 0 rows affected (0.18 sec) Login as the above created user. (Open command prompt, browse through the bin folder of MySQL installation folder and execute the following query) − MySQL_Installation_Directorybin>mysql -u tp -p ********* Following query replaces the password of the above created user − mysql> SET PASSWORD = 'newpassword' REPLACE 'test12345'; Query OK, 0 rows affected (0.12 sec) You can use REPLACE only for the current user You can assign random password using the RANDOM clause along with the SET PASSWORD Statement. SET PASSWORD TO RANDOM; Assume we have created a user named sample (without any password) using the CREATE USER Statement as shown below − mysql> CREATE USER 'tp'@'localhost'; Query OK, 0 rows affected (0.17 sec) Following query sets a random password of the above created user − mysql> SET PASSWORD FOR 'tp'@'localhost' TO RANDOM; +------+-----------+----------------------+ | user | host | generated password | +------+-----------+----------------------+ | tp | localhost | hTWnSP:h0eAe(ywVJArm | +------+-----------+----------------------+ 1 row in set (0.17 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2429, "s": 2333, "text": "You can password to an existing user using the MySQL SET PASSWORD Statement. Using this you can" }, { "code": null, "e": 2472, "s": 2429, "text": "Set a specific password to a user account." }, { "code": null, "e": 2495, "s": 2472, "text": "Set a random password." }, { "code": null, "e": 2540, "s": 2495, "text": "Replace the current password with a new one." }, { "code": null, "e": 2595, "s": 2540, "text": "Retain the current password as its secondary password." }, { "code": null, "e": 2657, "s": 2595, "text": "Following is the syntax of the MySQL SET PASSWORD Statement −" }, { "code": null, "e": 2768, "s": 2657, "text": "SET PASSWORD [FOR user_name] new_password\n [REPLACE 'current_password_string']\n [RETAIN CURRENT PASSWORD]\n" }, { "code": null, "e": 2852, "s": 2768, "text": "Where, user_name is the name of the user for which you need to change the password." }, { "code": null, "e": 2967, "s": 2852, "text": "Assume we have created a user named sample (without any password) using the CREATE USER Statement as shown below −" }, { "code": null, "e": 3041, "s": 2967, "text": "mysql> CREATE USER 'tp'@'localhost';\nQuery OK, 0 rows affected (0.34 sec)" }, { "code": null, "e": 3208, "s": 3041, "text": "To login as the above created user. Open command prompt, browse through the bin folder of MySQL installation folder and execute the command mysql -u user_name -p as −" }, { "code": null, "e": 3724, "s": 3208, "text": "MySQL_Installation_Directorybin>mysql -u tp\nWelcome to the MySQL monitor. Commands end with ; or \\g.\nYour MySQL connection id is 35\nServer version: 8.0.22 MySQL Community Server - GPL\n\nCopyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.\n\nOracle is a registered trademark of Oracle Corporation and/or its\naffiliates. Other names may be trademarks of their respective\nowners.\n\nType 'help;' or '\\h' for help. Type '\\c' to clear the current input statement. MySQL SET PASSWORD Statement\n\nmysql>" }, { "code": null, "e": 3799, "s": 3724, "text": "Now you can assign a password of the current user account as shown below −" }, { "code": null, "e": 3874, "s": 3799, "text": "mysql> SET PASSWORD ='mypassword123';\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 3970, "s": 3874, "text": "You set/assign password to a specific user using the FOR clause in the SET PASSWORD Statement −" }, { "code": null, "e": 4013, "s": 3970, "text": "SET PASSWORD FOR user_name password_string" }, { "code": null, "e": 4087, "s": 4013, "text": "Assume we have created a user named test using the CREATE USER statement." }, { "code": null, "e": 4163, "s": 4087, "text": "mysql> CREATE USER 'test'@'localhost';\nQuery OK, 0 rows affected (0.27 sec)" }, { "code": null, "e": 4225, "s": 4163, "text": "Following query assigns password for the above created user −" }, { "code": null, "e": 4321, "s": 4225, "text": "mysql> SET PASSWORD FOR 'test'@'localhost' = 'mypassword';\nQuery OK, 0 rows affected (0.21 sec)" }, { "code": null, "e": 4423, "s": 4321, "text": "You can replace the existing password using the REPLACE clause along with the SET PASSWORD statement." }, { "code": null, "e": 4473, "s": 4423, "text": "SET PASSWORD = new_password REPLACE old_password;" }, { "code": null, "e": 4570, "s": 4473, "text": "Assume we have created a user named test along with a password, using the CREATE USER statement." }, { "code": null, "e": 4668, "s": 4570, "text": "mysql> CREATE USER test@localhost IDENTIFIED BY 'test12345';\nQuery OK, 0 rows affected (0.18 sec)" }, { "code": null, "e": 4817, "s": 4668, "text": "Login as the above created user. (Open command prompt, browse through the bin folder of MySQL installation folder and execute the following query) −" }, { "code": null, "e": 4874, "s": 4817, "text": "MySQL_Installation_Directorybin>mysql -u tp -p\n*********" }, { "code": null, "e": 4940, "s": 4874, "text": "Following query replaces the password of the above created user −" }, { "code": null, "e": 5034, "s": 4940, "text": "mysql> SET PASSWORD = 'newpassword' REPLACE 'test12345';\nQuery OK, 0 rows affected (0.12 sec)" }, { "code": null, "e": 5080, "s": 5034, "text": "You can use REPLACE only for the current user" }, { "code": null, "e": 5174, "s": 5080, "text": "You can assign random password using the RANDOM clause along with the SET PASSWORD Statement." }, { "code": null, "e": 5198, "s": 5174, "text": "SET PASSWORD TO RANDOM;" }, { "code": null, "e": 5313, "s": 5198, "text": "Assume we have created a user named sample (without any password) using the CREATE USER Statement as shown below −" }, { "code": null, "e": 5387, "s": 5313, "text": "mysql> CREATE USER 'tp'@'localhost';\nQuery OK, 0 rows affected (0.17 sec)" }, { "code": null, "e": 5454, "s": 5387, "text": "Following query sets a random password of the above created user −" }, { "code": null, "e": 5751, "s": 5454, "text": "mysql> SET PASSWORD FOR 'tp'@'localhost' TO RANDOM;\n+------+-----------+----------------------+\n| user | host | generated password |\n+------+-----------+----------------------+\n| tp | localhost | hTWnSP:h0eAe(ywVJArm |\n+------+-----------+----------------------+\n1 row in set (0.17 sec)\n" }, { "code": null, "e": 5784, "s": 5751, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5812, "s": 5784, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5847, "s": 5812, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5864, "s": 5847, "text": " Frahaan Hussain" }, { "code": null, "e": 5898, "s": 5864, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5933, "s": 5898, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5967, "s": 5933, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 5995, "s": 5967, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6028, "s": 5995, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6048, "s": 6028, "text": " Harshit Srivastava" }, { "code": null, "e": 6081, "s": 6048, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 6099, "s": 6081, "text": " Trevoir Williams" }, { "code": null, "e": 6106, "s": 6099, "text": " Print" }, { "code": null, "e": 6117, "s": 6106, "text": " Add Notes" } ]
Redis - String Setnx Command
Redis SETNX command is used to set some string value in Redis key, if the key does not exist in Redis. Fullform of SETNX is SET if Not eXists. Integer reply 1 or 0 1, if the key is set. 0, if the key is not set. Following is the basic syntax of Redis SETNX command. redis 127.0.0.1:6379> SETNX KEY_NAME VALUE redis 127.0.0.1:6379> SETNX mykey redis (integer) 1 redis 127.0.0.1:6379> SETNX mykey mongodb (integer) 0 redis 127.0.0.1:6379> GET mykey "redis" 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2188, "s": 2045, "text": "Redis SETNX command is used to set some string value in Redis key, if the key does not exist in Redis. Fullform of SETNX is SET if Not eXists." }, { "code": null, "e": 2209, "s": 2188, "text": "Integer reply 1 or 0" }, { "code": null, "e": 2231, "s": 2209, "text": "1, if the key is set." }, { "code": null, "e": 2257, "s": 2231, "text": "0, if the key is not set." }, { "code": null, "e": 2311, "s": 2257, "text": "Following is the basic syntax of Redis SETNX command." }, { "code": null, "e": 2355, "s": 2311, "text": "redis 127.0.0.1:6379> SETNX KEY_NAME VALUE\n" }, { "code": null, "e": 2507, "s": 2355, "text": "redis 127.0.0.1:6379> SETNX mykey redis \n(integer) 1 \nredis 127.0.0.1:6379> SETNX mykey mongodb \n(integer) 0 \nredis 127.0.0.1:6379> GET mykey \n\"redis\"\n" }, { "code": null, "e": 2539, "s": 2507, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2559, "s": 2539, "text": " Skillbakerystudios" }, { "code": null, "e": 2566, "s": 2559, "text": " Print" }, { "code": null, "e": 2577, "s": 2566, "text": " Add Notes" } ]
How to set the background color of the TextBox in C#?
29 Nov, 2019 In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the background color of the TextBox with the help of BackColor property which makes your textbox more attractive. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the BackColor property of the TextBox. As shown in the following steps: Step 1: Create a windows form. As shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image: Step 3: After drag and drop you will go to the properties of the TextBox control to set the BackColor property of the TextBox. As shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the BackColor property of the TextBox programmatically with the help of given syntax: public override System.Drawing.Color BackColor { get; set; } Here, Color is used to represent the background color of the TextBox. Following steps are used to set the BackColor property of the TextBox: Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox TextBox Mytextbox = new TextBox(); // Creating textbox TextBox Mytextbox = new TextBox(); Step 2 : After creating TextBox, set the BackColor property of the TextBox provided by the TextBox class.// Set BackColor property Mytextbox.BackColor = Color.LightGray; // Set BackColor property Mytextbox.BackColor = Color.LightGray; Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form this.Controls.Add(Mytextbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Name"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.Font = new Font("Broadway", 12); // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output: // Add this textbox to form this.Controls.Add(Mytextbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = "Enter Name"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = "text_box1"; Mytextbox.Font = new Font("Broadway", 12); // Add this textbox to form this.Controls.Add(Mytextbox); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework Differences Between .NET Core and .NET Framework C# | Delegates C# | Data Types C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 C# | Constructors C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 413, "s": 28, "text": "In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the background color of the TextBox with the help of BackColor property which makes your textbox more attractive. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 531, "s": 413, "text": "1. Design-Time: It is the simplest way to set the BackColor property of the TextBox. As shown in the following steps:" }, { "code": null, "e": 648, "s": 531, "text": "Step 1: Create a windows form. As shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 835, "s": 648, "text": "Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. As shown in the below image:" }, { "code": null, "e": 998, "s": 835, "text": "Step 3: After drag and drop you will go to the properties of the TextBox control to set the BackColor property of the TextBox. As shown in the below image:Output:" }, { "code": null, "e": 1006, "s": 998, "text": "Output:" }, { "code": null, "e": 1184, "s": 1006, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the BackColor property of the TextBox programmatically with the help of given syntax:" }, { "code": null, "e": 1245, "s": 1184, "text": "public override System.Drawing.Color BackColor { get; set; }" }, { "code": null, "e": 1386, "s": 1245, "text": "Here, Color is used to represent the background color of the TextBox. Following steps are used to set the BackColor property of the TextBox:" }, { "code": null, "e": 1530, "s": 1386, "text": "Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1586, "s": 1530, "text": "// Creating textbox\nTextBox Mytextbox = new TextBox();\n" }, { "code": null, "e": 1757, "s": 1586, "text": "Step 2 : After creating TextBox, set the BackColor property of the TextBox provided by the TextBox class.// Set BackColor property\nMytextbox.BackColor = Color.LightGray;\n" }, { "code": null, "e": 1823, "s": 1757, "text": "// Set BackColor property\nMytextbox.BackColor = Color.LightGray;\n" }, { "code": null, "e": 3070, "s": 1823, "text": "Step 3 : And last add this textbox control to from using Add() method.// Add this textbox to form\nthis.Controls.Add(Mytextbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Name\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.Font = new Font(\"Broadway\", 12); // Add this textbox to form this.Controls.Add(Mytextbox); }}}Output:" }, { "code": null, "e": 3129, "s": 3070, "text": "// Add this textbox to form\nthis.Controls.Add(Mytextbox);\n" }, { "code": null, "e": 3138, "s": 3129, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace my { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of Lable1 Label Mylablel = new Label(); Mylablel.Location = new Point(96, 54); Mylablel.Text = \"Enter Name\"; Mylablel.AutoSize = true; Mylablel.BackColor = Color.LightGray; // Add this label to form this.Controls.Add(Mylablel); // Creating and setting the properties of TextBox1 TextBox Mytextbox = new TextBox(); Mytextbox.Location = new Point(187, 51); Mytextbox.BackColor = Color.LightGray; Mytextbox.AutoSize = true; Mytextbox.Name = \"text_box1\"; Mytextbox.Font = new Font(\"Broadway\", 12); // Add this textbox to form this.Controls.Add(Mytextbox); }}}", "e": 4242, "s": 3138, "text": null }, { "code": null, "e": 4250, "s": 4242, "text": "Output:" }, { "code": null, "e": 4281, "s": 4250, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 4284, "s": 4281, "text": "C#" }, { "code": null, "e": 4382, "s": 4284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4410, "s": 4382, "text": "C# Dictionary with examples" }, { "code": null, "e": 4453, "s": 4410, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4484, "s": 4453, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4533, "s": 4484, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4548, "s": 4533, "text": "C# | Delegates" }, { "code": null, "e": 4564, "s": 4548, "text": "C# | Data Types" }, { "code": null, "e": 4587, "s": 4564, "text": "C# | Method Overriding" }, { "code": null, "e": 4627, "s": 4587, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 4645, "s": 4627, "text": "C# | Constructors" } ]
Integer literal in C/C++ (Prefixes and Suffixes)
19 Jun, 2017 Integer literal is a type of literal for an integer whose value is directly represented in source code. For example, in the assignment statement x = 1, the string 1 is an integer literal indicating the value 1, while in the statement x = 0x10 the string 0x10 is an integer literal indicating the value 16(in decimal), which is represented by 10 in hexadecimal (indicated by the 0x prefix).Further, in x = “1” the “1” is a string literal(not a character or an integer literal), because it is in quotes. The value of the string is 1, which happens to be an integer string. Integer literals are expressed in two types i.e., Prefixes which indicates the base. For example, 0x10 indicates the value 16 in hexadecimal having prefix 0x.Suffixes which indicates the type. For example, 12345678901234LL indicates the value 12345678901234 as an long long integer having suffix LL. Prefixes which indicates the base. For example, 0x10 indicates the value 16 in hexadecimal having prefix 0x. Suffixes which indicates the type. For example, 12345678901234LL indicates the value 12345678901234 as an long long integer having suffix LL. Syntax Prefixes: They are basically represent in four types.Decimal-literal(base 10):- a non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). For example, 56, 78.Octal-literal(base 8):- a zero followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7). For example, 045, 076, 06210.Hex-literal(base 16):- 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F). For example, 0x23A, 0Xb4C, 0xFEA.Binary-literal(base 2):- 0b or 0B followed by one or more binary digits(0, 1). For example, 0b101, 0B111. Decimal-literal(base 10):- a non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). For example, 56, 78.Octal-literal(base 8):- a zero followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7). For example, 045, 076, 06210.Hex-literal(base 16):- 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F). For example, 0x23A, 0Xb4C, 0xFEA.Binary-literal(base 2):- 0b or 0B followed by one or more binary digits(0, 1). For example, 0b101, 0B111. Decimal-literal(base 10):- a non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). For example, 56, 78. Octal-literal(base 8):- a zero followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7). For example, 045, 076, 06210. Hex-literal(base 16):- 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F). For example, 0x23A, 0Xb4C, 0xFEA. Binary-literal(base 2):- 0b or 0B followed by one or more binary digits(0, 1). For example, 0b101, 0B111. Suffixes: They are represented in many ways according to their data types.int:- No suffix are required because integer constant are by default assigned as int data type.unsigned int: character u or U at the end of integer constant.long int: character l or L at the end of integer constant.unsigned long int: character ul or UL at the end of integer constant.long long int: character ll or LL at the end of integer constant.unsigned long long int: character ull or ULL at the end of integer constant. int:- No suffix are required because integer constant are by default assigned as int data type.unsigned int: character u or U at the end of integer constant.long int: character l or L at the end of integer constant.unsigned long int: character ul or UL at the end of integer constant.long long int: character ll or LL at the end of integer constant.unsigned long long int: character ull or ULL at the end of integer constant. int:- No suffix are required because integer constant are by default assigned as int data type. unsigned int: character u or U at the end of integer constant. long int: character l or L at the end of integer constant. unsigned long int: character ul or UL at the end of integer constant. long long int: character ll or LL at the end of integer constant. unsigned long long int: character ull or ULL at the end of integer constant. // C++ program to demonstrate the use of// integer literal#include <iostream>using namespace std; int main(){ // PREFIXES cout << 213 << '\n' // decimal integer literal << 0213 << '\n' // Octal integer literal << 0x213A << '\n' // hexadecimal integer literal << 0b101 << '\n' // binary integer literal // SUFFIXES // long long literal << 1234567890123456789LL << '\n' // unsigned long long literal << 12345678901234567890ull << '\n' // automatic conversion of unsigned long long even // without long long prefix << 12345678901234567890u; return 0;} Output: 213 139 8506 5 1234567890123456789 12345678901234567890 12345678901234567890 1221300 Digit separator: In C++, integer literals may contain digit separators to allow digit grouping into more readable forms. This is particularly useful for bit fields, and makes it easier to see the size of large numbers (such as a million) at a glance by subitizing rather than counting digits. It is also useful for numbers that are typically grouped, such as credit card number or social security numbers.[a] Very long numbers can be further grouped by doubling up separators.Typically decimal numbers (base-10) are grouped in three digit groups (representing one of 1000 possible values), binary numbers (base-2) in four digit groups (one nibble, representing one of 16 possible values), and hexadecimal numbers (base-16) in two digit groups (each digit is one nibble, so two digits are one byte, representing one of 256 possible values). Numbers from other systems (such as id numbers) are grouped following whatever convention is in use. // C++ program to demonstrate digit separator#include <iostream>using namespace std; int main(){ cout << 12345678901245LL <<'\n' // long long int literal digit separator << 12'345'678'901'245LL <<'\n' // binary literal digit separator << 0b1000'111'0 <<'\n' // hexadecimal literal digit separator << 0X12A'2b4; return 0;} Output: 12345678901245 12345678901245 142 1221300 Reference:- https://en.wikipedia.org/wiki/Integer_literalThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ 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) Set in C++ Standard Template Library (STL) unordered_map in C++ STL
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Jun, 2017" }, { "code": null, "e": 624, "s": 53, "text": "Integer literal is a type of literal for an integer whose value is directly represented in source code. For example, in the assignment statement x = 1, the string 1 is an integer literal indicating the value 1, while in the statement x = 0x10 the string 0x10 is an integer literal indicating the value 16(in decimal), which is represented by 10 in hexadecimal (indicated by the 0x prefix).Further, in x = “1” the “1” is a string literal(not a character or an integer literal), because it is in quotes. The value of the string is 1, which happens to be an integer string." }, { "code": null, "e": 674, "s": 624, "text": "Integer literals are expressed in two types i.e.," }, { "code": null, "e": 924, "s": 674, "text": "Prefixes which indicates the base. For example, 0x10 indicates the value 16 in hexadecimal having prefix 0x.Suffixes which indicates the type. For example, 12345678901234LL indicates the value 12345678901234 as an long long integer having suffix LL." }, { "code": null, "e": 1033, "s": 924, "text": "Prefixes which indicates the base. For example, 0x10 indicates the value 16 in hexadecimal having prefix 0x." }, { "code": null, "e": 1175, "s": 1033, "text": "Suffixes which indicates the type. For example, 12345678901234LL indicates the value 12345678901234 as an long long integer having suffix LL." }, { "code": null, "e": 1182, "s": 1175, "text": "Syntax" }, { "code": null, "e": 1782, "s": 1182, "text": "Prefixes: They are basically represent in four types.Decimal-literal(base 10):- a non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). For example, 56, 78.Octal-literal(base 8):- a zero followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7). For example, 045, 076, 06210.Hex-literal(base 16):- 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F). For example, 0x23A, 0Xb4C, 0xFEA.Binary-literal(base 2):- 0b or 0B followed by one or more binary digits(0, 1). For example, 0b101, 0B111." }, { "code": null, "e": 2329, "s": 1782, "text": "Decimal-literal(base 10):- a non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). For example, 56, 78.Octal-literal(base 8):- a zero followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7). For example, 045, 076, 06210.Hex-literal(base 16):- 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F). For example, 0x23A, 0Xb4C, 0xFEA.Binary-literal(base 2):- 0b or 0B followed by one or more binary digits(0, 1). For example, 0b101, 0B111." }, { "code": null, "e": 2473, "s": 2329, "text": "Decimal-literal(base 10):- a non-zero decimal digit followed by zero or more decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). For example, 56, 78." }, { "code": null, "e": 2597, "s": 2473, "text": "Octal-literal(base 8):- a zero followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7). For example, 045, 076, 06210." }, { "code": null, "e": 2773, "s": 2597, "text": "Hex-literal(base 16):- 0x or 0X followed by one or more hexadecimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F). For example, 0x23A, 0Xb4C, 0xFEA." }, { "code": null, "e": 2879, "s": 2773, "text": "Binary-literal(base 2):- 0b or 0B followed by one or more binary digits(0, 1). For example, 0b101, 0B111." }, { "code": null, "e": 3379, "s": 2879, "text": "Suffixes: They are represented in many ways according to their data types.int:- No suffix are required because integer constant are by default assigned as int data type.unsigned int: character u or U at the end of integer constant.long int: character l or L at the end of integer constant.unsigned long int: character ul or UL at the end of integer constant.long long int: character ll or LL at the end of integer constant.unsigned long long int: character ull or ULL at the end of integer constant." }, { "code": null, "e": 3805, "s": 3379, "text": "int:- No suffix are required because integer constant are by default assigned as int data type.unsigned int: character u or U at the end of integer constant.long int: character l or L at the end of integer constant.unsigned long int: character ul or UL at the end of integer constant.long long int: character ll or LL at the end of integer constant.unsigned long long int: character ull or ULL at the end of integer constant." }, { "code": null, "e": 3901, "s": 3805, "text": "int:- No suffix are required because integer constant are by default assigned as int data type." }, { "code": null, "e": 3964, "s": 3901, "text": "unsigned int: character u or U at the end of integer constant." }, { "code": null, "e": 4023, "s": 3964, "text": "long int: character l or L at the end of integer constant." }, { "code": null, "e": 4093, "s": 4023, "text": "unsigned long int: character ul or UL at the end of integer constant." }, { "code": null, "e": 4159, "s": 4093, "text": "long long int: character ll or LL at the end of integer constant." }, { "code": null, "e": 4236, "s": 4159, "text": "unsigned long long int: character ull or ULL at the end of integer constant." }, { "code": "// C++ program to demonstrate the use of// integer literal#include <iostream>using namespace std; int main(){ // PREFIXES cout << 213 << '\\n' // decimal integer literal << 0213 << '\\n' // Octal integer literal << 0x213A << '\\n' // hexadecimal integer literal << 0b101 << '\\n' // binary integer literal // SUFFIXES // long long literal << 1234567890123456789LL << '\\n' // unsigned long long literal << 12345678901234567890ull << '\\n' // automatic conversion of unsigned long long even // without long long prefix << 12345678901234567890u; return 0;}", "e": 4897, "s": 4236, "text": null }, { "code": null, "e": 4991, "s": 4897, "text": "Output:\n213\n139\n8506\n5\n1234567890123456789\n12345678901234567890\n12345678901234567890\n1221300\n" }, { "code": null, "e": 5932, "s": 4991, "text": "Digit separator: In C++, integer literals may contain digit separators to allow digit grouping into more readable forms. This is particularly useful for bit fields, and makes it easier to see the size of large numbers (such as a million) at a glance by subitizing rather than counting digits. It is also useful for numbers that are typically grouped, such as credit card number or social security numbers.[a] Very long numbers can be further grouped by doubling up separators.Typically decimal numbers (base-10) are grouped in three digit groups (representing one of 1000 possible values), binary numbers (base-2) in four digit groups (one nibble, representing one of 16 possible values), and hexadecimal numbers (base-16) in two digit groups (each digit is one nibble, so two digits are one byte, representing one of 256 possible values). Numbers from other systems (such as id numbers) are grouped following whatever convention is in use." }, { "code": "// C++ program to demonstrate digit separator#include <iostream>using namespace std; int main(){ cout << 12345678901245LL <<'\\n' // long long int literal digit separator << 12'345'678'901'245LL <<'\\n' // binary literal digit separator << 0b1000'111'0 <<'\\n' // hexadecimal literal digit separator << 0X12A'2b4; return 0;}", "e": 6320, "s": 5932, "text": null }, { "code": null, "e": 6371, "s": 6320, "text": "Output:\n12345678901245\n12345678901245\n142\n1221300\n" }, { "code": null, "e": 6730, "s": 6371, "text": "Reference:- https://en.wikipedia.org/wiki/Integer_literalThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 6741, "s": 6730, "text": "C Language" }, { "code": null, "e": 6745, "s": 6741, "text": "C++" }, { "code": null, "e": 6749, "s": 6745, "text": "CPP" }, { "code": null, "e": 6847, "s": 6749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6895, "s": 6847, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6940, "s": 6895, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 6961, "s": 6940, "text": "Operators in C / C++" }, { "code": null, "e": 6987, "s": 6961, "text": "Exception Handling in C++" }, { "code": null, "e": 7025, "s": 6987, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 7043, "s": 7025, "text": "Vector in C++ STL" }, { "code": null, "e": 7086, "s": 7043, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 7132, "s": 7086, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 7175, "s": 7132, "text": "Set in C++ Standard Template Library (STL)" } ]
How to Execute Shell Commands in a Remote Machine using Python – Paramiko
19 Feb, 2022 Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model. To authenticate an SSH connection, we need to set up a private RSA SSH key (not to be confused with OpenSSH). We can generate a key using the following command: $ ssh-keygen -t rsa This will prompt us to provide a name for our key. Name it whatever you like and generate a public/private RSA key pair. Enter the name by which you wish to save the key. i.e., /home/username/.ssh/id_rsa Next, you’ll be prompted to provide a password (feel free to leave this blank). Now that we have our key, we need to copy this to our remote host. The easiest way to do this is by using ssh-copy-id: $ ssh-copy-id -i ~/.ssh/mykey username@my_remote_host.org If you’d like to check which keys you already have, these can be found in your system’s .ssh directory: ~/.sshCheck We’re looking for keys that begin with the following header: —–BEGIN RSA PRIVATE KEY—– —–END RSA PRIVATE KEY—– SSH(Secure Shell) is an access credential that is used in the SSH Protocol. In other words, it is a cryptographic network protocol that is used for transferring encrypted data over the network. It allows you to connect to a server, or multiple servers, without having you remember or enter your password for each system that is to log in remotely from one system into another. To install paramiko library, run the subsequent command in the command prompt. paramiko needs cryptography as a dependency module. So run both commands in the command prompt : pip install paramiko pip install cryptography Note: For more information, refer to Install Paramiko on Windows and Linux After installation is completed, now we’ll hook up with a remote SSH server using paramiko library. Code snippet for an equivalent is given below: Python3 import paramiko # Create object of SSHClient and# connecting to SSHssh = paramiko.SSHClient() # Adding new host key to the local# HostKeys object(in case of missing)# AutoAddPolicy for missing host key to be set before connection setup.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('1.1.1.2', port=22, username='UserName', password='PassWord', timeout=3) # Execute command on SSH terminal# using exec_commandstdin, stdout, stderr = ssh.exec_command('show ip interface brief') Taking this as a base, one can automate the things of login to the remote SSH server, executing commands, and capturing the results, just using one python script. By this, you can create an SSH connection to another host from within your application, with this connection you can send your commands to the host and retrieve the output. Given below is a program to depict the same. Here we are printing the username. Program: Python3 import paramikooutput_file = 'paramiko.org' def paramiko_GKG(hostname, command): print('running') try: port = '22' # created client using paramiko client = paramiko.SSHClient() # here we are loading the system # host keys client.load_system_host_keys() # connecting paramiko using host # name and password client.connect(hostname, port=22, username='geeksForgeeks', password='geeksForgeeks') # below line command will actually # execute in your remote machine (stdin, stdout, stderr) = client.exec_command(command) # redirecting all the output in cmd_output # variable cmd_output = stdout.read() print('log printing: ', command, cmd_output) # we are creating file which will read our # cmd_output and write it in output_file with open(output_file, "w+") as file: file.write(str(cmd_output)) # we are returning the output return output_file finally: client.close() paramiko_GKG('10.10.10.1', 'uname') Output: $ python GFG_paramiko.py running [log printing: ,'uname','Linux\n'] So by running our Python file we are getting out a printed statement with uname command and Linux as an output. The same program can be modified for different commands to get information as required. kapoorsagar226 omkargurav python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2022" }, { "code": null, "e": 263, "s": 28, "text": "Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model." }, { "code": null, "e": 424, "s": 263, "text": "To authenticate an SSH connection, we need to set up a private RSA SSH key (not to be confused with OpenSSH). We can generate a key using the following command:" }, { "code": null, "e": 444, "s": 424, "text": "$ ssh-keygen -t rsa" }, { "code": null, "e": 615, "s": 444, "text": "This will prompt us to provide a name for our key. Name it whatever you like and generate a public/private RSA key pair. Enter the name by which you wish to save the key." }, { "code": null, "e": 649, "s": 615, "text": "i.e., /home/username/.ssh/id_rsa " }, { "code": null, "e": 729, "s": 649, "text": "Next, you’ll be prompted to provide a password (feel free to leave this blank)." }, { "code": null, "e": 848, "s": 729, "text": "Now that we have our key, we need to copy this to our remote host. The easiest way to do this is by using ssh-copy-id:" }, { "code": null, "e": 906, "s": 848, "text": "$ ssh-copy-id -i ~/.ssh/mykey username@my_remote_host.org" }, { "code": null, "e": 1010, "s": 906, "text": "If you’d like to check which keys you already have, these can be found in your system’s .ssh directory:" }, { "code": null, "e": 1024, "s": 1010, "text": " ~/.sshCheck " }, { "code": null, "e": 1085, "s": 1024, "text": "We’re looking for keys that begin with the following header:" }, { "code": null, "e": 1111, "s": 1085, "text": "—–BEGIN RSA PRIVATE KEY—–" }, { "code": null, "e": 1135, "s": 1111, "text": "—–END RSA PRIVATE KEY—–" }, { "code": null, "e": 1512, "s": 1135, "text": "SSH(Secure Shell) is an access credential that is used in the SSH Protocol. In other words, it is a cryptographic network protocol that is used for transferring encrypted data over the network. It allows you to connect to a server, or multiple servers, without having you remember or enter your password for each system that is to log in remotely from one system into another." }, { "code": null, "e": 1688, "s": 1512, "text": "To install paramiko library, run the subsequent command in the command prompt. paramiko needs cryptography as a dependency module. So run both commands in the command prompt :" }, { "code": null, "e": 1709, "s": 1688, "text": "pip install paramiko" }, { "code": null, "e": 1734, "s": 1709, "text": "pip install cryptography" }, { "code": null, "e": 1809, "s": 1734, "text": "Note: For more information, refer to Install Paramiko on Windows and Linux" }, { "code": null, "e": 1956, "s": 1809, "text": "After installation is completed, now we’ll hook up with a remote SSH server using paramiko library. Code snippet for an equivalent is given below:" }, { "code": null, "e": 1964, "s": 1956, "text": "Python3" }, { "code": "import paramiko # Create object of SSHClient and# connecting to SSHssh = paramiko.SSHClient() # Adding new host key to the local# HostKeys object(in case of missing)# AutoAddPolicy for missing host key to be set before connection setup.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('1.1.1.2', port=22, username='UserName', password='PassWord', timeout=3) # Execute command on SSH terminal# using exec_commandstdin, stdout, stderr = ssh.exec_command('show ip interface brief')", "e": 2475, "s": 1964, "text": null }, { "code": null, "e": 2638, "s": 2475, "text": "Taking this as a base, one can automate the things of login to the remote SSH server, executing commands, and capturing the results, just using one python script." }, { "code": null, "e": 2812, "s": 2638, "text": "By this, you can create an SSH connection to another host from within your application, with this connection you can send your commands to the host and retrieve the output. " }, { "code": null, "e": 2892, "s": 2812, "text": "Given below is a program to depict the same. Here we are printing the username." }, { "code": null, "e": 2901, "s": 2892, "text": "Program:" }, { "code": null, "e": 2909, "s": 2901, "text": "Python3" }, { "code": "import paramikooutput_file = 'paramiko.org' def paramiko_GKG(hostname, command): print('running') try: port = '22' # created client using paramiko client = paramiko.SSHClient() # here we are loading the system # host keys client.load_system_host_keys() # connecting paramiko using host # name and password client.connect(hostname, port=22, username='geeksForgeeks', password='geeksForgeeks') # below line command will actually # execute in your remote machine (stdin, stdout, stderr) = client.exec_command(command) # redirecting all the output in cmd_output # variable cmd_output = stdout.read() print('log printing: ', command, cmd_output) # we are creating file which will read our # cmd_output and write it in output_file with open(output_file, \"w+\") as file: file.write(str(cmd_output)) # we are returning the output return output_file finally: client.close() paramiko_GKG('10.10.10.1', 'uname')", "e": 4074, "s": 2909, "text": null }, { "code": null, "e": 4082, "s": 4074, "text": "Output:" }, { "code": null, "e": 4150, "s": 4082, "text": "$ python GFG_paramiko.py\nrunning\n[log printing: ,'uname','Linux\\n']" }, { "code": null, "e": 4350, "s": 4150, "text": "So by running our Python file we are getting out a printed statement with uname command and Linux as an output. The same program can be modified for different commands to get information as required." }, { "code": null, "e": 4365, "s": 4350, "text": "kapoorsagar226" }, { "code": null, "e": 4376, "s": 4365, "text": "omkargurav" }, { "code": null, "e": 4391, "s": 4376, "text": "python-modules" }, { "code": null, "e": 4406, "s": 4391, "text": "python-utility" }, { "code": null, "e": 4413, "s": 4406, "text": "Python" } ]
comment – Django template tags
23 Sep, 2021 A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to the template but also provide some limited features of programming such as variables, for loops, comments, etc. This article revolves about how to use comment tag in Template. Template ignores everything between {% comment %} and {% endcomment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled. Syntax {% comment 'comment_name' %} {% endcomment %} Example {% comment "Optional note" %} Commented out text with {{ create_date|date:"c" }} {% endcomment %} Illustration of How to use comment tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now create a view through which we will pass the context dictionary, In geeks/views.py, Python3 # import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { "data" : "<h1>GeeksForGeeks is the Best</h1>", } # return response return render(request, "geeks.html", context) Create a url path to map to this view. In geeks/urls.py, Python3 from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),] Create a template in templates/geeks.html, HTML Data uncommented :{{ data }}Data commented :{% comment "Optional note" %} {{ data }}{% endcomment %} Let’s check is comments are displayed in the template. surindertarika1234 Django-templates Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 691, "s": 28, "text": "A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to the template but also provide some limited features of programming such as variables, for loops, comments, etc. This article revolves about how to use comment tag in Template. Template ignores everything between {% comment %} and {% endcomment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled. " }, { "code": null, "e": 699, "s": 691, "text": "Syntax " }, { "code": null, "e": 745, "s": 699, "text": "{% comment 'comment_name' %}\n{% endcomment %}" }, { "code": null, "e": 754, "s": 745, "text": "Example " }, { "code": null, "e": 856, "s": 754, "text": "{% comment \"Optional note\" %}\n Commented out text with {{ create_date|date:\"c\" }}\n{% endcomment %}" }, { "code": null, "e": 1000, "s": 856, "text": "Illustration of How to use comment tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 1088, "s": 1000, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 1139, "s": 1088, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1172, "s": 1139, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1261, "s": 1172, "text": "Now create a view through which we will pass the context dictionary, In geeks/views.py, " }, { "code": null, "e": 1269, "s": 1261, "text": "Python3" }, { "code": "# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { \"data\" : \"<h1>GeeksForGeeks is the Best</h1>\", } # return response return render(request, \"geeks.html\", context)", "e": 1552, "s": 1269, "text": null }, { "code": null, "e": 1609, "s": 1552, "text": "Create a url path to map to this view. In geeks/urls.py," }, { "code": null, "e": 1617, "s": 1609, "text": "Python3" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]", "e": 1750, "s": 1617, "text": null }, { "code": null, "e": 1794, "s": 1750, "text": "Create a template in templates/geeks.html, " }, { "code": null, "e": 1799, "s": 1794, "text": "HTML" }, { "code": "Data uncommented :{{ data }}Data commented :{% comment \"Optional note\" %} {{ data }}{% endcomment %}", "e": 1903, "s": 1799, "text": null }, { "code": null, "e": 1959, "s": 1903, "text": "Let’s check is comments are displayed in the template. " }, { "code": null, "e": 1980, "s": 1961, "text": "surindertarika1234" }, { "code": null, "e": 1997, "s": 1980, "text": "Django-templates" }, { "code": null, "e": 2011, "s": 1997, "text": "Python Django" }, { "code": null, "e": 2018, "s": 2011, "text": "Python" }, { "code": null, "e": 2116, "s": 2018, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2134, "s": 2116, "text": "Python Dictionary" }, { "code": null, "e": 2176, "s": 2134, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2198, "s": 2176, "text": "Enumerate() in Python" }, { "code": null, "e": 2233, "s": 2198, "text": "Read a file line by line in Python" }, { "code": null, "e": 2259, "s": 2233, "text": "Python String | replace()" }, { "code": null, "e": 2291, "s": 2259, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2320, "s": 2291, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2347, "s": 2320, "text": "Python Classes and Objects" }, { "code": null, "e": 2368, "s": 2347, "text": "Python OOPs Concepts" } ]
How to find time taken by a command/program on Linux Shell?
26 Sep, 2017 We have already discussed a way to find time taken by a function through C libraries. If we are on Linux, then it becomes very easy to find time taken by a program/command. We can use time command for this purpose. The time taken is shown in three forms.real: Total end to end time taken by program/commanduser: Time taken in user mode.sys: Time taken in kernel mode A Command Example (Time taken by ls-l): $ time ls -l The above command runs "ls -l" and shows contents of current directory followed by the time taken by command "ls -l". A program example (Time taken by fib(30)):let us consider below program. #include<stdio.h>int fib(int n){ if (n <= 1) return n; return fib(n-1) + fib(n-2);} int main (){ printf("Fibonacci Number is %d", fib(30)); return 0;} Let we save above program as fib.c. // Compiling above program on shell ~$ gcc fib.c // Running the generated executable with time ~$ time ./a.out Fibonacci Number is 832040 real 0m0.017s user 0m0.017s sys 0m0.000s Note: 0.017 seconds (shown with real) is total time taken by program. This article is contributed Dheeraj Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples TCP Server-Client implementation in C Conditional Statements | Shell Script How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker? Running Python script on GPU.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Sep, 2017" }, { "code": null, "e": 225, "s": 52, "text": "We have already discussed a way to find time taken by a function through C libraries. If we are on Linux, then it becomes very easy to find time taken by a program/command." }, { "code": null, "e": 419, "s": 225, "text": "We can use time command for this purpose. The time taken is shown in three forms.real: Total end to end time taken by program/commanduser: Time taken in user mode.sys: Time taken in kernel mode" }, { "code": null, "e": 459, "s": 419, "text": "A Command Example (Time taken by ls-l):" }, { "code": null, "e": 595, "s": 459, "text": "$ time ls -l\n\nThe above command runs \"ls -l\" and shows \ncontents of current directory followed by\nthe time taken by command \"ls -l\". \n" }, { "code": null, "e": 670, "s": 597, "text": "A program example (Time taken by fib(30)):let us consider below program." }, { "code": "#include<stdio.h>int fib(int n){ if (n <= 1) return n; return fib(n-1) + fib(n-2);} int main (){ printf(\"Fibonacci Number is %d\", fib(30)); return 0;}", "e": 833, "s": 670, "text": null }, { "code": null, "e": 1132, "s": 833, "text": "Let we save above program as fib.c.\n\n// Compiling above program on shell\n~$ gcc fib.c\n\n// Running the generated executable with time\n~$ time ./a.out\nFibonacci Number is 832040\nreal 0m0.017s\nuser 0m0.017s\nsys 0m0.000s\n\nNote: 0.017 seconds (shown with real) is total \ntime taken by program.\n" }, { "code": null, "e": 1396, "s": 1132, "text": "This article is contributed Dheeraj Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1520, "s": 1396, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 1531, "s": 1520, "text": "Linux-Unix" }, { "code": null, "e": 1540, "s": 1531, "text": "TechTips" }, { "code": null, "e": 1638, "s": 1540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1673, "s": 1638, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 1708, "s": 1673, "text": "tar command in Linux with examples" }, { "code": null, "e": 1744, "s": 1708, "text": "curl command in Linux with Examples" }, { "code": null, "e": 1782, "s": 1744, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1820, "s": 1782, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 1873, "s": 1820, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 1899, "s": 1873, "text": "Docker - COPY Instruction" }, { "code": null, "e": 1934, "s": 1899, "text": "Setting up the environment in Java" }, { "code": null, "e": 1975, "s": 1934, "text": "How to Run a Python Script using Docker?" } ]
How to create a news ticker using jQuery ?
18 May, 2021 A news ticker is a text-based display either in the form of graphic that display news scrolling text running from up to down or right to left. In this article, we will use a jQuery plugin called easy-ticker to create a news ticker in a simple manner. To use this plugin, simply add the CDN link in the script tag of your HTML code. <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery-easy-ticker/2.0.0/jquery.easy-ticker.min.js”></script> Let us look at the HTML code to know how we can create a news ticker using the easy-ticker plugin. HTML <!DOCTYPE HTML><html> <head> <title>News Ticker Effect</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easy-ticker/2.0.0/jquery.easy-ticker.min.js"> </script> <style> .dashboard { background-color: green; width: 600px; height: 350px; border: 3px solid black; overflow: hidden; border-radius: 15px; margin: 0px auto; } ul { margin: 1px; padding: 1px; } li { text-align: justify; border-bottom: 2px solid blue; } h1 { color: red; } </style></head> <body style="text-align:center;"> <h1>GFG COURSES</h1> <div class="dashboard"> <ul id="news"> <li> <h1>Android App with Kotlin</h1> <p> This course will begin from the basics of Android Development and will take you to a level where you can make full fledged Android apps. It covers things like UI building, Kotlin programming, communicating between different screens of an app,implementing static and dynamic custom lists, working with databases ,fetching data from the internet using REST APIs, using various important libraries and working with local device storage. </p> </li> <li> <h1> Data Structure and Algorithm self paced </h1> <p> This course is a complete package that helps you learn Data Structures and Algorithms from basic to an advanced level. The course curriculum has been divided into 10 weeks where you can practice questions & attempt the assessment tests according to your own pace. The course offers you a wealth of programming challenges that will help you to prepare for interviews with top-notch companies like Microsoft, Amazon,Adobe etc. </p> </li> <li> <h1>Java Backend Course</h1> <p> This course will help you to learn Advanced Java, Spring / Spring Boot, Hibernate, RESTful APIs, Micro-services & related technologies to build Java -based web applications. The course will be mentored & guided by an Industry expert having hands-on experience in the design, development & maintenance of Java (Spring / Spring Boot) based web applications.The course includes 1 major & 2 minor projects based on real -world applications with guided lab sessions. </p> </li> <li> <h1>Fundamentals of Java and Collections</h1> <p> This course covers the basics of Java and in-depth explanations to Java Collections Framework along with video explanations of some problems based on the Java Collections Framework. The Java Collections Framework is a set of classes, Interfaces, and methods that provide us various data structures like LinkedList, ArrayList, HashMap, HashSet etc. </p> </li> </ul> </div> <script type="text/javascript"> $(document).ready(function () { // Calling easyTicker function to // create newsticker movement $('.dashboard').easyTicker({ direction: 'up', easing: 'swing', speed: 'slow', interval: 2000, height: 'auto', mousePause: true, controls: { playText: 'Play', stopText: 'Stop' }, callbacks: { before: false, after: false } }); }); </script></body> </html> Output: HTML-Questions HTML-Tags jQuery-Plugin jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to get the value in an input text box using jQuery ? jQuery | ajax() Method How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | removeAttr() with Examples jQuery | parent() & parents() with Examples Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2021" }, { "code": null, "e": 279, "s": 28, "text": "A news ticker is a text-based display either in the form of graphic that display news scrolling text running from up to down or right to left. In this article, we will use a jQuery plugin called easy-ticker to create a news ticker in a simple manner." }, { "code": null, "e": 360, "s": 279, "text": "To use this plugin, simply add the CDN link in the script tag of your HTML code." }, { "code": null, "e": 562, "s": 360, "text": "<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery-easy-ticker/2.0.0/jquery.easy-ticker.min.js”></script>" }, { "code": null, "e": 661, "s": 562, "text": "Let us look at the HTML code to know how we can create a news ticker using the easy-ticker plugin." }, { "code": null, "e": 666, "s": 661, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <title>News Ticker Effect</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-easy-ticker/2.0.0/jquery.easy-ticker.min.js\"> </script> <style> .dashboard { background-color: green; width: 600px; height: 350px; border: 3px solid black; overflow: hidden; border-radius: 15px; margin: 0px auto; } ul { margin: 1px; padding: 1px; } li { text-align: justify; border-bottom: 2px solid blue; } h1 { color: red; } </style></head> <body style=\"text-align:center;\"> <h1>GFG COURSES</h1> <div class=\"dashboard\"> <ul id=\"news\"> <li> <h1>Android App with Kotlin</h1> <p> This course will begin from the basics of Android Development and will take you to a level where you can make full fledged Android apps. It covers things like UI building, Kotlin programming, communicating between different screens of an app,implementing static and dynamic custom lists, working with databases ,fetching data from the internet using REST APIs, using various important libraries and working with local device storage. </p> </li> <li> <h1> Data Structure and Algorithm self paced </h1> <p> This course is a complete package that helps you learn Data Structures and Algorithms from basic to an advanced level. The course curriculum has been divided into 10 weeks where you can practice questions & attempt the assessment tests according to your own pace. The course offers you a wealth of programming challenges that will help you to prepare for interviews with top-notch companies like Microsoft, Amazon,Adobe etc. </p> </li> <li> <h1>Java Backend Course</h1> <p> This course will help you to learn Advanced Java, Spring / Spring Boot, Hibernate, RESTful APIs, Micro-services & related technologies to build Java -based web applications. The course will be mentored & guided by an Industry expert having hands-on experience in the design, development & maintenance of Java (Spring / Spring Boot) based web applications.The course includes 1 major & 2 minor projects based on real -world applications with guided lab sessions. </p> </li> <li> <h1>Fundamentals of Java and Collections</h1> <p> This course covers the basics of Java and in-depth explanations to Java Collections Framework along with video explanations of some problems based on the Java Collections Framework. The Java Collections Framework is a set of classes, Interfaces, and methods that provide us various data structures like LinkedList, ArrayList, HashMap, HashSet etc. </p> </li> </ul> </div> <script type=\"text/javascript\"> $(document).ready(function () { // Calling easyTicker function to // create newsticker movement $('.dashboard').easyTicker({ direction: 'up', easing: 'swing', speed: 'slow', interval: 2000, height: 'auto', mousePause: true, controls: { playText: 'Play', stopText: 'Stop' }, callbacks: { before: false, after: false } }); }); </script></body> </html>", "e": 5448, "s": 666, "text": null }, { "code": null, "e": 5456, "s": 5448, "text": "Output:" }, { "code": null, "e": 5471, "s": 5456, "text": "HTML-Questions" }, { "code": null, "e": 5481, "s": 5471, "text": "HTML-Tags" }, { "code": null, "e": 5495, "s": 5481, "text": "jQuery-Plugin" }, { "code": null, "e": 5512, "s": 5495, "text": "jQuery-Questions" }, { "code": null, "e": 5519, "s": 5512, "text": "Picked" }, { "code": null, "e": 5526, "s": 5519, "text": "JQuery" }, { "code": null, "e": 5543, "s": 5526, "text": "Web Technologies" }, { "code": null, "e": 5641, "s": 5543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5698, "s": 5641, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 5721, "s": 5698, "text": "jQuery | ajax() Method" }, { "code": null, "e": 5794, "s": 5721, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 5830, "s": 5794, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 5874, "s": 5830, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 5907, "s": 5874, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5969, "s": 5907, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6030, "s": 5969, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6080, "s": 6030, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How jQuery selects elements using CSS?
jQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element. Here is the description of all parameter used by this method − name − The name of the property to access. You can try to run the following code to learn how jQuery selects elements with CSS: Live Demo <html> <head> <title>jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("div").click(function () { var color = $(this).css("background-color"); $("#result").html("That div is <span style = 'color:" + color + ";'>" + color + "</span>."); }); }); </script> <style> div { width:60px; height:60px; margin:5px; float:left; } </style> </head> <body> <p>Click on any square:</p> <span id = "result"> </span> <div style = "background-color:blue;"></div> <div style = "background-color:gray;"></div> <div style = "background-color:#123456;"></div> <div style = "background-color:#f11;"></div> </body> </html>
[ { "code": null, "e": 1399, "s": 1187, "text": "jQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element." }, { "code": null, "e": 1462, "s": 1399, "text": "Here is the description of all parameter used by this method −" }, { "code": null, "e": 1505, "s": 1462, "text": "name − The name of the property to access." }, { "code": null, "e": 1590, "s": 1505, "text": "You can try to run the following code to learn how jQuery selects elements with CSS:" }, { "code": null, "e": 1600, "s": 1590, "text": "Live Demo" }, { "code": null, "e": 2561, "s": 1600, "text": "<html>\n\n <head>\n <title>jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n $(\"div\").click(function () {\n var color = $(this).css(\"background-color\");\n $(\"#result\").html(\"That div is <span style = 'color:\" +\n color + \";'>\" + color + \"</span>.\");\n });\n \n });\n </script>\n \n <style>\n div { width:60px; height:60px; margin:5px; float:left; }\n </style>\n </head>\n \n <body>\n \n <p>Click on any square:</p>\n <span id = \"result\"> </span>\n \n <div style = \"background-color:blue;\"></div>\n <div style = \"background-color:gray;\"></div>\n <div style = \"background-color:#123456;\"></div>\n <div style = \"background-color:#f11;\"></div>\n \n </body>\n \n</html>" } ]
numpy.frombuffer() function – Python
18 Aug, 2020 numpy.frombuffer() function interpret a buffer as a 1-dimensional array. Syntax : numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0) Parameters : buffer : [buffer_like] An object that exposes the buffer interface. dtype : [data-type, optional] Data-type of the returned array, default data-type is float. count : [int, optional] Number of items to read. offset : [int, optional] Start reading the buffer from this offset, default is 0. Return : This function interpret a buffer as a 1-dimensional array. Code #1 : Python3 # Python program explaining# numpy.frombuffer() function # importing numpy as geek import numpy as geek gfg = geek.frombuffer(b'\x01\x02\x03', dtype = geek.uint8) print (gfg) Output : [1 2 3] Code #2 : Python3 # Python program explaining# numpy.frombuffer() function # importing numpy as geek import numpy as geek gfg = geek.frombuffer(b'\x01\x02\x03\x04\x05\x06\x07', dtype = geek.uint8, count = 5) print (gfg) Output : [1 2 3 4 5] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts 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 Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2020" }, { "code": null, "e": 101, "s": 28, "text": "numpy.frombuffer() function interpret a buffer as a 1-dimensional array." }, { "code": null, "e": 177, "s": 101, "text": "Syntax : numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)" }, { "code": null, "e": 190, "s": 177, "text": "Parameters :" }, { "code": null, "e": 258, "s": 190, "text": "buffer : [buffer_like] An object that exposes the buffer interface." }, { "code": null, "e": 349, "s": 258, "text": "dtype : [data-type, optional] Data-type of the returned array, default data-type is float." }, { "code": null, "e": 398, "s": 349, "text": "count : [int, optional] Number of items to read." }, { "code": null, "e": 480, "s": 398, "text": "offset : [int, optional] Start reading the buffer from this offset, default is 0." }, { "code": null, "e": 548, "s": 480, "text": "Return : This function interpret a buffer as a 1-dimensional array." }, { "code": null, "e": 558, "s": 548, "text": "Code #1 :" }, { "code": null, "e": 566, "s": 558, "text": "Python3" }, { "code": "# Python program explaining# numpy.frombuffer() function # importing numpy as geek import numpy as geek gfg = geek.frombuffer(b'\\x01\\x02\\x03', dtype = geek.uint8) print (gfg)", "e": 757, "s": 566, "text": null }, { "code": null, "e": 766, "s": 757, "text": "Output :" }, { "code": null, "e": 774, "s": 766, "text": "[1 2 3]" }, { "code": null, "e": 784, "s": 774, "text": "Code #2 :" }, { "code": null, "e": 792, "s": 784, "text": "Python3" }, { "code": "# Python program explaining# numpy.frombuffer() function # importing numpy as geek import numpy as geek gfg = geek.frombuffer(b'\\x01\\x02\\x03\\x04\\x05\\x06\\x07', dtype = geek.uint8, count = 5) print (gfg)", "e": 1010, "s": 792, "text": null }, { "code": null, "e": 1019, "s": 1010, "text": "Output :" }, { "code": null, "e": 1031, "s": 1019, "text": "[1 2 3 4 5]" }, { "code": null, "e": 1044, "s": 1031, "text": "Python-numpy" }, { "code": null, "e": 1051, "s": 1044, "text": "Python" }, { "code": null, "e": 1149, "s": 1051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1181, "s": 1149, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1208, "s": 1181, "text": "Python Classes and Objects" }, { "code": null, "e": 1239, "s": 1208, "text": "Python | os.path.join() method" }, { "code": null, "e": 1262, "s": 1239, "text": "Introduction To PYTHON" }, { "code": null, "e": 1283, "s": 1262, "text": "Python OOPs Concepts" }, { "code": null, "e": 1339, "s": 1283, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1381, "s": 1339, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1423, "s": 1381, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1462, "s": 1423, "text": "Python | Get unique values from a list" } ]
Access specifier of methods in interfaces
07 Dec, 2018 In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized. Consider the following example, x is by default public static final and foo() is public even if there are no specifiers. interface Test { int x = 10; // x is public static final and must be initialized here void foo(); // foo() is public} Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. access modifiers java-basics java-interfaces Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Dec, 2018" }, { "code": null, "e": 286, "s": 52, "text": "In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized." }, { "code": null, "e": 407, "s": 286, "text": "Consider the following example, x is by default public static final and foo() is public even if there are no specifiers." }, { "code": "interface Test { int x = 10; // x is public static final and must be initialized here void foo(); // foo() is public}", "e": 529, "s": 407, "text": null }, { "code": null, "e": 654, "s": 529, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 671, "s": 654, "text": "access modifiers" }, { "code": null, "e": 683, "s": 671, "text": "java-basics" }, { "code": null, "e": 699, "s": 683, "text": "java-interfaces" }, { "code": null, "e": 704, "s": 699, "text": "Java" }, { "code": null, "e": 723, "s": 704, "text": "School Programming" }, { "code": null, "e": 728, "s": 723, "text": "Java" }, { "code": null, "e": 826, "s": 728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 841, "s": 826, "text": "Arrays in Java" }, { "code": null, "e": 877, "s": 841, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 921, "s": 877, "text": "Split() String method in Java with examples" }, { "code": null, "e": 946, "s": 921, "text": "Reverse a string in Java" }, { "code": null, "e": 997, "s": 946, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 1015, "s": 997, "text": "Python Dictionary" }, { "code": null, "e": 1040, "s": 1015, "text": "Reverse a string in Java" }, { "code": null, "e": 1056, "s": 1040, "text": "Arrays in C/C++" }, { "code": null, "e": 1079, "s": 1056, "text": "Introduction To PYTHON" } ]
How to change the font size of the Title in a Matplotlib figure ?
03 Nov, 2021 In this article, we are going to discuss how to change the font size of the title in a figure using matplotlib module. As we use matplotlib.pyplot.title() method to assign a title a plot, so in order to change the font size, we are going to use the fontsize argument of the pyplot.title() method in the matplotlib module. Below is are some programs which depict how to change the font size of the title in a matplotlib figure: Example 1: Python3 # importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesx = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = [] for i in range(len(x)): y.append(max(0, x[i])) # depicting the visualizationplt.plot(x, y, color='green')plt.xlabel('x')plt.ylabel('y') # displaying the titleplt.title("ReLU Function", fontsize = 40) Output: Example 2: Python3 # importing modulesfrom matplotlib import pyplot as plt # assigning x and y coordinatesfoodPreference = ['Vegetarian', 'Non Vegetarian', 'Vegan', 'Eggitarian'] consumers = [30, 100, 10, 60] # depicting the visualizationfig = plt.figure()ax = fig.add_axes([0, 0, 1, 1])ax.axis('equal')ax.pie(consumers, labels = foodPreference, autopct='%1.2f%%') # displaying the titleplt.title("Society Food Preference", fontsize = 10) Output: Example 3: Python3 # importing modulesfrom matplotlib import pyplotimport numpy # assigning time values of the signal# initial time period, final time period# and phase anglesignalTime = numpy.arange(0, 100, 0.5) # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # depicting the visualizationpyplot.plot(signalTime, signalAmplitude, color = 'green') pyplot.xlabel('Time')pyplot.ylabel('Amplitude') # displaying the titlepyplot.title("Signal", fontsize = 30) Output: kashishsoda Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Nov, 2021" }, { "code": null, "e": 147, "s": 28, "text": "In this article, we are going to discuss how to change the font size of the title in a figure using matplotlib module." }, { "code": null, "e": 352, "s": 147, "text": "As we use matplotlib.pyplot.title() method to assign a title a plot, so in order to change the font size, we are going to use the fontsize argument of the pyplot.title() method in the matplotlib module. " }, { "code": null, "e": 457, "s": 352, "text": "Below is are some programs which depict how to change the font size of the title in a matplotlib figure:" }, { "code": null, "e": 468, "s": 457, "text": "Example 1:" }, { "code": null, "e": 476, "s": 468, "text": "Python3" }, { "code": "# importing moduleimport matplotlib.pyplot as plt # assigning x and y coordinatesx = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]y = [] for i in range(len(x)): y.append(max(0, x[i])) # depicting the visualizationplt.plot(x, y, color='green')plt.xlabel('x')plt.ylabel('y') # displaying the titleplt.title(\"ReLU Function\", fontsize = 40)", "e": 818, "s": 476, "text": null }, { "code": null, "e": 826, "s": 818, "text": "Output:" }, { "code": null, "e": 837, "s": 826, "text": "Example 2:" }, { "code": null, "e": 845, "s": 837, "text": "Python3" }, { "code": "# importing modulesfrom matplotlib import pyplot as plt # assigning x and y coordinatesfoodPreference = ['Vegetarian', 'Non Vegetarian', 'Vegan', 'Eggitarian'] consumers = [30, 100, 10, 60] # depicting the visualizationfig = plt.figure()ax = fig.add_axes([0, 0, 1, 1])ax.axis('equal')ax.pie(consumers, labels = foodPreference, autopct='%1.2f%%') # displaying the titleplt.title(\"Society Food Preference\", fontsize = 10)", "e": 1311, "s": 845, "text": null }, { "code": null, "e": 1319, "s": 1311, "text": "Output:" }, { "code": null, "e": 1330, "s": 1319, "text": "Example 3:" }, { "code": null, "e": 1338, "s": 1330, "text": "Python3" }, { "code": "# importing modulesfrom matplotlib import pyplotimport numpy # assigning time values of the signal# initial time period, final time period# and phase anglesignalTime = numpy.arange(0, 100, 0.5) # getting the amplitude of the signalsignalAmplitude = numpy.sin(signalTime) # depicting the visualizationpyplot.plot(signalTime, signalAmplitude, color = 'green') pyplot.xlabel('Time')pyplot.ylabel('Amplitude') # displaying the titlepyplot.title(\"Signal\", fontsize = 30)", "e": 1827, "s": 1338, "text": null }, { "code": null, "e": 1835, "s": 1827, "text": "Output:" }, { "code": null, "e": 1847, "s": 1835, "text": "kashishsoda" }, { "code": null, "e": 1854, "s": 1847, "text": "Picked" }, { "code": null, "e": 1872, "s": 1854, "text": "Python-matplotlib" }, { "code": null, "e": 1896, "s": 1872, "text": "Technical Scripter 2020" }, { "code": null, "e": 1903, "s": 1896, "text": "Python" }, { "code": null, "e": 1922, "s": 1903, "text": "Technical Scripter" }, { "code": null, "e": 2020, "s": 1922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2065, "s": 2020, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2115, "s": 2065, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2131, "s": 2115, "text": "Deque in Python" }, { "code": null, "e": 2147, "s": 2131, "text": "Queue in Python" }, { "code": null, "e": 2169, "s": 2147, "text": "Defaultdict in Python" }, { "code": null, "e": 2211, "s": 2169, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2238, "s": 2211, "text": "Python Classes and Objects" }, { "code": null, "e": 2261, "s": 2238, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 2280, "s": 2261, "text": "reduce() in Python" } ]
What is the difference between SCSS and SASS ?
01 Jun, 2022 SASS (Syntactically Awesome Style Sheets) is a pre-processor scripting language that will be compiled or interpreted into CSS. SassScript is itself a scripting language whereas SCSS is the main syntax for the SASS which builds on top of the existing CSS syntax. It makes use of semicolons and brackets like CSS (Cascaded Style Sheets).SASS and SCSS can import each other. Sass actually makes CSS more powerful with math and variable support. Let’s list down the main difference between SASS and SCSS. SASS is used when we need an original syntax, code syntax is not required for SCSS. SASS follows strict indentation, SCSS has no strict indentation. SASS has a loose syntax with white space and no semicolons, the SCSS resembles more to CSS style and use of semicolons and braces are mandatory. SASS file extension is .sass and SCSS file extension is .scss. SASS has more developer community and support than SCSS. SASS supports SassDoc to add documentation whereas SCSS allows inline documentation. SASS can’t be used as CSS and vice-versa whereas a valid CSS code is also a valid SCSS code. SASS is hard to add to existing CSS projects whereas SCSS can be added easily to an existing CSS project just by adding new code. SCSS Example: SCSS /* .scss file */$bgcolor: blue;$textcolor: red;$fontsize: 25px; /* Use the variables */body { background-color: $bgcolor; color: $textcolor; font-size: $fontsize;} Output CSS: body { background-color: blue; color: red; font-size: 25px; } /* now this can apply resulting html file */ SASS Example: SASS /* SASS */ $primary-color: green$primary-bg: red body color: $primary-color background: $primary-bg Output CSS: /* CSS */ body { color: green; background: red; } CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. raragarwal102 daveholuborhee olumideokedusi siddharthredhu01 Picked SASS CSS Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to select all child elements recursively using CSS? Build a Survey Form using HTML and CSS CSS | :not(:last-child):after Selector Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jun, 2022" }, { "code": null, "e": 557, "s": 54, "text": "SASS (Syntactically Awesome Style Sheets) is a pre-processor scripting language that will be compiled or interpreted into CSS. SassScript is itself a scripting language whereas SCSS is the main syntax for the SASS which builds on top of the existing CSS syntax. It makes use of semicolons and brackets like CSS (Cascaded Style Sheets).SASS and SCSS can import each other. Sass actually makes CSS more powerful with math and variable support. Let’s list down the main difference between SASS and SCSS. " }, { "code": null, "e": 641, "s": 557, "text": "SASS is used when we need an original syntax, code syntax is not required for SCSS." }, { "code": null, "e": 706, "s": 641, "text": "SASS follows strict indentation, SCSS has no strict indentation." }, { "code": null, "e": 851, "s": 706, "text": "SASS has a loose syntax with white space and no semicolons, the SCSS resembles more to CSS style and use of semicolons and braces are mandatory." }, { "code": null, "e": 914, "s": 851, "text": "SASS file extension is .sass and SCSS file extension is .scss." }, { "code": null, "e": 971, "s": 914, "text": "SASS has more developer community and support than SCSS." }, { "code": null, "e": 1056, "s": 971, "text": "SASS supports SassDoc to add documentation whereas SCSS allows inline documentation." }, { "code": null, "e": 1149, "s": 1056, "text": "SASS can’t be used as CSS and vice-versa whereas a valid CSS code is also a valid SCSS code." }, { "code": null, "e": 1279, "s": 1149, "text": "SASS is hard to add to existing CSS projects whereas SCSS can be added easily to an existing CSS project just by adding new code." }, { "code": null, "e": 1295, "s": 1279, "text": "SCSS Example: " }, { "code": null, "e": 1300, "s": 1295, "text": "SCSS" }, { "code": "/* .scss file */$bgcolor: blue;$textcolor: red;$fontsize: 25px; /* Use the variables */body { background-color: $bgcolor; color: $textcolor; font-size: $fontsize;}", "e": 1467, "s": 1300, "text": null }, { "code": null, "e": 1481, "s": 1467, "text": "Output CSS: " }, { "code": null, "e": 1594, "s": 1481, "text": "body {\n background-color: blue;\n color: red;\n font-size: 25px;\n}\n/* now this can apply resulting html file */" }, { "code": null, "e": 1609, "s": 1594, "text": "SASS Example: " }, { "code": null, "e": 1614, "s": 1609, "text": "SASS" }, { "code": "/* SASS */ $primary-color: green$primary-bg: red body color: $primary-color background: $primary-bg", "e": 1716, "s": 1614, "text": null }, { "code": null, "e": 1728, "s": 1716, "text": "Output CSS:" }, { "code": null, "e": 1782, "s": 1728, "text": "/* CSS */\nbody {\n color: green;\n background: red;\n}" }, { "code": null, "e": 1968, "s": 1782, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 1982, "s": 1968, "text": "raragarwal102" }, { "code": null, "e": 1997, "s": 1982, "text": "daveholuborhee" }, { "code": null, "e": 2012, "s": 1997, "text": "olumideokedusi" }, { "code": null, "e": 2029, "s": 2012, "text": "siddharthredhu01" }, { "code": null, "e": 2036, "s": 2029, "text": "Picked" }, { "code": null, "e": 2041, "s": 2036, "text": "SASS" }, { "code": null, "e": 2045, "s": 2041, "text": "CSS" }, { "code": null, "e": 2064, "s": 2045, "text": "Technical Scripter" }, { "code": null, "e": 2081, "s": 2064, "text": "Web Technologies" }, { "code": null, "e": 2108, "s": 2081, "text": "Web technologies Questions" }, { "code": null, "e": 2206, "s": 2108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2245, "s": 2206, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2284, "s": 2245, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2340, "s": 2284, "text": "How to select all child elements recursively using CSS?" }, { "code": null, "e": 2379, "s": 2340, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2418, "s": 2379, "text": "CSS | :not(:last-child):after Selector" }, { "code": null, "e": 2451, "s": 2418, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2512, "s": 2451, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2555, "s": 2512, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2627, "s": 2555, "text": "Differences between Functional Components and Class Components in React" } ]
Magic numbers | Practice | GeeksforGeeks
Given two function, one is h(x) which is the product of all the number in an array A[ ] having size N and another function f(x) which denotes the GCD of all the numbers in an array. Your task is to find the value of h(x)f(x). Note: Since the answer can be very large, use modulo 109+7. Example 1: Input: N = 2, A[] = {2, 4} Output: 64 Explanation: h(x) = 8, f(x) = 2, Therefore, the answer is 82 = 64. Example 2: Input: N = 3, A[] = {1, 3, 7} Output: 21 Explanation: h(x) = 21, f(x) = 1, Therefore, the answer is 211 = 21. Your Task: You don't need to read input or print anything. Your task is to complete the function getVal() which takes an Integer N and an array of integers A[] as input and returns the answer. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 105 1 <= A[i] <= 105 0 mustangg3 months ago Why its not working!!!! class Solution { static Long getVal(int N, int[] A) { long mult = 1; long po = 0; long mod=1000000007; for(int i: A) { mult*=i; } long res = 0; for(int i:A){ res = gcd(res,i); } po =(long) Math.pow(mult,res); return po%mod; } static long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } }; 0 user00375 months ago long long gcd(long long a,long long b){ if(b==0){ return a; } return gcd(b,a%b); } long long getVal(int N, int A[]) { // code here long long g=A[0],l=A[0],mod=1000000007; for(int i=1;i<N;i++){ g = gcd(g,A[i]); l = (l*A[i])%mod; } long long ans = pow(l,g); return ans%mod; } 0 Ujjwal Pandey1 year ago Ujjwal Pandey class Solution { static long modulo = 1000000007 ; static Long getVal(int N, int[] A) { // code here long pdct = product(A, A.length) ; long cal = cal(A, A.length) ; long res = 1 ; while(cal > 0){ if((cal & 1) != 0){ res = (res%modulo * pdct%modulo) % modulo ; } pdct = (pdct*pdct)%modulo ; cal = cal >> 1 ; } return res%modulo ; } static long product( int[] A, int N){ long prod = 1 ; for(int val: A) { prod *= (val%modulo) ; } return prod%modulo ; } static long cal(int[] A, int n) {long ans = A[0] ;long res = 0 ;for(int i = 1 ; i < n ; i++) {ans = (getGCD(ans, A[i])%modulo) ; } return (ans%modulo) ;} static long getGCD(long a, long b) {if(b == 0)return (a%modulo) ; return getGCD(b, a % b)%modulo ;}} Wrong Answer. !!!Wrong Answer Possibly your code doesn't work correctly for multiple test-cases (TCs). The first test case where your code failed: Input:76612759 17064 14213 26992 20182 26404 22253 26342 15533 32565 11569 16113 328 13166 20909 14412 25099 9967 16651 27337 11784 26833 6421 23518 30838 5317 18119 17505 22366 26359 23209 25488 31384 18233 30556 852 12022 3933 3698 4551 8639 4322 24451 29683 30815 7636 28028 30173 4188 6381 24123 31682 31628 20736 30809 22688 3206 11160 13127 28152 1878 25308 3485 30930 19061 23221 7598 12291 1016 20787 4192 6059 18183 28205 2619 11777 5521 30248 7871 21843 12862 9338 20987 8008 20133 28848 22619 2................. Its Correct output is:64263939 And Your Code's output is:0 please figure out the problem We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 525, "s": 238, "text": "Given two function, one is h(x) which is the product of all the number in an array A[ ] having size N and another\nfunction f(x) which denotes the GCD of all the numbers in an array. Your task is to find the value of h(x)f(x).\nNote: Since the answer can be very large, use modulo 109+7." }, { "code": null, "e": 536, "s": 525, "text": "Example 1:" }, { "code": null, "e": 641, "s": 536, "text": "Input:\nN = 2, A[] = {2, 4}\nOutput:\n64\nExplanation:\nh(x) = 8, f(x) = 2, Therefore, the\nanswer is 82 = 64." }, { "code": null, "e": 652, "s": 641, "text": "Example 2:" }, { "code": null, "e": 763, "s": 652, "text": "Input:\nN = 3, A[] = {1, 3, 7}\nOutput:\n21\nExplanation:\nh(x) = 21, f(x) = 1, Therefore, the\nanswer is 211 = 21.\n" }, { "code": null, "e": 956, "s": 763, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function getVal() which takes an Integer N and an array of integers A[] as input and returns the answer." }, { "code": null, "e": 1018, "s": 956, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1062, "s": 1018, "text": "Constraints:\n1 <= N <= 105\n1 <= A[i] <= 105" }, { "code": null, "e": 1064, "s": 1062, "text": "0" }, { "code": null, "e": 1085, "s": 1064, "text": "mustangg3 months ago" }, { "code": null, "e": 1109, "s": 1085, "text": "Why its not working!!!!" }, { "code": null, "e": 1562, "s": 1109, "text": "class Solution {\n static Long getVal(int N, int[] A) {\n long mult = 1;\n long po = 0;\n long mod=1000000007;\n for(int i: A)\n {\n mult*=i;\n }\n long res = 0;\n for(int i:A){\n \n res = gcd(res,i);\n }\n po =(long) Math.pow(mult,res);\n \n return po%mod;\n }\n \n static long gcd(long a,long b)\n {\n return a==0?b:gcd(b%a,a);\n }\n};" }, { "code": null, "e": 1564, "s": 1562, "text": "0" }, { "code": null, "e": 1585, "s": 1564, "text": "user00375 months ago" }, { "code": null, "e": 1987, "s": 1585, "text": "long long gcd(long long a,long long b){\n if(b==0){\n return a;\n }\n return gcd(b,a%b);\n }\n long long getVal(int N, int A[]) {\n // code here\n \n long long g=A[0],l=A[0],mod=1000000007;\n for(int i=1;i<N;i++){\n g = gcd(g,A[i]);\n l = (l*A[i])%mod;\n }\n \n long long ans = pow(l,g);\n return ans%mod;\n }" }, { "code": null, "e": 1993, "s": 1991, "text": "0" }, { "code": null, "e": 2017, "s": 1993, "text": "Ujjwal Pandey1 year ago" }, { "code": null, "e": 2031, "s": 2017, "text": "Ujjwal Pandey" }, { "code": null, "e": 2372, "s": 2031, "text": "class Solution { static long modulo = 1000000007 ; static Long getVal(int N, int[] A) { // code here long pdct = product(A, A.length) ; long cal = cal(A, A.length) ; long res = 1 ; while(cal > 0){ if((cal & 1) != 0){ res = (res%modulo * pdct%modulo) % modulo ; }" }, { "code": null, "e": 2449, "s": 2372, "text": " pdct = (pdct*pdct)%modulo ; cal = cal >> 1 ; }" }, { "code": null, "e": 2482, "s": 2449, "text": " return res%modulo ; }" }, { "code": null, "e": 2547, "s": 2482, "text": " static long product( int[] A, int N){ long prod = 1 ;" }, { "code": null, "e": 2612, "s": 2547, "text": " for(int val: A) { prod *= (val%modulo) ; }" }, { "code": null, "e": 2646, "s": 2612, "text": " return prod%modulo ; }" }, { "code": null, "e": 2779, "s": 2646, "text": " static long cal(int[] A, int n) {long ans = A[0] ;long res = 0 ;for(int i = 1 ; i < n ; i++) {ans = (getGCD(ans, A[i])%modulo) ;" }, { "code": null, "e": 2781, "s": 2779, "text": "}" }, { "code": null, "e": 2804, "s": 2781, "text": "return (ans%modulo) ;}" }, { "code": null, "e": 2870, "s": 2804, "text": "static long getGCD(long a, long b) {if(b == 0)return (a%modulo) ;" }, { "code": null, "e": 2905, "s": 2870, "text": "return getGCD(b, a % b)%modulo ;}}" }, { "code": null, "e": 2935, "s": 2905, "text": "Wrong Answer. !!!Wrong Answer" }, { "code": null, "e": 3008, "s": 2935, "text": "Possibly your code doesn't work correctly for multiple test-cases (TCs)." }, { "code": null, "e": 3052, "s": 3008, "text": "The first test case where your code failed:" }, { "code": null, "e": 3575, "s": 3052, "text": "Input:76612759 17064 14213 26992 20182 26404 22253 26342 15533 32565 11569 16113 328 13166 20909 14412 25099 9967 16651 27337 11784 26833 6421 23518 30838 5317 18119 17505 22366 26359 23209 25488 31384 18233 30556 852 12022 3933 3698 4551 8639 4322 24451 29683 30815 7636 28028 30173 4188 6381 24123 31682 31628 20736 30809 22688 3206 11160 13127 28152 1878 25308 3485 30930 19061 23221 7598 12291 1016 20787 4192 6059 18183 28205 2619 11777 5521 30248 7871 21843 12862 9338 20987 8008 20133 28848 22619 2................." }, { "code": null, "e": 3606, "s": 3575, "text": "Its Correct output is:64263939" }, { "code": null, "e": 3634, "s": 3606, "text": "And Your Code's output is:0" }, { "code": null, "e": 3664, "s": 3634, "text": "please figure out the problem" }, { "code": null, "e": 3810, "s": 3664, "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": 3846, "s": 3810, "text": " Login to access your submissions. " }, { "code": null, "e": 3856, "s": 3846, "text": "\nProblem\n" }, { "code": null, "e": 3866, "s": 3856, "text": "\nContest\n" }, { "code": null, "e": 3929, "s": 3866, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4077, "s": 3929, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4285, "s": 4077, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4391, "s": 4285, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How can we use MySQL INSTR() function with WHERE clause?
When we use INSTR() function with MySQL WHERE clause, we need to provide column name of the table as the first argument and the substring as second argument along with a comparison operator. Following is an example using ‘Student’ table to demonstrate it − Suppose we have the following values in ‘Student’ table − mysql> Select * from Student; +------+---------+---------+-----------+ | Id | Name | Address | Subject | +------+---------+---------+-----------+ | 1 | Gaurav | Delhi | Computers | | 2 | Aarav | Mumbai | History | | 15 | Harshit | Delhi | Commerce | | 20 | Gaurav | Jaipur | Computers | | 21 | Yashraj | NULL | Math | +------+---------+---------+-----------+ 5 rows in set (0.02 sec) Now, following query show how we can use INSTR() function with WHERE caluse − mysql> select name, INSTR(Name,'av')As Result from student where INSTR(Name,'av') > 0; +--------+--------+ | name | Result | +--------+--------+ | Gaurav | 5 | | Aarav | 4 | | Gaurav | 5 | +--------+--------+ 3 rows in set (0.00 sec) mysql> select name, INSTR(Name,'av')As Result from student where INSTR(Name,'av') = 0 ; +---------+--------+ | name | Result | +---------+--------+ | Harshit | 0 | | Yashraj | 0 | +---------+--------+ 2 rows in set (0.01 sec)
[ { "code": null, "e": 1319, "s": 1062, "text": "When we use INSTR() function with MySQL WHERE clause, we need to provide column name of the table as the first argument and the substring as second argument along with a comparison operator. Following is an example using ‘Student’ table to demonstrate it −" }, { "code": null, "e": 1377, "s": 1319, "text": "Suppose we have the following values in ‘Student’ table −" }, { "code": null, "e": 1802, "s": 1377, "text": "mysql> Select * from Student;\n+------+---------+---------+-----------+\n| Id | Name | Address | Subject |\n+------+---------+---------+-----------+\n| 1 | Gaurav | Delhi | Computers |\n| 2 | Aarav | Mumbai | History |\n| 15 | Harshit | Delhi | Commerce |\n| 20 | Gaurav | Jaipur | Computers |\n| 21 | Yashraj | NULL | Math |\n+------+---------+---------+-----------+\n\n5 rows in set (0.02 sec)" }, { "code": null, "e": 1880, "s": 1802, "text": "Now, following query show how we can use INSTR() function with WHERE caluse −" }, { "code": null, "e": 2376, "s": 1880, "text": "mysql> select name, INSTR(Name,'av')As Result from student where INSTR(Name,'av') > 0;\n\n+--------+--------+\n| name | Result |\n+--------+--------+\n| Gaurav | 5 |\n| Aarav | 4 |\n| Gaurav | 5 |\n+--------+--------+\n\n3 rows in set (0.00 sec)\n\nmysql> select name, INSTR(Name,'av')As Result from student where INSTR(Name,'av') = 0 ;\n\n+---------+--------+\n| name | Result |\n+---------+--------+\n| Harshit | 0 |\n| Yashraj | 0 |\n+---------+--------+\n\n2 rows in set (0.01 sec)" } ]
PyQt5 - QFileDialog Widget
This widget is a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. The dialog is invoked either through static functions or by calling exec_() function on the dialog object. Static functions of QFileDialog class (getOpenFileName() and getSaveFileName()) call the native file dialog of the current operating system. A file filter can also applied to display only files of the specified extensions. The starting directory and default file name can also be set. Important methods and enumerations of QFileDialog class are listed in the following table − getOpenFileName() Returns name of the file selected by the user to open it getSaveFileName() Uses the file name selected by the user to save the file setacceptMode() Determines whether the file box acts as open or save dialog QFileDialog.AcceptOpen QFileDialog.AcceptSave setFileMode() Type of selectable files. Enumerated constants are − QFileDialog.AnyFile QFileDialog.ExistingFile QFileDialog.Directory QFileDialog.ExistingFiles setFilter() Displays only those files having mentioned extensions Both methods of invoking the file dialog are demonstrated in the following example. The first button invokes the file dialog by the static method. fname = QFileDialog.getOpenFileName(self, 'Open file', 'c:\\',"Image files (*.jpg *.gif)") The selected image file is displayed on a label widget. The second button invokes the file dialog by calling exec_() method on QFileDialog object. dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter("Text files (*.txt)") filenames = QStringList() if dlg.exec_(): filenames = dlg.selectedFiles() The contents of the selected file are displayed in the TextEdit widget. f = open(filenames[0], 'r') with f: data = f.read() self.contents.setText(data) The complete code is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class filedialogdemo(QWidget): def __init__(self, parent = None): super(filedialogdemo, self).__init__(parent) layout = QVBoxLayout() self.btn = QPushButton("QFileDialog static method demo") self.btn.clicked.connect(self.getfile) layout.addWidget(self.btn) self.le = QLabel("Hello") layout.addWidget(self.le) self.btn1 = QPushButton("QFileDialog object") self.btn1.clicked.connect(self.getfiles) layout.addWidget(self.btn1) self.contents = QTextEdit() layout.addWidget(self.contents) self.setLayout(layout) self.setWindowTitle("File Dialog demo") def getfile(self): fname = QFileDialog.getOpenFileName(self, 'Open file', 'c:\\',"Image files (*.jpg *.gif)") self.le.setPixmap(QPixmap(fname)) def getfiles(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter("Text files (*.txt)") filenames = QStringList() if dlg.exec_(): filenames = dlg.selectedFiles() f = open(filenames[0], 'r') with f: data = f.read() self.contents.setText(data) def main(): app = QApplication(sys.argv) ex = filedialogdemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output − The complete code for exec_() method is as follows − import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class CustomDialog(QFileDialog): def __init__(self, *args, **kwargs): super(CustomDialog, self).__init__(*args, **kwargs) self.setWindowTitle("HELLO!") QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(QBtn) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout = QVBoxLayout() self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) class filedialogdemo(QWidget): def __init__(self, parent = None): super(filedialogdemo, self).__init__(parent) layout = QVBoxLayout() self.btn1 = QPushButton("QFileDialog object") self.btn1.clicked.connect(self.getfiles) layout.addWidget(self.btn1) self.contents = QTextEdit() layout.addWidget(self.contents) self.setLayout(layout) self.setWindowTitle("File Dialog demo") def getfiles(self, s): print("click", s) dlg = CustomDialog(self) if dlg.exec_(): filenames = dlg.selectedFiles() f = open(filenames[0], 'r') with f: data = f.read() self.contents.setText(data) def main(): app = QApplication(sys.argv) ex = filedialogdemo() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() The above code produces the following output − Text in selected file will be displayed in TextEdit control. 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2200, "s": 1963, "text": "This widget is a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. The dialog is invoked either through static functions or by calling exec_() function on the dialog object." }, { "code": null, "e": 2341, "s": 2200, "text": "Static functions of QFileDialog class (getOpenFileName() and getSaveFileName()) call the native file dialog of the current operating system." }, { "code": null, "e": 2485, "s": 2341, "text": "A file filter can also applied to display only files of the specified extensions. The starting directory and default file name can also be set." }, { "code": null, "e": 2577, "s": 2485, "text": "Important methods and enumerations of QFileDialog class are listed in the following table −" }, { "code": null, "e": 2595, "s": 2577, "text": "getOpenFileName()" }, { "code": null, "e": 2652, "s": 2595, "text": "Returns name of the file selected by the user to open it" }, { "code": null, "e": 2670, "s": 2652, "text": "getSaveFileName()" }, { "code": null, "e": 2727, "s": 2670, "text": "Uses the file name selected by the user to save the file" }, { "code": null, "e": 2743, "s": 2727, "text": "setacceptMode()" }, { "code": null, "e": 2803, "s": 2743, "text": "Determines whether the file box acts as open or save dialog" }, { "code": null, "e": 2826, "s": 2803, "text": "QFileDialog.AcceptOpen" }, { "code": null, "e": 2849, "s": 2826, "text": "QFileDialog.AcceptSave" }, { "code": null, "e": 2863, "s": 2849, "text": "setFileMode()" }, { "code": null, "e": 2916, "s": 2863, "text": "Type of selectable files. Enumerated constants are −" }, { "code": null, "e": 2936, "s": 2916, "text": "QFileDialog.AnyFile" }, { "code": null, "e": 2961, "s": 2936, "text": "QFileDialog.ExistingFile" }, { "code": null, "e": 2983, "s": 2961, "text": "QFileDialog.Directory" }, { "code": null, "e": 3009, "s": 2983, "text": "QFileDialog.ExistingFiles" }, { "code": null, "e": 3021, "s": 3009, "text": "setFilter()" }, { "code": null, "e": 3075, "s": 3021, "text": "Displays only those files having mentioned extensions" }, { "code": null, "e": 3159, "s": 3075, "text": "Both methods of invoking the file dialog are demonstrated in the following example." }, { "code": null, "e": 3222, "s": 3159, "text": "The first button invokes the file dialog by the static method." }, { "code": null, "e": 3318, "s": 3222, "text": "fname = QFileDialog.getOpenFileName(self, 'Open file', \n 'c:\\\\',\"Image files (*.jpg *.gif)\")\n" }, { "code": null, "e": 3465, "s": 3318, "text": "The selected image file is displayed on a label widget. The second button invokes the file dialog by calling exec_() method on QFileDialog object." }, { "code": null, "e": 3642, "s": 3465, "text": "dlg = QFileDialog()\ndlg.setFileMode(QFileDialog.AnyFile)\ndlg.setFilter(\"Text files (*.txt)\")\nfilenames = QStringList()\n\n if dlg.exec_():\n filenames = dlg.selectedFiles()" }, { "code": null, "e": 3714, "s": 3642, "text": "The contents of the selected file are displayed in the TextEdit widget." }, { "code": null, "e": 3809, "s": 3714, "text": "f = open(filenames[0], 'r')\n with f:\n data = f.read()\n self.contents.setText(data)" }, { "code": null, "e": 3843, "s": 3809, "text": "The complete code is as follows −" }, { "code": null, "e": 5268, "s": 3843, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass filedialogdemo(QWidget):\n def __init__(self, parent = None):\n super(filedialogdemo, self).__init__(parent)\n\t\t\n layout = QVBoxLayout()\n self.btn = QPushButton(\"QFileDialog static method demo\")\n self.btn.clicked.connect(self.getfile)\n\t\t\n layout.addWidget(self.btn)\n self.le = QLabel(\"Hello\")\n\t\t\n layout.addWidget(self.le)\n self.btn1 = QPushButton(\"QFileDialog object\")\n self.btn1.clicked.connect(self.getfiles)\n layout.addWidget(self.btn1)\n\t\t\n self.contents = QTextEdit()\n layout.addWidget(self.contents)\n self.setLayout(layout)\n self.setWindowTitle(\"File Dialog demo\")\n\t\t\n def getfile(self):\n fname = QFileDialog.getOpenFileName(self, 'Open file', \n 'c:\\\\',\"Image files (*.jpg *.gif)\")\n self.le.setPixmap(QPixmap(fname))\n\t\t\n def getfiles(self):\n dlg = QFileDialog()\n dlg.setFileMode(QFileDialog.AnyFile)\n dlg.setFilter(\"Text files (*.txt)\")\n filenames = QStringList()\n\t\t\n if dlg.exec_():\n filenames = dlg.selectedFiles()\n f = open(filenames[0], 'r')\n\t\t\t\n with f:\n data = f.read()\n self.contents.setText(data)\n\t\t\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = filedialogdemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 5315, "s": 5268, "text": "The above code produces the following output −" }, { "code": null, "e": 5368, "s": 5315, "text": "The complete code for exec_() method is as follows −" }, { "code": null, "e": 6792, "s": 5368, "text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nclass CustomDialog(QFileDialog):\n\n def __init__(self, *args, **kwargs):\n super(CustomDialog, self).__init__(*args, **kwargs)\n \n self.setWindowTitle(\"HELLO!\")\n\n QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel\n\n self.buttonBox = QDialogButtonBox(QBtn)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.buttonBox)\n self.setLayout(self.layout)\n\nclass filedialogdemo(QWidget):\n def __init__(self, parent = None):\n\n super(filedialogdemo, self).__init__(parent)\n\n layout = QVBoxLayout()\n\n self.btn1 = QPushButton(\"QFileDialog object\")\n self.btn1.clicked.connect(self.getfiles)\n layout.addWidget(self.btn1)\n\n self.contents = QTextEdit()\n layout.addWidget(self.contents)\n self.setLayout(layout)\n self.setWindowTitle(\"File Dialog demo\")\n\n def getfiles(self, s):\n print(\"click\", s)\n dlg = CustomDialog(self)\n if dlg.exec_():\n filenames = dlg.selectedFiles()\n f = open(filenames[0], 'r')\n\n with f:\n data = f.read()\n self.contents.setText(data)\ndef main():\n\n app = QApplication(sys.argv)\n ex = filedialogdemo()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 6839, "s": 6792, "text": "The above code produces the following output −" }, { "code": null, "e": 6900, "s": 6839, "text": "Text in selected file will be displayed in TextEdit control." }, { "code": null, "e": 6937, "s": 6900, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 6947, "s": 6937, "text": " ALAA EID" }, { "code": null, "e": 6954, "s": 6947, "text": " Print" }, { "code": null, "e": 6965, "s": 6954, "text": " Add Notes" } ]
Flutter - Horizontal List - GeeksforGeeks
30 Nov, 2021 In Flutter there can be Two types of lists, namely, horizontal list and vertical list. Both these lists are created using the ListView constructor and assigning the scrollDirection parameter. By default, the scroll direction parameter is vertical for a vertical list but it can be overridden by passing a horizontal parameter to it. ListView( {Key key, Axis scrollDirection: Axis.vertical, bool reverse: false, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap: false, EdgeInsetsGeometry padding, double itemExtent, bool addAutomaticKeepAlives: true, bool addRepaintBoundaries: true, bool addSemanticIndexes: true, double cacheExtent, List<Widget> children: const <Widget>[], int semanticChildCount, DragStartBehavior dragStartBehavior: DragStartBehavior.start, ScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual, String restorationId, Clip clipBehavior: Clip.hardEdge} ) childrenDelegate: This property takes in SliverChildDelegate class as the object. It provides a children delegate for the Listview. itemExtent: The itemExtent property takes in a double value as the object to set the extent of the scrollable area for the ListView. In this article, we will look into the process of creating a horizontal list. For the same purpose, we will design a simple app that shows a list of images of superheroes in a horizontal direction. To do so we will need to follow the below steps: Create a statelessWidget (say, Myapp) Add scaffold widget to hold the containers Add container containing the images inside a ListView constructor It is important to note that all the images used in the application will be stored in the assets/images folder as shown below: Also, the assets dependency needs to be stated in the pubspec.yaml file as shown below: Now let’s look into them in detail. To create a stateful widget that provides a base structure to the application using the below code: Dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'GeeksForGeeks'; return MaterialApp() To add a scaffold widget inside the statelessWidget use the below technique: Dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'GeeksForGeeks'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: Text(title), ) A simple ListView with containers can be created as follows: Dart ListView( scrollDirection: Axis.horizontal, children: <Widget>[ Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/aquaman.png'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/greenlantern.webp'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 240.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/batman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/superman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/wonderwomen.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), ], ), Now that we have designed all the essential components of the app, it’s time to integrate them into one complete app as follows: Complete Source Code: Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'GeeksForGeeks'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: Text(title), backgroundColor: Colors.green, ), body: Container( margin: EdgeInsets.symmetric(vertical: 20.0), height: 550.0, child: ListView( scrollDirection: Axis.horizontal, children: <Widget>[ Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/aquaman.png'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/greenlantern.webp'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 240.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/batman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/superman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/wonderwomen.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), ], ), ), ), ); }} Output: ankit_kumar_ vinitmppromail android Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Listview.builder in Flutter Flutter - DropDownButton Widget Flutter - Asset Image Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - BoxShadow Widget Flutter - Flexible Widget
[ { "code": null, "e": 25938, "s": 25910, "text": "\n30 Nov, 2021" }, { "code": null, "e": 26271, "s": 25938, "text": "In Flutter there can be Two types of lists, namely, horizontal list and vertical list. Both these lists are created using the ListView constructor and assigning the scrollDirection parameter. By default, the scroll direction parameter is vertical for a vertical list but it can be overridden by passing a horizontal parameter to it." }, { "code": null, "e": 26891, "s": 26271, "text": "ListView(\n{Key key,\nAxis scrollDirection: Axis.vertical,\nbool reverse: false,\nScrollController controller,\nbool primary,\nScrollPhysics physics,\nbool shrinkWrap: false,\nEdgeInsetsGeometry padding,\ndouble itemExtent,\nbool addAutomaticKeepAlives: true,\nbool addRepaintBoundaries: true,\nbool addSemanticIndexes: true,\ndouble cacheExtent,\nList<Widget> children: const <Widget>[],\nint semanticChildCount,\nDragStartBehavior dragStartBehavior: DragStartBehavior.start,\nScrollViewKeyboardDismissBehavior keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,\nString restorationId,\nClip clipBehavior: Clip.hardEdge}\n)" }, { "code": null, "e": 27023, "s": 26891, "text": "childrenDelegate: This property takes in SliverChildDelegate class as the object. It provides a children delegate for the Listview." }, { "code": null, "e": 27156, "s": 27023, "text": "itemExtent: The itemExtent property takes in a double value as the object to set the extent of the scrollable area for the ListView." }, { "code": null, "e": 27403, "s": 27156, "text": "In this article, we will look into the process of creating a horizontal list. For the same purpose, we will design a simple app that shows a list of images of superheroes in a horizontal direction. To do so we will need to follow the below steps:" }, { "code": null, "e": 27441, "s": 27403, "text": "Create a statelessWidget (say, Myapp)" }, { "code": null, "e": 27484, "s": 27441, "text": "Add scaffold widget to hold the containers" }, { "code": null, "e": 27550, "s": 27484, "text": "Add container containing the images inside a ListView constructor" }, { "code": null, "e": 27677, "s": 27550, "text": "It is important to note that all the images used in the application will be stored in the assets/images folder as shown below:" }, { "code": null, "e": 27765, "s": 27677, "text": "Also, the assets dependency needs to be stated in the pubspec.yaml file as shown below:" }, { "code": null, "e": 27801, "s": 27765, "text": "Now let’s look into them in detail." }, { "code": null, "e": 27901, "s": 27801, "text": "To create a stateful widget that provides a base structure to the application using the below code:" }, { "code": null, "e": 27906, "s": 27901, "text": "Dart" }, { "code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'GeeksForGeeks'; return MaterialApp()", "e": 28052, "s": 27906, "text": null }, { "code": null, "e": 28134, "s": 28057, "text": "To add a scaffold widget inside the statelessWidget use the below technique:" }, { "code": null, "e": 28141, "s": 28136, "text": "Dart" }, { "code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'GeeksForGeeks'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: Text(title), )", "e": 28387, "s": 28141, "text": null }, { "code": null, "e": 28453, "s": 28392, "text": "A simple ListView with containers can be created as follows:" }, { "code": null, "e": 28460, "s": 28455, "text": "Dart" }, { "code": "ListView( scrollDirection: Axis.horizontal, children: <Widget>[ Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/aquaman.png'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/greenlantern.webp'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 240.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/batman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/superman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/wonderwomen.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), ], ),", "e": 30479, "s": 28460, "text": null }, { "code": null, "e": 30611, "s": 30482, "text": "Now that we have designed all the essential components of the app, it’s time to integrate them into one complete app as follows:" }, { "code": null, "e": 30635, "s": 30613, "text": "Complete Source Code:" }, { "code": null, "e": 30642, "s": 30637, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'GeeksForGeeks'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: Text(title), backgroundColor: Colors.green, ), body: Container( margin: EdgeInsets.symmetric(vertical: 20.0), height: 550.0, child: ListView( scrollDirection: Axis.horizontal, children: <Widget>[ Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/aquaman.png'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/greenlantern.webp'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 240.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/batman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/superman.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), Container( height: 480.0, width: 240.0, decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'assets/images/wonderwomen.jpg'), fit: BoxFit.fill, ), shape: BoxShape.rectangle, ), ), ], ), ), ), ); }}", "e": 33231, "s": 30642, "text": null }, { "code": null, "e": 33242, "s": 33234, "text": "Output:" }, { "code": null, "e": 33259, "s": 33246, "text": "ankit_kumar_" }, { "code": null, "e": 33274, "s": 33259, "text": "vinitmppromail" }, { "code": null, "e": 33282, "s": 33274, "text": "android" }, { "code": null, "e": 33290, "s": 33282, "text": "Flutter" }, { "code": null, "e": 33312, "s": 33290, "text": "Flutter UI-components" }, { "code": null, "e": 33317, "s": 33312, "text": "Dart" }, { "code": null, "e": 33325, "s": 33317, "text": "Flutter" }, { "code": null, "e": 33423, "s": 33325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33451, "s": 33423, "text": "Listview.builder in Flutter" }, { "code": null, "e": 33483, "s": 33451, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33505, "s": 33483, "text": "Flutter - Asset Image" }, { "code": null, "e": 33544, "s": 33505, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33569, "s": 33544, "text": "Splash Screen in Flutter" }, { "code": null, "e": 33601, "s": 33569, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33640, "s": 33601, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33666, "s": 33640, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 33693, "s": 33666, "text": "Flutter - BoxShadow Widget" } ]
Gaussian Mixture Models Clustering Algorithm Explained | by Cory Maklin | Towards Data Science
Gaussian mixture models can be used to cluster unlabeled data in much the same way as k-means. There are, however, a couple of advantages to using Gaussian mixture models over k-means. First and foremost, k-means does not account for variance. By variance, we are referring to the width of the bell shape curve. In two dimensions, variance (covariance to be exact) determines the shape of the distribution. One way to think about the k-means model is that it places a circle (or, in higher dimensions, a hyper-sphere) at the center of each cluster, with a radius defined by the most distant point in the cluster. This works fine for when your data is circular. However, when your data takes on different shape, you end up with something like this. In contrast, Gaussian mixture models can handle even very oblong clusters. The second difference between k-means and Gaussian mixture models is that the former performs hard classification whereas the latter performs soft classification. In other words, k-means tells us what data point belong to which cluster but won’t provide us with the probabilities that a given data point belongs to each of the possible clusters. In calling the predict function, the model will assign every data point to one of the clusters. gmm.predict(X) On the other hand, we can call the predict_proba function to return the probabilities that a data point belongs to each of the K clusters. gmm.predict_proba(X) As the name implies, a Gaussian mixture model involves the mixture (i.e. superposition) of multiple Gaussian distributions. For the sake of explanation, suppose we had three distributions made up of samples from three distinct classes. The blue Gaussian represents the level of education of people that make up the lower class. The red Gaussian represents the level of education of people that make up the middle class, and the green Gaussian represents the level of education of people that make up the upper class. Not knowing what samples came from which class, our goal will be to use Gaussian Mixture Models to assign the data points to the appropriate cluster. After training the model, we’d ideally end up with three distributions on the same axis. Then, depending on the level of education of a given sample (where it is located on the axis), we’d place it in one of the three categories. Every distribution is multiplied by a weight π to account for the fact that we do not have an equal number of samples from each category. In other words, we might only have included 1000 people from the upper class and 100,000 people from the middle class. Since, we’re dealing with probabilities, the weights should add to 1, when summed. If we decided to add another dimension such as the number of children, then, it might look something like this. For those of you who aren’t mathematically inclined, I apologize in advance as the next section is quite heavy. Let’s suppose we wanted to know what is the likelihood that the ith sample came from Gaussian k. We can express this as: Where theta represents the mean, covariance and weight for each Gaussian. You may also come across the equation written as π. This is not to be confused with the weight associated with each Gaussian (confusing I know). Next, we express the likelihood of observing a data point given that it came from Gaussian K as: The latter is sometimes written as follows (I believe the N comes from Normal Distribution): Suppose we had a Gaussian distribution where the horizontal axis is the different IQ scores an individual could possibly get, lowest through highest. We can find out how likely it is for an individual to have an IQ of 120 by drawing a vertical line from the position along the x-axis to the curve and then looking at the corresponding value on the y-axis. The value of y at any point is equal to the equation above. If we’d like to know the likelihood of observing the sample i while taking into account all the different distributions, we simply sum the likelihoods of observing the sample given that it came from each of the possible Gaussian. Said differently, we take one sample (row) from our dataset, look at a single feature (i.e. level of education), plot its position on the x-axis and sum the corresponding y values (likelihood) for each distribution. In order to extend this to all samples in our dataset. We assume the likelihood of observing one sample is independent from all the others and then we can simply multiply them. We can rewrite the equation using the nomenclature we saw previously as follows: More often than not, we take the log of the likelihood because the multiplication of two numbers inside of a log is equal to the sum of the logs of its constituents, and it’s easier to add numbers than to multiply them. We have yet to address the fact that we need the parameters of each Gaussian (i.e. variance, mean and weight) in order to cluster our data but we need to know which sample belongs to what Gaussian in order to estimate those very same parameters. This is where expectation maximization comes in to play. At a high level, the expectation maximization algorithm can be described as follows: Start with random Gaussian parameters (θ)Repeat the following until we converge: Start with random Gaussian parameters (θ) Repeat the following until we converge: a) Expectation Step: Compute p(zi = k | xi, θ). In other words, does sample i look like it came from cluster k? b) Maximization Step: Update the Gaussian parameters (θ) to fit points assigned to them. In the maximization step, we want to maximize the likelihood that each sample came from the distribution. Recall, that the likelihood is the height of the curve at a point along the x-axis. Therefore, we want to modify the variance and mean of the distribution such that the height of the plot at each data point is maximized. This brings up the question, “How should we go about selecting the optimal values for the variance and mean.” Using the general form of expectation maximization, we can derive a set of equations for the mean, variance and weight. We can follow the same process to obtain the equations for the covariance and weight. Once we have the equations, we simply apply them during the maximization step. That is to say, we plugin in the numbers in each equation to determine the best mean, covariance, weight, and then set the Gaussian parameters accordingly. Let’s take a look at the math in action. Initially, we don’t know what points are associated with which distribution. We start off with K Gaussians (in this case, K=2) with random mean, variance and weight. Then, we repeat the expectation and maximization steps until there is little to no change in theta (θ). It’s worth noting, that the algorithm is susceptible to local maxima. Now, that we have a grasp of how Gaussian mixture models work, let’s take a look at how we could go about implementing them. To start, import the following libraries. import numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom sklearn.mixture import GaussianMixturefrom matplotlib import pyplot as pltimport seaborn as snssns.set() We randomly generate 4 clusters. X, y = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)plt.scatter(X[:,0], X[:,1]) The optimal number of clusters (K) is the value that minimizes the Akaike information criterion (AIC) or the Bayesian information criterion (BIC). n_components = np.arange(1, 21)models = [GaussianMixture(n, covariance_type='full', random_state=0).fit(X) for n in n_components]plt.plot(n_components, [m.bic(X) for m in models], label='BIC')plt.plot(n_components, [m.aic(X) for m in models], label='AIC')plt.legend(loc='best')plt.xlabel('n_components'); We train our model using the optimal number of clusters (in this case, 4). gmm = GaussianMixture(n_components=4)gmm.fit(X) We use the predict method to obtain a list of points and their respective clusters. labels = gmm.predict(X)plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis'); Unlike k-means, Gaussian mixture models account for variance and returns the probability that a data point belongs to each of the K clusters.
[ { "code": null, "e": 357, "s": 172, "text": "Gaussian mixture models can be used to cluster unlabeled data in much the same way as k-means. There are, however, a couple of advantages to using Gaussian mixture models over k-means." }, { "code": null, "e": 484, "s": 357, "text": "First and foremost, k-means does not account for variance. By variance, we are referring to the width of the bell shape curve." }, { "code": null, "e": 579, "s": 484, "text": "In two dimensions, variance (covariance to be exact) determines the shape of the distribution." }, { "code": null, "e": 785, "s": 579, "text": "One way to think about the k-means model is that it places a circle (or, in higher dimensions, a hyper-sphere) at the center of each cluster, with a radius defined by the most distant point in the cluster." }, { "code": null, "e": 920, "s": 785, "text": "This works fine for when your data is circular. However, when your data takes on different shape, you end up with something like this." }, { "code": null, "e": 995, "s": 920, "text": "In contrast, Gaussian mixture models can handle even very oblong clusters." }, { "code": null, "e": 1341, "s": 995, "text": "The second difference between k-means and Gaussian mixture models is that the former performs hard classification whereas the latter performs soft classification. In other words, k-means tells us what data point belong to which cluster but won’t provide us with the probabilities that a given data point belongs to each of the possible clusters." }, { "code": null, "e": 1437, "s": 1341, "text": "In calling the predict function, the model will assign every data point to one of the clusters." }, { "code": null, "e": 1452, "s": 1437, "text": "gmm.predict(X)" }, { "code": null, "e": 1591, "s": 1452, "text": "On the other hand, we can call the predict_proba function to return the probabilities that a data point belongs to each of the K clusters." }, { "code": null, "e": 1612, "s": 1591, "text": "gmm.predict_proba(X)" }, { "code": null, "e": 1848, "s": 1612, "text": "As the name implies, a Gaussian mixture model involves the mixture (i.e. superposition) of multiple Gaussian distributions. For the sake of explanation, suppose we had three distributions made up of samples from three distinct classes." }, { "code": null, "e": 2129, "s": 1848, "text": "The blue Gaussian represents the level of education of people that make up the lower class. The red Gaussian represents the level of education of people that make up the middle class, and the green Gaussian represents the level of education of people that make up the upper class." }, { "code": null, "e": 2279, "s": 2129, "text": "Not knowing what samples came from which class, our goal will be to use Gaussian Mixture Models to assign the data points to the appropriate cluster." }, { "code": null, "e": 2509, "s": 2279, "text": "After training the model, we’d ideally end up with three distributions on the same axis. Then, depending on the level of education of a given sample (where it is located on the axis), we’d place it in one of the three categories." }, { "code": null, "e": 2766, "s": 2509, "text": "Every distribution is multiplied by a weight π to account for the fact that we do not have an equal number of samples from each category. In other words, we might only have included 1000 people from the upper class and 100,000 people from the middle class." }, { "code": null, "e": 2849, "s": 2766, "text": "Since, we’re dealing with probabilities, the weights should add to 1, when summed." }, { "code": null, "e": 2961, "s": 2849, "text": "If we decided to add another dimension such as the number of children, then, it might look something like this." }, { "code": null, "e": 3073, "s": 2961, "text": "For those of you who aren’t mathematically inclined, I apologize in advance as the next section is quite heavy." }, { "code": null, "e": 3194, "s": 3073, "text": "Let’s suppose we wanted to know what is the likelihood that the ith sample came from Gaussian k. We can express this as:" }, { "code": null, "e": 3268, "s": 3194, "text": "Where theta represents the mean, covariance and weight for each Gaussian." }, { "code": null, "e": 3413, "s": 3268, "text": "You may also come across the equation written as π. This is not to be confused with the weight associated with each Gaussian (confusing I know)." }, { "code": null, "e": 3510, "s": 3413, "text": "Next, we express the likelihood of observing a data point given that it came from Gaussian K as:" }, { "code": null, "e": 3603, "s": 3510, "text": "The latter is sometimes written as follows (I believe the N comes from Normal Distribution):" }, { "code": null, "e": 4019, "s": 3603, "text": "Suppose we had a Gaussian distribution where the horizontal axis is the different IQ scores an individual could possibly get, lowest through highest. We can find out how likely it is for an individual to have an IQ of 120 by drawing a vertical line from the position along the x-axis to the curve and then looking at the corresponding value on the y-axis. The value of y at any point is equal to the equation above." }, { "code": null, "e": 4249, "s": 4019, "text": "If we’d like to know the likelihood of observing the sample i while taking into account all the different distributions, we simply sum the likelihoods of observing the sample given that it came from each of the possible Gaussian." }, { "code": null, "e": 4465, "s": 4249, "text": "Said differently, we take one sample (row) from our dataset, look at a single feature (i.e. level of education), plot its position on the x-axis and sum the corresponding y values (likelihood) for each distribution." }, { "code": null, "e": 4642, "s": 4465, "text": "In order to extend this to all samples in our dataset. We assume the likelihood of observing one sample is independent from all the others and then we can simply multiply them." }, { "code": null, "e": 4723, "s": 4642, "text": "We can rewrite the equation using the nomenclature we saw previously as follows:" }, { "code": null, "e": 4943, "s": 4723, "text": "More often than not, we take the log of the likelihood because the multiplication of two numbers inside of a log is equal to the sum of the logs of its constituents, and it’s easier to add numbers than to multiply them." }, { "code": null, "e": 5189, "s": 4943, "text": "We have yet to address the fact that we need the parameters of each Gaussian (i.e. variance, mean and weight) in order to cluster our data but we need to know which sample belongs to what Gaussian in order to estimate those very same parameters." }, { "code": null, "e": 5331, "s": 5189, "text": "This is where expectation maximization comes in to play. At a high level, the expectation maximization algorithm can be described as follows:" }, { "code": null, "e": 5412, "s": 5331, "text": "Start with random Gaussian parameters (θ)Repeat the following until we converge:" }, { "code": null, "e": 5454, "s": 5412, "text": "Start with random Gaussian parameters (θ)" }, { "code": null, "e": 5494, "s": 5454, "text": "Repeat the following until we converge:" }, { "code": null, "e": 5606, "s": 5494, "text": "a) Expectation Step: Compute p(zi = k | xi, θ). In other words, does sample i look like it came from cluster k?" }, { "code": null, "e": 5695, "s": 5606, "text": "b) Maximization Step: Update the Gaussian parameters (θ) to fit points assigned to them." }, { "code": null, "e": 6022, "s": 5695, "text": "In the maximization step, we want to maximize the likelihood that each sample came from the distribution. Recall, that the likelihood is the height of the curve at a point along the x-axis. Therefore, we want to modify the variance and mean of the distribution such that the height of the plot at each data point is maximized." }, { "code": null, "e": 6252, "s": 6022, "text": "This brings up the question, “How should we go about selecting the optimal values for the variance and mean.” Using the general form of expectation maximization, we can derive a set of equations for the mean, variance and weight." }, { "code": null, "e": 6338, "s": 6252, "text": "We can follow the same process to obtain the equations for the covariance and weight." }, { "code": null, "e": 6573, "s": 6338, "text": "Once we have the equations, we simply apply them during the maximization step. That is to say, we plugin in the numbers in each equation to determine the best mean, covariance, weight, and then set the Gaussian parameters accordingly." }, { "code": null, "e": 6691, "s": 6573, "text": "Let’s take a look at the math in action. Initially, we don’t know what points are associated with which distribution." }, { "code": null, "e": 6780, "s": 6691, "text": "We start off with K Gaussians (in this case, K=2) with random mean, variance and weight." }, { "code": null, "e": 6884, "s": 6780, "text": "Then, we repeat the expectation and maximization steps until there is little to no change in theta (θ)." }, { "code": null, "e": 6954, "s": 6884, "text": "It’s worth noting, that the algorithm is susceptible to local maxima." }, { "code": null, "e": 7121, "s": 6954, "text": "Now, that we have a grasp of how Gaussian mixture models work, let’s take a look at how we could go about implementing them. To start, import the following libraries." }, { "code": null, "e": 7306, "s": 7121, "text": "import numpy as npfrom sklearn.datasets.samples_generator import make_blobsfrom sklearn.mixture import GaussianMixturefrom matplotlib import pyplot as pltimport seaborn as snssns.set()" }, { "code": null, "e": 7339, "s": 7306, "text": "We randomly generate 4 clusters." }, { "code": null, "e": 7444, "s": 7339, "text": "X, y = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)plt.scatter(X[:,0], X[:,1])" }, { "code": null, "e": 7591, "s": 7444, "text": "The optimal number of clusters (K) is the value that minimizes the Akaike information criterion (AIC) or the Bayesian information criterion (BIC)." }, { "code": null, "e": 7896, "s": 7591, "text": "n_components = np.arange(1, 21)models = [GaussianMixture(n, covariance_type='full', random_state=0).fit(X) for n in n_components]plt.plot(n_components, [m.bic(X) for m in models], label='BIC')plt.plot(n_components, [m.aic(X) for m in models], label='AIC')plt.legend(loc='best')plt.xlabel('n_components');" }, { "code": null, "e": 7971, "s": 7896, "text": "We train our model using the optimal number of clusters (in this case, 4)." }, { "code": null, "e": 8019, "s": 7971, "text": "gmm = GaussianMixture(n_components=4)gmm.fit(X)" }, { "code": null, "e": 8103, "s": 8019, "text": "We use the predict method to obtain a list of points and their respective clusters." }, { "code": null, "e": 8183, "s": 8103, "text": "labels = gmm.predict(X)plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis');" } ]
How to serialize the order of properties using the Jackson library in Java?
The @JsonPropertyOrder is an annotation to be used at the class-level. It takes as property a list of fields that defines the order in which fields can appear in the string resulting from the object JSON serialization. The properties included in the annotation declaration can be serialized first(in defined order), followed by any properties not included in the definition. public @interface JsonPropertyOrder import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.util.*; import java.io.*; public class JsonPropertyOrderTest { public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException { Employee emp = new Employee(); emp.setFirstName("Adithya"); emp.setEmpId(25); emp.setLastName("Jai"); emp.getTechnologies().add("Java"); emp.getTechnologies().add("Scala"); emp.getTechnologies().add("Python"); ObjectMapper mapper = new ObjectMapper(); mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp); } } // Employee class @JsonPropertyOrder({ "firstName", "lastName", "technologies", "empId" }) class Employee { private int empId; private String firstName; private String lastName; private List<String> technologies = new ArrayList<>(); public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public List<String> getTechnologies() { return technologies; } public void setTechnologies(List<String> technologies) { this.technologies = technologies; } } { "firstName" : "Adithya", "lastName" : "Jai", "technologies" : [ "Java", "Scala", "Python" ], "empId" : 125 }
[ { "code": null, "e": 1437, "s": 1062, "text": "The @JsonPropertyOrder is an annotation to be used at the class-level. It takes as property a list of fields that defines the order in which fields can appear in the string resulting from the object JSON serialization. The properties included in the annotation declaration can be serialized first(in defined order), followed by any properties not included in the definition." }, { "code": null, "e": 1473, "s": 1437, "text": "public @interface JsonPropertyOrder" }, { "code": null, "e": 3037, "s": 1473, "text": "import com.fasterxml.jackson.core.*;\nimport com.fasterxml.jackson.databind.*;\nimport com.fasterxml.jackson.annotation.JsonPropertyOrder;\nimport java.util.*;\nimport java.io.*;\npublic class JsonPropertyOrderTest {\n public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {\n Employee emp = new Employee();\n emp.setFirstName(\"Adithya\");\n emp.setEmpId(25);\n emp.setLastName(\"Jai\");\n emp.getTechnologies().add(\"Java\");\n emp.getTechnologies().add(\"Scala\");\n emp.getTechnologies().add(\"Python\");\n ObjectMapper mapper = new ObjectMapper();\n mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);\n }\n}\n// Employee class\n@JsonPropertyOrder({\n \"firstName\",\n \"lastName\",\n \"technologies\",\n \"empId\"\n})\nclass Employee {\n private int empId;\n private String firstName;\n private String lastName;\n private List<String> technologies = new ArrayList<>();\n public int getEmpId() {\n return empId;\n }\n public void setEmpId(int empId) {\n this.empId = empId;\n }\n public String getFirstName() {\n return firstName;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n public List<String> getTechnologies() {\n return technologies;\n }\n public void setTechnologies(List<String> technologies) {\n this.technologies = technologies;\n }\n}" }, { "code": null, "e": 3160, "s": 3037, "text": "{\n \"firstName\" : \"Adithya\",\n \"lastName\" : \"Jai\",\n \"technologies\" : [ \"Java\", \"Scala\", \"Python\" ],\n \"empId\" : 125\n}" } ]
When to use the readNBytes() method of InputStream in Java 9?
Since Java 9, the readNBytes() method can be added to the InputStream class. This method reads the requested number of bytes from an input stream into the given byte array. This method blocks until len bytes of input data have read, end of a stream is detected, or an exception is thrown. The readNBytes() method doesn't close an input stream. This method can be useful to avoid memory problems with large files. public int readNBytes(byte[] b, int off, int len) throws IOException In the below example, we have created a "Technology.txt" file in the source folder with simple data: { "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}. import java.io.*; import java.util.stream.*; import java.nio.*; import java.nio.file.*; public class InputStreamReadNByteMethodTest { InputStream inputStream = nputStreamReadNByteMethodTest.class.getResourceAsStream("Technology.txt"); public void testReadNBytes() throws Exception { final byte[] data = new byte[10]; inputStream.readNBytes(data, 0, 7); System.out.println(new String(data)); } public static void main(String args[]) throws Exception { InputStreamReadNByteMethodTest t = new InputStreamReadNByteMethodTest(); t.testReadNBytes(); } } "JAVA",
[ { "code": null, "e": 1475, "s": 1062, "text": "Since Java 9, the readNBytes() method can be added to the InputStream class. This method reads the requested number of bytes from an input stream into the given byte array. This method blocks until len bytes of input data have read, end of a stream is detected, or an exception is thrown. The readNBytes() method doesn't close an input stream. This method can be useful to avoid memory problems with large files." }, { "code": null, "e": 1544, "s": 1475, "text": "public int readNBytes(byte[] b, int off, int len) throws IOException" }, { "code": null, "e": 1701, "s": 1544, "text": "In the below example, we have created a \"Technology.txt\" file in the source folder with simple data: { \"JAVA\", \"PYTHON\", \"JAVASCRIPT\", \"SELENIUM\", \"SCALA\"}." }, { "code": null, "e": 2298, "s": 1701, "text": "import java.io.*;\nimport java.util.stream.*;\nimport java.nio.*;\nimport java.nio.file.*;\n\npublic class InputStreamReadNByteMethodTest {\n InputStream inputStream = nputStreamReadNByteMethodTest.class.getResourceAsStream(\"Technology.txt\");\n\n public void testReadNBytes() throws Exception {\n final byte[] data = new byte[10];\n inputStream.readNBytes(data, 0, 7);\n System.out.println(new String(data));\n }\n public static void main(String args[]) throws Exception {\n InputStreamReadNByteMethodTest t = new InputStreamReadNByteMethodTest();\n t.testReadNBytes(); \n }\n}" }, { "code": null, "e": 2306, "s": 2298, "text": "\"JAVA\"," } ]
How to identify nth element using xpath in Selenium with python?
There are multiple ways of building a customized xpath. In case we need to identify nth element we can achieve this by the ways listed below. position() method in xpath.Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1. position() method in xpath. Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1. Syntax − driver.find_element_by_xpath("//input[@type='text'][position()=1]") square bracket addition with braces to indicate index.Suppose we need to reach the third row of the table and the customized xpath for that row should be indicated with the help of [3] expression. square bracket addition with braces to indicate index. Suppose we need to reach the third row of the table and the customized xpath for that row should be indicated with the help of [3] expression. Syntax − driver.find_element_by_xpath("//table/tbody/tr[2]/td[2]") Code Implementation with position() from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/index.htm") #to refresh the browser driver.refresh() # identifying the edit box with the help of position() driver.find_element_by_xpath("//input[@type='text'][position()=1]"). send_keys("Selenium") #to close the browser driver.close() Code Implementation with index from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm") #to refresh the browser driver.refresh() # printing the first data in the row 2 of table with index print(driver.find_element_by_xpath("//table/tbody/tr[2]/td[1]").text) #to close the browser driver.close()
[ { "code": null, "e": 1204, "s": 1062, "text": "There are multiple ways of building a customized xpath. In case we need to identify nth element we can achieve this by the ways listed below." }, { "code": null, "e": 1372, "s": 1204, "text": "position() method in xpath.Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1." }, { "code": null, "e": 1400, "s": 1372, "text": "position() method in xpath." }, { "code": null, "e": 1541, "s": 1400, "text": "Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1." }, { "code": null, "e": 1550, "s": 1541, "text": "Syntax −" }, { "code": null, "e": 1618, "s": 1550, "text": "driver.find_element_by_xpath(\"//input[@type='text'][position()=1]\")" }, { "code": null, "e": 1815, "s": 1618, "text": "square bracket addition with braces to indicate index.Suppose we need to reach the third row of the table and the customized xpath for that row should be indicated with the help of [3] expression." }, { "code": null, "e": 1870, "s": 1815, "text": "square bracket addition with braces to indicate index." }, { "code": null, "e": 2013, "s": 1870, "text": "Suppose we need to reach the third row of the table and the customized xpath for that row should be indicated with the help of [3] expression." }, { "code": null, "e": 2022, "s": 2013, "text": "Syntax −" }, { "code": null, "e": 2080, "s": 2022, "text": "driver.find_element_by_xpath(\"//table/tbody/tr[2]/td[2]\")" }, { "code": null, "e": 2116, "s": 2080, "text": "Code Implementation with position()" }, { "code": null, "e": 2713, "s": 2116, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the edit box with the help of position()\ndriver.find_element_by_xpath(\"//input[@type='text'][position()=1]\").\nsend_keys(\"Selenium\")\n#to close the browser\ndriver.close()" }, { "code": null, "e": 2744, "s": 2713, "text": "Code Implementation with index" }, { "code": null, "e": 3343, "s": 2744, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm\")\n#to refresh the browser\ndriver.refresh()\n# printing the first data in the row 2 of table with index\nprint(driver.find_element_by_xpath(\"//table/tbody/tr[2]/td[1]\").text)\n#to close the browser\ndriver.close()" } ]
Python - Maximum of each Column - GeeksforGeeks
30 Jan, 2020 Sometimes, we are encountered with such problem in which we need to find the maximum of each column in a matrix i.e maximum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using max() + list comprehension + zip()The combination of above methods are required to solve this particular problem. The max function is used to get the required maximum value and zip function provides the combination of like indices and then list is created using list comprehension. # Python3 code to demonstrate# Maximum of each Column# using max() + list comprehension + zip() # initializing listtest_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]] # printing original listprint("The original list : " + str(test_list)) # using max() + list comprehension + zip()# Maximum of each Columnres = [max(idx) for idx in zip(*test_list)] # print resultprint("The Maximum of each index list is : " + str(res)) The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]] The Maximum of each index list is : [9, 7, 6] Method #2 : Using map() + max() + zip()This works in almost similar way as the above method, but the difference is just that we use map function to build the max element list rather than using list comprehension. # Python3 code to demonstrate# Maximum index value# using max() + map() + zip() # initializing listtest_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]] # printing original listprint("The original list : " + str(test_list)) # using max() + map() + zip()# Maximum index valueres = list(map(max, zip(*test_list))) # print resultprint("The Maximum of each index list is : " + str(res)) The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]] The Maximum of each index list is : [9, 7, 6] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python Defaultdict in Python Python program to convert a list to string Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25020, "s": 24992, "text": "\n30 Jan, 2020" }, { "code": null, "e": 25316, "s": 25020, "text": "Sometimes, we are encountered with such problem in which we need to find the maximum of each column in a matrix i.e maximum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 25616, "s": 25316, "text": "Method #1 : Using max() + list comprehension + zip()The combination of above methods are required to solve this particular problem. The max function is used to get the required maximum value and zip function provides the combination of like indices and then list is created using list comprehension." }, { "code": "# Python3 code to demonstrate# Maximum of each Column# using max() + list comprehension + zip() # initializing listtest_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]] # printing original listprint(\"The original list : \" + str(test_list)) # using max() + list comprehension + zip()# Maximum of each Columnres = [max(idx) for idx in zip(*test_list)] # print resultprint(\"The Maximum of each index list is : \" + str(res))", "e": 26033, "s": 25616, "text": null }, { "code": null, "e": 26134, "s": 26033, "text": "The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]\nThe Maximum of each index list is : [9, 7, 6]\n" }, { "code": null, "e": 26349, "s": 26136, "text": "Method #2 : Using map() + max() + zip()This works in almost similar way as the above method, but the difference is just that we use map function to build the max element list rather than using list comprehension." }, { "code": "# Python3 code to demonstrate# Maximum index value# using max() + map() + zip() # initializing listtest_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]] # printing original listprint(\"The original list : \" + str(test_list)) # using max() + map() + zip()# Maximum index valueres = list(map(max, zip(*test_list))) # print resultprint(\"The Maximum of each index list is : \" + str(res))", "e": 26728, "s": 26349, "text": null }, { "code": null, "e": 26829, "s": 26728, "text": "The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]\nThe Maximum of each index list is : [9, 7, 6]\n" }, { "code": null, "e": 26850, "s": 26829, "text": "Python list-programs" }, { "code": null, "e": 26857, "s": 26850, "text": "Python" }, { "code": null, "e": 26873, "s": 26857, "text": "Python Programs" }, { "code": null, "e": 26971, "s": 26873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26989, "s": 26971, "text": "Python Dictionary" }, { "code": null, "e": 27024, "s": 26989, "text": "Read a file line by line in Python" }, { "code": null, "e": 27056, "s": 27024, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27098, "s": 27056, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27120, "s": 27098, "text": "Enumerate() in Python" }, { "code": null, "e": 27142, "s": 27120, "text": "Defaultdict in Python" }, { "code": null, "e": 27185, "s": 27142, "text": "Python program to convert a list to string" }, { "code": null, "e": 27224, "s": 27185, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27270, "s": 27224, "text": "Python | Split string into list of characters" } ]
What are Enumerated Constants in C++?
An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration. These are also called as enumerated constants. For example, if you are creating an application that has a fixed number of types for some variable. For example, let's say gender, it can be of three types male, female and others. You can define and use an enum like − #include<iostream> using namespace std; enum Gender {MALE, FEMALE, OTHERS}; int main() { Gender gen = Gender.FEMALE; return 0; } By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But these values don't matter because enums are basically used to have a symbolic meaning. Whenever you compare an enum in your program, you'd be just using its symbolic meaning and not its actual value.
[ { "code": null, "e": 1298, "s": 1062, "text": "An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the enumeration. These are also called as enumerated constants." }, { "code": null, "e": 1517, "s": 1298, "text": "For example, if you are creating an application that has a fixed number of types for some variable. For example, let's say gender, it can be of three types male, female and others. You can define and use an enum like −" }, { "code": null, "e": 1652, "s": 1517, "text": "#include<iostream>\nusing namespace std;\nenum Gender {MALE, FEMALE, OTHERS};\nint main() {\n Gender gen = Gender.FEMALE;\n return 0;\n}" }, { "code": null, "e": 1977, "s": 1652, "text": "By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But these values don't matter because enums are basically used to have a symbolic meaning. Whenever you compare an enum in your program, you'd be just using its symbolic meaning and not its actual value." } ]
Difference between multiple arguments and options object - GeeksforGeeks
28 Dec, 2021 Multiple Arguments: The arguments object is an array-like object that represents the passed arguments when invoking a function. This array-like object does not have the array prototype chain, hence it cannot use any of the array methods. It has length property but it does not have array’s built-in methods like forEach() and map() method.Features: Arguments in Javascript are Passed by Value. This function only gets to know the values, not the arguments locations. Arguments.length In Javascript Depends on Invocation Arguments, Not Function Signatures. You can use arguments.length to determine how many arguments were passed-in during the given function invocation. Code readability is maximum. Usage: arguments.callee: Reference to the currently executing function that the arguments belong to. arguments.length: The number of arguments that were passed to the function. arguments.caller: Reference to the function that invoked the currently executing function. arguments[@@iterator]: Returns a new Array Iterator object that contains the value for each index in arguments. Example: This is an example of multiple arguments in javascript. Actually arguments is not like an arrays, It does not follow the array properties except Length. we can use all types of inputs into the function as multiple arguments. Within the function, we can pass multiple arguments but it is difficult to pass named arguments as multiple arguments. Program: javascript <script>// Example of arguments of two// number a and b.function args(){ // Using for loop // It can use length method for(var i = 0; i < arguments.length; i++) { console.log(arguments[i]); }} args(1, 3);</script> Output: 1 2 Options Object: Options object are a common pattern for passing named arguments into the function. When a function has two or more parameters then we can use the options object. For a function with four or more parameters then the options object is a good choice. A function has one or two-parameter and we want to add more parameters in the future so instead of rewriting the code later we can use options object.The options object is different from multiple arguments because multiple arguments can take multi-type of arguments e.g. int, float, char, string...etc while options object can take named arguments like AlertIcon, etc only.Features: This function can take up to 34 parameters, all of which are optional. Using the ‘options as an object’ approach is going to be best. You don’t have to worry about the order of the properties. Usage: If you have more than four-parameter. At least one parameter is optional. Feel complex to figure out what parameter function takes. Example: Program: html <!DOCTYPE html><html> <head> <title>Option object</title> <script type="text/javascript"> var courses = ['HTML', 'CSS', 'JavaScript', 'Bootstrap']; function courselist() { var countryList = document.getElementById ("course"); for (var i = 0; i < courses.length; i += 1) { // Option (text, value) var courseOption = new Option (courses[i], courses[i+1]); countryList.options.add (courseOption); } } </script></head> <body onload="courselist()"> <select id="course"></select></body> </html> Output: A dropdown menu of available courses Differences between multiple Arguments and Options Object: sagar0719kumar surindertarika1234 JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to detect browser or tab closing in JavaScript ? How to get selected value in dropdown list using JavaScript ? 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": 25300, "s": 25272, "text": "\n28 Dec, 2021" }, { "code": null, "e": 25651, "s": 25300, "text": "Multiple Arguments: The arguments object is an array-like object that represents the passed arguments when invoking a function. This array-like object does not have the array prototype chain, hence it cannot use any of the array methods. It has length property but it does not have array’s built-in methods like forEach() and map() method.Features: " }, { "code": null, "e": 25769, "s": 25651, "text": "Arguments in Javascript are Passed by Value. This function only gets to know the values, not the arguments locations." }, { "code": null, "e": 25858, "s": 25769, "text": "Arguments.length In Javascript Depends on Invocation Arguments, Not Function Signatures." }, { "code": null, "e": 25972, "s": 25858, "text": "You can use arguments.length to determine how many arguments were passed-in during the given function invocation." }, { "code": null, "e": 26001, "s": 25972, "text": "Code readability is maximum." }, { "code": null, "e": 26010, "s": 26001, "text": "Usage: " }, { "code": null, "e": 26104, "s": 26010, "text": "arguments.callee: Reference to the currently executing function that the arguments belong to." }, { "code": null, "e": 26180, "s": 26104, "text": "arguments.length: The number of arguments that were passed to the function." }, { "code": null, "e": 26271, "s": 26180, "text": "arguments.caller: Reference to the function that invoked the currently executing function." }, { "code": null, "e": 26383, "s": 26271, "text": "arguments[@@iterator]: Returns a new Array Iterator object that contains the value for each index in arguments." }, { "code": null, "e": 26738, "s": 26383, "text": "Example: This is an example of multiple arguments in javascript. Actually arguments is not like an arrays, It does not follow the array properties except Length. we can use all types of inputs into the function as multiple arguments. Within the function, we can pass multiple arguments but it is difficult to pass named arguments as multiple arguments. " }, { "code": null, "e": 26749, "s": 26738, "text": "Program: " }, { "code": null, "e": 26760, "s": 26749, "text": "javascript" }, { "code": "<script>// Example of arguments of two// number a and b.function args(){ // Using for loop // It can use length method for(var i = 0; i < arguments.length; i++) { console.log(arguments[i]); }} args(1, 3);</script>", "e": 27000, "s": 26760, "text": null }, { "code": null, "e": 27010, "s": 27000, "text": "Output: " }, { "code": null, "e": 27014, "s": 27010, "text": "1\n2" }, { "code": null, "e": 27663, "s": 27014, "text": "Options Object: Options object are a common pattern for passing named arguments into the function. When a function has two or more parameters then we can use the options object. For a function with four or more parameters then the options object is a good choice. A function has one or two-parameter and we want to add more parameters in the future so instead of rewriting the code later we can use options object.The options object is different from multiple arguments because multiple arguments can take multi-type of arguments e.g. int, float, char, string...etc while options object can take named arguments like AlertIcon, etc only.Features: " }, { "code": null, "e": 27734, "s": 27663, "text": "This function can take up to 34 parameters, all of which are optional." }, { "code": null, "e": 27856, "s": 27734, "text": "Using the ‘options as an object’ approach is going to be best. You don’t have to worry about the order of the properties." }, { "code": null, "e": 27865, "s": 27856, "text": "Usage: " }, { "code": null, "e": 27903, "s": 27865, "text": "If you have more than four-parameter." }, { "code": null, "e": 27939, "s": 27903, "text": "At least one parameter is optional." }, { "code": null, "e": 27997, "s": 27939, "text": "Feel complex to figure out what parameter function takes." }, { "code": null, "e": 28008, "s": 27997, "text": "Example: " }, { "code": null, "e": 28019, "s": 28008, "text": "Program: " }, { "code": null, "e": 28024, "s": 28019, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Option object</title> <script type=\"text/javascript\"> var courses = ['HTML', 'CSS', 'JavaScript', 'Bootstrap']; function courselist() { var countryList = document.getElementById (\"course\"); for (var i = 0; i < courses.length; i += 1) { // Option (text, value) var courseOption = new Option (courses[i], courses[i+1]); countryList.options.add (courseOption); } } </script></head> <body onload=\"courselist()\"> <select id=\"course\"></select></body> </html> ", "e": 28720, "s": 28024, "text": null }, { "code": null, "e": 28730, "s": 28720, "text": "Output: " }, { "code": null, "e": 28767, "s": 28730, "text": "A dropdown menu of available courses" }, { "code": null, "e": 28827, "s": 28767, "text": "Differences between multiple Arguments and Options Object: " }, { "code": null, "e": 28842, "s": 28827, "text": "sagar0719kumar" }, { "code": null, "e": 28861, "s": 28842, "text": "surindertarika1234" }, { "code": null, "e": 28877, "s": 28861, "text": "JavaScript-Misc" }, { "code": null, "e": 28884, "s": 28877, "text": "Picked" }, { "code": null, "e": 28895, "s": 28884, "text": "JavaScript" }, { "code": null, "e": 28912, "s": 28895, "text": "Web Technologies" }, { "code": null, "e": 28939, "s": 28912, "text": "Web technologies Questions" }, { "code": null, "e": 29037, "s": 28939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29046, "s": 29037, "text": "Comments" }, { "code": null, "e": 29059, "s": 29046, "text": "Old Comments" }, { "code": null, "e": 29120, "s": 29059, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29161, "s": 29120, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29215, "s": 29161, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29268, "s": 29215, "text": "How to detect browser or tab closing in JavaScript ?" }, { "code": null, "e": 29330, "s": 29268, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 29372, "s": 29330, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29405, "s": 29372, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29467, "s": 29405, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29510, "s": 29467, "text": "How to fetch data from an API in ReactJS ?" } ]
Classifying Ships in Satellite Imagery with Neural Networks | by Andrew Udell | Towards Data Science
Nothing tells of the ubiquity of satellite imagery like Google Maps. A completely unpaid service provides anyone with internet access a entire planet’s worth of satellite imagery. While Google Maps is free, other paid alternatives exist which take photos of the earth’s surface on a more frequent basis for commercial use. World governments also utilize their satellites for many domestic uses. As the availability of satellite imagery outpaces the ability of humans to look through them manually, an automated means to classify them must be developed. Classification of images is a fundamental problem in computer vision and neural networks provide an interesting solution. Available on Kaggle, the Ships in Satellite Imagery dataset contains 4000 annotated images of ships and non-ships. Taken from the Planet API, the 1000 ship images are uniformly 80px x 80px and contain a ship in various orientations, but always near centered. Of the 3000 non-ship images, about 1000 depict random features, such as the ocean or a building, about a 1000 depict a partial, but not complete, image of a ship, and the last 1000 depict images which have been mislabeled by other machine learning models. The accompanying JSON file includes an image’s ID and a notation of whether or not the image contains a ship, as designated by a 1 or 0, accordingly. In addition, it contains the actual pixel values for each image. Arranged as 19,200 integer values, the first third contain all pixel values in the red channel, followed by pixel values in the green channel, and the final third in the blue channel. Since the pixel values are explicitly stated in the dataset, the actual images themselves don’t technically need to be downloaded, but they are a nice reference. To classify these images, a convolutional neural network (CNN) will be trained. As a type of artificial neural network, CNN’s mimic the neurons in the brain, particularly those used for vision. Each neuron in the network develops a unique feature map which can identify a feature in an image. In shallow networks, a feature map might recognize a vertical or horizonal line. As layers are added to the network, however, feature maps may recognize more complex structures, such as an eye or, in this case, a ship. Various libraries exist to write CNN’s, but this tutorial will cover TensorFlow with Keras. import tensorflow as tfimport pandas as pdimport numpy as np Before training anything, basic imports are used. TensorFlow is a machine learning library that places a large focus on neural networks. Pandas is a spreadsheet-type library to help parse data. Finally, NumPy helps crunch numbers quickly and efficiently. # Read the datadf = pd.read_json("shipsnet.json") This line simply imports the JSON file and reads it as a data frame. # Normalize and reshape the image datadf["normalized_data"] = df["data"].apply(lambda x: (np.array(x) / 255).reshape(80, 80, 3)) The pixel values are stored in a column in the data frame titled “data.” As is, these pixel values aren’t ready to be processed by a CNN. Instead, the new data is converted to a NumPy array and divided by 255 to normalize the values. All 19,200 values should now be some value between 0 and 1. Next the data is reshaped to 80 x 80 x 3 matrix so that it’s formatted as a picture. # Define X and YX = df["normalized_data"]Y = df["labels"]# Split the data into training and testing sets. Use a 75/25 splitfrom sklearn.model_selection import train_test_split(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, test_size=0.25, random_state=42) The X and Y values are defined. Y is predictably the column titled “labels” and contains the array of 1’s and 0’s to define whether an image contains a ship. The X is the normalized image data abstracted from the pixel values. With X and Y defined, they are split into training and testing sets along a 75/25 split. As a result, the model will train on 3000 images and validate its results on 1000 other images. # Transform the training and testing data into arraysX_train = np.array([x for x in X_train])X_test = np.array([x for x in X_test])Y_train = np.array([y for y in Y_train])Y_test = np.array([y for y in Y_test]) Unfortunately, Pandas Series aren’t accepted in TensorFlow, so the training and testing data are converted into arrays. from tensorflow.keras import datasets, layers, modelsfrom tensorflow.keras.layers import Activation# Starts the model with a sequential ANNmodel = models.Sequential() After a couple of imports, the actual CNN is ready to be built. The CNN is initialized as a sequential model, which ensures each layer receives one input and one output. # Adds the first convulsion layer and follows up with max poolingmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(80, 80, 3)))model.add(layers.MaxPooling2D((2, 2))) The first two layers are added to the model. The first layer is a convolution layer which uses a “ReLu” activation function and expects an input tensor of 80 x 80 x 3, the exact dimensions of the training images. The 32 represents the dimensionality of the output of the layer and the (3, 3) represents the size of the convolution window, 3px x 3px in this case. The next layer added is for max pooling, which takes a pool size of 2 x 2. # Add additional hidden layersmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(64, (3, 3), activation='relu')) Much like the previous bit of code, these two lines additional hidden layers to the network. While output size has changed, these layers follow the same basic pattern as the first two. # Flattens the input into a 1D tensormodel.add(layers.Flatten())# Makes the input more readable for classificationmodel.add(layers.Dense(64, activation='relu'))# Classifies - ensure the input in the number of classes, indexed# at 0model.add(layers.Dense(1))# Final activation functionmodel.add(Activation('sigmoid')) The first line simply flattens the tensor into a 1 dimension, which will make processing easier. The next line, the first dense layer, formats the resulting input. The next dense layer concerns itself with classification. As a result, the only argument passed is the number of classes, indexed at 0. Since there are two classes in this example, either ship or not-ship, 1 is passed. Finally an activation layer is added which tells the whether or not to fire the neuron. model.summary() Before moving forward, take the time to review the model using the summary method. The output should look like this: Note how each line describes a layer built into the CNN, as well as its output shape, and number of parameters. # Compile the model# Use binary_crossentropy because there are only 2 classes presentmodel.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) This line simply compiles the model. If there were issues with input/output dimensionality while adding layers, the program will let you know at this step. The loss function is taken as binary crossentropy, since the model uses only two classes. Using more classes would require something different. A full list of loss functions may be reviewed here. The optimizer is taken as the RMS prop algorithm, but others are available here. The metrics argument simply looks at what needs to be optimized, which in this case is simply accuracy. # Train the modelgen_model = model.fit(X_train, Y_train, epochs=10, validation_data=(X_test, Y_test)) It’s finally time to fit the model. Passing the training and testing data is straightforward. The epochs argument essentially tells the model how many iterations to go through. There’s a diminishing margin of return for setting epochs. A higher number will generally return a better accuracy, but each additional gain in accuracy will decrease until it approaches the maximum amount of accuracy the dataset can produce. Additionally, more epochs will take longer to run. For this dataset, 10 will return good results. When the model trains, output will be given that looks like the below for each epoch: After returning the number of samples and giving the time to train the epoch, the line will also return the loss and accuracy of the model on its own training set of images as well as its loss and accuracy for the validation set. In this case, on the 10th epoch, the model achieved 99.27% accuracy on its own training images and 98.5% accuracy on images the model had never seen before. Before celebrating too much, a deeper analysis of the results should be taken. # Evaluate the modelfrom sklearn.metrics import classification_report, confusion_matrixpredictions = model.predict(X_test)print(classification_report(Y_test, predictions.round()))print(confusion_matrix(Y_test, predictions.round())) These lines import a few functions to help evaluate the accuracy of the model, apply the model to the testing data, and print a classification report and a confusion matrix. The classification report: The testing data was composed of 1000 images, 733 of which were non-ships and 267 were ships. A precision of 99% for the non-ships is slightly higher than the 97% for the ships. Essentially, for all the images the model classified as ships, 97% were actual ships. The model was able to recall 99% of the non-ship images and 98% of the non-ship images, respectfully. Overall, these are great results for a simple CNN. Now, looking at the confusion matrix: Of the 733 non-ship images, 725 were correctly identified and 8 were mislabeled as a ship. These are the false positives. Of the 267 ship images, 262 were correctly identified and 5 were mislabeled as a non-ship. These are the false negatives. A CNN probably wouldn’t be very useful if needed to be trained every time it was needed. In this case, the training time only took a few minutes, but on deeper networks with more epochs, training can take hours or even days. Consequently, there’s a simple method to call to save the whole model. # Save the model for later usemodel.save("ShipCNN.h5") The save method simply takes the name of the path to save it as a H5 file. # Load a modelnew_model = tf.keras.models.load_model("model.h5") Loading a pre-saved file is also fairly simple. It’s also a good a good idea to call the summary method to check that the model’s architecture matches to expectation. Using satellite imagery to train a CNN provided the perfect dataset. All images were of the same size, taken at essentially the same angle and distance, and every ship retained a top-down view. While changing any of these parameters would make the problem of classification more difficult, the ship images demonstrated the power of neural networks applied to computer vision problems. The CNN used was relatively simple, but still returned a high accuracy for only a few minutes of training. Approaching a human-level of performance, only 13 of 1000 images were incorrectly labeled. While the application was idealized, the potential is plainly obvious.
[ { "code": null, "e": 567, "s": 172, "text": "Nothing tells of the ubiquity of satellite imagery like Google Maps. A completely unpaid service provides anyone with internet access a entire planet’s worth of satellite imagery. While Google Maps is free, other paid alternatives exist which take photos of the earth’s surface on a more frequent basis for commercial use. World governments also utilize their satellites for many domestic uses." }, { "code": null, "e": 847, "s": 567, "text": "As the availability of satellite imagery outpaces the ability of humans to look through them manually, an automated means to classify them must be developed. Classification of images is a fundamental problem in computer vision and neural networks provide an interesting solution." }, { "code": null, "e": 1106, "s": 847, "text": "Available on Kaggle, the Ships in Satellite Imagery dataset contains 4000 annotated images of ships and non-ships. Taken from the Planet API, the 1000 ship images are uniformly 80px x 80px and contain a ship in various orientations, but always near centered." }, { "code": null, "e": 1362, "s": 1106, "text": "Of the 3000 non-ship images, about 1000 depict random features, such as the ocean or a building, about a 1000 depict a partial, but not complete, image of a ship, and the last 1000 depict images which have been mislabeled by other machine learning models." }, { "code": null, "e": 1577, "s": 1362, "text": "The accompanying JSON file includes an image’s ID and a notation of whether or not the image contains a ship, as designated by a 1 or 0, accordingly. In addition, it contains the actual pixel values for each image." }, { "code": null, "e": 1923, "s": 1577, "text": "Arranged as 19,200 integer values, the first third contain all pixel values in the red channel, followed by pixel values in the green channel, and the final third in the blue channel. Since the pixel values are explicitly stated in the dataset, the actual images themselves don’t technically need to be downloaded, but they are a nice reference." }, { "code": null, "e": 2435, "s": 1923, "text": "To classify these images, a convolutional neural network (CNN) will be trained. As a type of artificial neural network, CNN’s mimic the neurons in the brain, particularly those used for vision. Each neuron in the network develops a unique feature map which can identify a feature in an image. In shallow networks, a feature map might recognize a vertical or horizonal line. As layers are added to the network, however, feature maps may recognize more complex structures, such as an eye or, in this case, a ship." }, { "code": null, "e": 2527, "s": 2435, "text": "Various libraries exist to write CNN’s, but this tutorial will cover TensorFlow with Keras." }, { "code": null, "e": 2588, "s": 2527, "text": "import tensorflow as tfimport pandas as pdimport numpy as np" }, { "code": null, "e": 2843, "s": 2588, "text": "Before training anything, basic imports are used. TensorFlow is a machine learning library that places a large focus on neural networks. Pandas is a spreadsheet-type library to help parse data. Finally, NumPy helps crunch numbers quickly and efficiently." }, { "code": null, "e": 2893, "s": 2843, "text": "# Read the datadf = pd.read_json(\"shipsnet.json\")" }, { "code": null, "e": 2962, "s": 2893, "text": "This line simply imports the JSON file and reads it as a data frame." }, { "code": null, "e": 3091, "s": 2962, "text": "# Normalize and reshape the image datadf[\"normalized_data\"] = df[\"data\"].apply(lambda x: (np.array(x) / 255).reshape(80, 80, 3))" }, { "code": null, "e": 3470, "s": 3091, "text": "The pixel values are stored in a column in the data frame titled “data.” As is, these pixel values aren’t ready to be processed by a CNN. Instead, the new data is converted to a NumPy array and divided by 255 to normalize the values. All 19,200 values should now be some value between 0 and 1. Next the data is reshaped to 80 x 80 x 3 matrix so that it’s formatted as a picture." }, { "code": null, "e": 3738, "s": 3470, "text": "# Define X and YX = df[\"normalized_data\"]Y = df[\"labels\"]# Split the data into training and testing sets. Use a 75/25 splitfrom sklearn.model_selection import train_test_split(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, test_size=0.25, random_state=42)" }, { "code": null, "e": 3965, "s": 3738, "text": "The X and Y values are defined. Y is predictably the column titled “labels” and contains the array of 1’s and 0’s to define whether an image contains a ship. The X is the normalized image data abstracted from the pixel values." }, { "code": null, "e": 4150, "s": 3965, "text": "With X and Y defined, they are split into training and testing sets along a 75/25 split. As a result, the model will train on 3000 images and validate its results on 1000 other images." }, { "code": null, "e": 4360, "s": 4150, "text": "# Transform the training and testing data into arraysX_train = np.array([x for x in X_train])X_test = np.array([x for x in X_test])Y_train = np.array([y for y in Y_train])Y_test = np.array([y for y in Y_test])" }, { "code": null, "e": 4480, "s": 4360, "text": "Unfortunately, Pandas Series aren’t accepted in TensorFlow, so the training and testing data are converted into arrays." }, { "code": null, "e": 4647, "s": 4480, "text": "from tensorflow.keras import datasets, layers, modelsfrom tensorflow.keras.layers import Activation# Starts the model with a sequential ANNmodel = models.Sequential()" }, { "code": null, "e": 4817, "s": 4647, "text": "After a couple of imports, the actual CNN is ready to be built. The CNN is initialized as a sequential model, which ensures each layer receives one input and one output." }, { "code": null, "e": 5001, "s": 4817, "text": "# Adds the first convulsion layer and follows up with max poolingmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(80, 80, 3)))model.add(layers.MaxPooling2D((2, 2)))" }, { "code": null, "e": 5364, "s": 5001, "text": "The first two layers are added to the model. The first layer is a convolution layer which uses a “ReLu” activation function and expects an input tensor of 80 x 80 x 3, the exact dimensions of the training images. The 32 represents the dimensionality of the output of the layer and the (3, 3) represents the size of the convolution window, 3px x 3px in this case." }, { "code": null, "e": 5439, "s": 5364, "text": "The next layer added is for max pooling, which takes a pool size of 2 x 2." }, { "code": null, "e": 5618, "s": 5439, "text": "# Add additional hidden layersmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(64, (3, 3), activation='relu'))" }, { "code": null, "e": 5803, "s": 5618, "text": "Much like the previous bit of code, these two lines additional hidden layers to the network. While output size has changed, these layers follow the same basic pattern as the first two." }, { "code": null, "e": 6120, "s": 5803, "text": "# Flattens the input into a 1D tensormodel.add(layers.Flatten())# Makes the input more readable for classificationmodel.add(layers.Dense(64, activation='relu'))# Classifies - ensure the input in the number of classes, indexed# at 0model.add(layers.Dense(1))# Final activation functionmodel.add(Activation('sigmoid'))" }, { "code": null, "e": 6284, "s": 6120, "text": "The first line simply flattens the tensor into a 1 dimension, which will make processing easier. The next line, the first dense layer, formats the resulting input." }, { "code": null, "e": 6503, "s": 6284, "text": "The next dense layer concerns itself with classification. As a result, the only argument passed is the number of classes, indexed at 0. Since there are two classes in this example, either ship or not-ship, 1 is passed." }, { "code": null, "e": 6591, "s": 6503, "text": "Finally an activation layer is added which tells the whether or not to fire the neuron." }, { "code": null, "e": 6607, "s": 6591, "text": "model.summary()" }, { "code": null, "e": 6724, "s": 6607, "text": "Before moving forward, take the time to review the model using the summary method. The output should look like this:" }, { "code": null, "e": 6836, "s": 6724, "text": "Note how each line describes a layer built into the CNN, as well as its output shape, and number of parameters." }, { "code": null, "e": 7006, "s": 6836, "text": "# Compile the model# Use binary_crossentropy because there are only 2 classes presentmodel.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])" }, { "code": null, "e": 7162, "s": 7006, "text": "This line simply compiles the model. If there were issues with input/output dimensionality while adding layers, the program will let you know at this step." }, { "code": null, "e": 7543, "s": 7162, "text": "The loss function is taken as binary crossentropy, since the model uses only two classes. Using more classes would require something different. A full list of loss functions may be reviewed here. The optimizer is taken as the RMS prop algorithm, but others are available here. The metrics argument simply looks at what needs to be optimized, which in this case is simply accuracy." }, { "code": null, "e": 7645, "s": 7543, "text": "# Train the modelgen_model = model.fit(X_train, Y_train, epochs=10, validation_data=(X_test, Y_test))" }, { "code": null, "e": 7822, "s": 7645, "text": "It’s finally time to fit the model. Passing the training and testing data is straightforward. The epochs argument essentially tells the model how many iterations to go through." }, { "code": null, "e": 8163, "s": 7822, "text": "There’s a diminishing margin of return for setting epochs. A higher number will generally return a better accuracy, but each additional gain in accuracy will decrease until it approaches the maximum amount of accuracy the dataset can produce. Additionally, more epochs will take longer to run. For this dataset, 10 will return good results." }, { "code": null, "e": 8249, "s": 8163, "text": "When the model trains, output will be given that looks like the below for each epoch:" }, { "code": null, "e": 8479, "s": 8249, "text": "After returning the number of samples and giving the time to train the epoch, the line will also return the loss and accuracy of the model on its own training set of images as well as its loss and accuracy for the validation set." }, { "code": null, "e": 8636, "s": 8479, "text": "In this case, on the 10th epoch, the model achieved 99.27% accuracy on its own training images and 98.5% accuracy on images the model had never seen before." }, { "code": null, "e": 8715, "s": 8636, "text": "Before celebrating too much, a deeper analysis of the results should be taken." }, { "code": null, "e": 8947, "s": 8715, "text": "# Evaluate the modelfrom sklearn.metrics import classification_report, confusion_matrixpredictions = model.predict(X_test)print(classification_report(Y_test, predictions.round()))print(confusion_matrix(Y_test, predictions.round()))" }, { "code": null, "e": 9121, "s": 8947, "text": "These lines import a few functions to help evaluate the accuracy of the model, apply the model to the testing data, and print a classification report and a confusion matrix." }, { "code": null, "e": 9148, "s": 9121, "text": "The classification report:" }, { "code": null, "e": 9514, "s": 9148, "text": "The testing data was composed of 1000 images, 733 of which were non-ships and 267 were ships. A precision of 99% for the non-ships is slightly higher than the 97% for the ships. Essentially, for all the images the model classified as ships, 97% were actual ships. The model was able to recall 99% of the non-ship images and 98% of the non-ship images, respectfully." }, { "code": null, "e": 9565, "s": 9514, "text": "Overall, these are great results for a simple CNN." }, { "code": null, "e": 9603, "s": 9565, "text": "Now, looking at the confusion matrix:" }, { "code": null, "e": 9725, "s": 9603, "text": "Of the 733 non-ship images, 725 were correctly identified and 8 were mislabeled as a ship. These are the false positives." }, { "code": null, "e": 9847, "s": 9725, "text": "Of the 267 ship images, 262 were correctly identified and 5 were mislabeled as a non-ship. These are the false negatives." }, { "code": null, "e": 10143, "s": 9847, "text": "A CNN probably wouldn’t be very useful if needed to be trained every time it was needed. In this case, the training time only took a few minutes, but on deeper networks with more epochs, training can take hours or even days. Consequently, there’s a simple method to call to save the whole model." }, { "code": null, "e": 10198, "s": 10143, "text": "# Save the model for later usemodel.save(\"ShipCNN.h5\")" }, { "code": null, "e": 10273, "s": 10198, "text": "The save method simply takes the name of the path to save it as a H5 file." }, { "code": null, "e": 10338, "s": 10273, "text": "# Load a modelnew_model = tf.keras.models.load_model(\"model.h5\")" }, { "code": null, "e": 10505, "s": 10338, "text": "Loading a pre-saved file is also fairly simple. It’s also a good a good idea to call the summary method to check that the model’s architecture matches to expectation." }, { "code": null, "e": 10890, "s": 10505, "text": "Using satellite imagery to train a CNN provided the perfect dataset. All images were of the same size, taken at essentially the same angle and distance, and every ship retained a top-down view. While changing any of these parameters would make the problem of classification more difficult, the ship images demonstrated the power of neural networks applied to computer vision problems." } ]
BlackWidow - Web Application Spider - GeeksforGeeks
23 Aug, 2021 Gathering Information about the target domain is very important for making the penetration testing or bug bounty hunting process successful. Collecting Subdomains, Unique URLs, URLs with Parameters, Emails of the target domain, etc information is very crucial, so to get this Information we have a tool named BlackWidow. BlackWidow tool is a python language-based tool used for web-based application spider and gathers lots of information. Inject-X fuzzer is used in this tool for scanning Dynamic URLs for common OWASP vulnerabilities. BlackWidow tool can be used in the initial steps of web-based application vulnerability assessment for the Information Gathering phase. Inject-X fuzzer has the capability to detect XSS, SWL Injection, HTML code injection, etc. vulnerabilities. It gathers subdomains, unique dynamic URLs, emails, phone numbers.It uses an Inject-X fuzzer for the detection of vulnerability.It can store the results in dedicated text files in sorted order.It is developed in Python Language.It is open-source and free to use. It gathers subdomains, unique dynamic URLs, emails, phone numbers. It uses an Inject-X fuzzer for the detection of vulnerability. It can store the results in dedicated text files in sorted order. It is developed in Python Language. It is open-source and free to use. Step 1: Check whether Python Environment is Established or not, use the following command: python3 Step 2: Open up your Kali Linux terminal and move to Desktop using the following command. cd Desktop Step 3: You are on Desktop now create a new directory called Black-Widow using the following command. In this directory, we will complete the installation of the Black-Widow tool. mkdir Black-Widow Step 4: Now switch to the Black-Widow directory using the following command. cd Black-Widow Step 5: Now you have to install the tool. You have to clone the tool from Github. sudo git clone https://github.com/1N3/BlackWidow.git Step 6: The tool has been downloaded successfully in the Black-Widow directory. Now list out the contents of the tool by using the below command. ls Step 7: You can observe that there is a new directory created of the BlackWidow tool that has been generated while we were installing the tool. Now move to that directory using the below command: cd BlackWidow Step 8: Once again to discover the contents of the tool, use the below command. ls Step 9: Download the required packages for running the tool, use the following command. sudo pip3 install -r requirements.txt Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of tool) index of the tool. python3 blackwidow -h In this example, we will be performing Full URL Spider. We have provided the target Full URL using the -u tag (https://geeksforgeeks.org) sudo python3 blackwidow -u https://geeksforgeeks.org In the below Screenshot, we are getting our scan results, Subdomains of geeksforgeeks.org are displayed in the below Screenshot. In the below Screenshot, dynamic URLs found on geeksforgeeks.org are mentioned below in the screenshot, Basically, these are parameterized URLs that can be tested for XSS and many more vulnerabilities. In the below screenshot, the files created by the tool while scanning is shown. Each file has its own results like subdomains, emails, URLs, etc. In the below Screenshot, You can see that Emails of geeksforgeeks.org are saved in the emails.txt file, this makes the task easier. In this example, rather than providing a full URL (like Example 1), we are specifying only domain names to scan. -d tag is used along with the target domain name. sudo python3 blackwidow -d geeksforgeeks.org Domain name to spider In the below Screenshot, we have got the results of our Domain name Spider. In this example, we will scan the domain to a certain depth. 5 levels of depth will be scanned as we have specified a depth of 5 using the -l tag. sudo python3 blackwidow -d geeksforgeeks.org -l 5 In the below Screenshot, the results of the depth of 5 are displayed. In this example, We will scan for all the dynamic URLs detected on the geeksforgeeks.org domain. In the below Screenshot, the list of unique_dynaminc URLs list is displayed. sudo python3 blackwidow -d geeksforgeeks.org -s /usr/share/blackwidow/geeksforgeeks.org_80/geeksforgeeks.org_80-dynamic-unique.txt In the below Screenshot, we are starting our Scan on dynamic URLs which are provided in the form of list. In the below screenshot, you can see that the results of the above scan are displayed. In this example, we will perform a scan on the domain specified with the port number. We have specified Port 80, so only Port 80 URLs will be scanned. sudo python3 blackwidow -d geeksforgeeks.org -p 80 In the below Screenshot, we have got the results of our above Example Port of the URL. In this example, we will be displayed in a more verbose format. -v tag is used along with the confirmation (y/n). sudo python3 blackwidow -d geeksforgeeks.org -v y In the below Screenshot, the results of verbose format are displayed. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples Thread functions in C/C++ scp command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting Named Pipe or FIFO with example C program
[ { "code": null, "e": 24406, "s": 24378, "text": "\n23 Aug, 2021" }, { "code": null, "e": 24727, "s": 24406, "text": "Gathering Information about the target domain is very important for making the penetration testing or bug bounty hunting process successful. Collecting Subdomains, Unique URLs, URLs with Parameters, Emails of the target domain, etc information is very crucial, so to get this Information we have a tool named BlackWidow." }, { "code": null, "e": 25187, "s": 24727, "text": "BlackWidow tool is a python language-based tool used for web-based application spider and gathers lots of information. Inject-X fuzzer is used in this tool for scanning Dynamic URLs for common OWASP vulnerabilities. BlackWidow tool can be used in the initial steps of web-based application vulnerability assessment for the Information Gathering phase. Inject-X fuzzer has the capability to detect XSS, SWL Injection, HTML code injection, etc. vulnerabilities." }, { "code": null, "e": 25450, "s": 25187, "text": "It gathers subdomains, unique dynamic URLs, emails, phone numbers.It uses an Inject-X fuzzer for the detection of vulnerability.It can store the results in dedicated text files in sorted order.It is developed in Python Language.It is open-source and free to use." }, { "code": null, "e": 25517, "s": 25450, "text": "It gathers subdomains, unique dynamic URLs, emails, phone numbers." }, { "code": null, "e": 25580, "s": 25517, "text": "It uses an Inject-X fuzzer for the detection of vulnerability." }, { "code": null, "e": 25646, "s": 25580, "text": "It can store the results in dedicated text files in sorted order." }, { "code": null, "e": 25682, "s": 25646, "text": "It is developed in Python Language." }, { "code": null, "e": 25717, "s": 25682, "text": "It is open-source and free to use." }, { "code": null, "e": 25808, "s": 25717, "text": "Step 1: Check whether Python Environment is Established or not, use the following command:" }, { "code": null, "e": 25816, "s": 25808, "text": "python3" }, { "code": null, "e": 25906, "s": 25816, "text": "Step 2: Open up your Kali Linux terminal and move to Desktop using the following command." }, { "code": null, "e": 25917, "s": 25906, "text": "cd Desktop" }, { "code": null, "e": 26097, "s": 25917, "text": "Step 3: You are on Desktop now create a new directory called Black-Widow using the following command. In this directory, we will complete the installation of the Black-Widow tool." }, { "code": null, "e": 26115, "s": 26097, "text": "mkdir Black-Widow" }, { "code": null, "e": 26192, "s": 26115, "text": "Step 4: Now switch to the Black-Widow directory using the following command." }, { "code": null, "e": 26207, "s": 26192, "text": "cd Black-Widow" }, { "code": null, "e": 26289, "s": 26207, "text": "Step 5: Now you have to install the tool. You have to clone the tool from Github." }, { "code": null, "e": 26342, "s": 26289, "text": "sudo git clone https://github.com/1N3/BlackWidow.git" }, { "code": null, "e": 26488, "s": 26342, "text": "Step 6: The tool has been downloaded successfully in the Black-Widow directory. Now list out the contents of the tool by using the below command." }, { "code": null, "e": 26491, "s": 26488, "text": "ls" }, { "code": null, "e": 26687, "s": 26491, "text": "Step 7: You can observe that there is a new directory created of the BlackWidow tool that has been generated while we were installing the tool. Now move to that directory using the below command:" }, { "code": null, "e": 26702, "s": 26687, "text": "cd BlackWidow " }, { "code": null, "e": 26782, "s": 26702, "text": "Step 8: Once again to discover the contents of the tool, use the below command." }, { "code": null, "e": 26785, "s": 26782, "text": "ls" }, { "code": null, "e": 26873, "s": 26785, "text": "Step 9: Download the required packages for running the tool, use the following command." }, { "code": null, "e": 26911, "s": 26873, "text": "sudo pip3 install -r requirements.txt" }, { "code": null, "e": 27056, "s": 26911, "text": "Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of tool) index of the tool." }, { "code": null, "e": 27078, "s": 27056, "text": "python3 blackwidow -h" }, { "code": null, "e": 27217, "s": 27078, "text": "In this example, we will be performing Full URL Spider. We have provided the target Full URL using the -u tag (https://geeksforgeeks.org) " }, { "code": null, "e": 27270, "s": 27217, "text": "sudo python3 blackwidow -u https://geeksforgeeks.org" }, { "code": null, "e": 27399, "s": 27270, "text": "In the below Screenshot, we are getting our scan results, Subdomains of geeksforgeeks.org are displayed in the below Screenshot." }, { "code": null, "e": 27601, "s": 27399, "text": "In the below Screenshot, dynamic URLs found on geeksforgeeks.org are mentioned below in the screenshot, Basically, these are parameterized URLs that can be tested for XSS and many more vulnerabilities." }, { "code": null, "e": 27747, "s": 27601, "text": "In the below screenshot, the files created by the tool while scanning is shown. Each file has its own results like subdomains, emails, URLs, etc." }, { "code": null, "e": 27879, "s": 27747, "text": "In the below Screenshot, You can see that Emails of geeksforgeeks.org are saved in the emails.txt file, this makes the task easier." }, { "code": null, "e": 28042, "s": 27879, "text": "In this example, rather than providing a full URL (like Example 1), we are specifying only domain names to scan. -d tag is used along with the target domain name." }, { "code": null, "e": 28087, "s": 28042, "text": "sudo python3 blackwidow -d geeksforgeeks.org" }, { "code": null, "e": 28109, "s": 28087, "text": "Domain name to spider" }, { "code": null, "e": 28185, "s": 28109, "text": "In the below Screenshot, we have got the results of our Domain name Spider." }, { "code": null, "e": 28332, "s": 28185, "text": "In this example, we will scan the domain to a certain depth. 5 levels of depth will be scanned as we have specified a depth of 5 using the -l tag." }, { "code": null, "e": 28382, "s": 28332, "text": "sudo python3 blackwidow -d geeksforgeeks.org -l 5" }, { "code": null, "e": 28452, "s": 28382, "text": "In the below Screenshot, the results of the depth of 5 are displayed." }, { "code": null, "e": 28626, "s": 28452, "text": "In this example, We will scan for all the dynamic URLs detected on the geeksforgeeks.org domain. In the below Screenshot, the list of unique_dynaminc URLs list is displayed." }, { "code": null, "e": 28757, "s": 28626, "text": "sudo python3 blackwidow -d geeksforgeeks.org -s /usr/share/blackwidow/geeksforgeeks.org_80/geeksforgeeks.org_80-dynamic-unique.txt" }, { "code": null, "e": 28863, "s": 28757, "text": "In the below Screenshot, we are starting our Scan on dynamic URLs which are provided in the form of list." }, { "code": null, "e": 28950, "s": 28863, "text": "In the below screenshot, you can see that the results of the above scan are displayed." }, { "code": null, "e": 29101, "s": 28950, "text": "In this example, we will perform a scan on the domain specified with the port number. We have specified Port 80, so only Port 80 URLs will be scanned." }, { "code": null, "e": 29152, "s": 29101, "text": "sudo python3 blackwidow -d geeksforgeeks.org -p 80" }, { "code": null, "e": 29239, "s": 29152, "text": "In the below Screenshot, we have got the results of our above Example Port of the URL." }, { "code": null, "e": 29353, "s": 29239, "text": "In this example, we will be displayed in a more verbose format. -v tag is used along with the confirmation (y/n)." }, { "code": null, "e": 29403, "s": 29353, "text": "sudo python3 blackwidow -d geeksforgeeks.org -v y" }, { "code": null, "e": 29473, "s": 29403, "text": "In the below Screenshot, the results of verbose format are displayed." }, { "code": null, "e": 29484, "s": 29473, "text": "Kali-Linux" }, { "code": null, "e": 29496, "s": 29484, "text": "Linux-Tools" }, { "code": null, "e": 29507, "s": 29496, "text": "Linux-Unix" }, { "code": null, "e": 29605, "s": 29507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29642, "s": 29605, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29668, "s": 29642, "text": "Thread functions in C/C++" }, { "code": null, "e": 29703, "s": 29668, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29737, "s": 29703, "text": "mv command in Linux with examples" }, { "code": null, "e": 29774, "s": 29737, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29803, "s": 29774, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29829, "s": 29803, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29869, "s": 29829, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 29904, "s": 29869, "text": "Basic Operators in Shell Scripting" } ]
Last element of vector in C++ (Accessing and updating) - GeeksforGeeks
10 Sep, 2020 In C++ vectors, we can access last element using size of vector using following ways. 1) Using size() #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{10, 20, 30, 40, 50}; // Accessing last element int n = v.size(); cout << v[n - 1] << endl; // modifying last element v[n - 1] = 100; cout << v[n - 1] << endl; return 0;} Output : 50 100 2) Using back() We can access and modify last value using back(). #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{10, 20, 30, 40, 50}; // Accessing last element cout << v.back() << endl; // modifying last element v.back() = 100; cout << v.back() << endl; return 0;} Output : 50 100 19bcs1298 cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Classes and Objects Constructors in C++ Socket Programming in C/C++ Operator Overloading in C++ Copy Constructor in C++ Virtual Function in C++ vector erase() and clear() in C++ rand() and srand() in C/C++ Templates in C++ with Examples unordered_map in C++ STL
[ { "code": null, "e": 24080, "s": 24052, "text": "\n10 Sep, 2020" }, { "code": null, "e": 24166, "s": 24080, "text": "In C++ vectors, we can access last element using size of vector using following ways." }, { "code": null, "e": 24182, "s": 24166, "text": "1) Using size()" }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{10, 20, 30, 40, 50}; // Accessing last element int n = v.size(); cout << v[n - 1] << endl; // modifying last element v[n - 1] = 100; cout << v[n - 1] << endl; return 0;}", "e": 24458, "s": 24182, "text": null }, { "code": null, "e": 24467, "s": 24458, "text": "Output :" }, { "code": null, "e": 24474, "s": 24467, "text": "50\n100" }, { "code": null, "e": 24540, "s": 24474, "text": "2) Using back() We can access and modify last value using back()." }, { "code": "#include <bits/stdc++.h>using namespace std; int main(){ vector<int> v{10, 20, 30, 40, 50}; // Accessing last element cout << v.back() << endl; // modifying last element v.back() = 100; cout << v.back() << endl; return 0;}", "e": 24795, "s": 24540, "text": null }, { "code": null, "e": 24804, "s": 24795, "text": "Output :" }, { "code": null, "e": 24811, "s": 24804, "text": "50\n100" }, { "code": null, "e": 24821, "s": 24811, "text": "19bcs1298" }, { "code": null, "e": 24832, "s": 24821, "text": "cpp-vector" }, { "code": null, "e": 24836, "s": 24832, "text": "STL" }, { "code": null, "e": 24840, "s": 24836, "text": "C++" }, { "code": null, "e": 24844, "s": 24840, "text": "STL" }, { "code": null, "e": 24848, "s": 24844, "text": "CPP" }, { "code": null, "e": 24946, "s": 24848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24955, "s": 24946, "text": "Comments" }, { "code": null, "e": 24968, "s": 24955, "text": "Old Comments" }, { "code": null, "e": 24992, "s": 24968, "text": "C++ Classes and Objects" }, { "code": null, "e": 25012, "s": 24992, "text": "Constructors in C++" }, { "code": null, "e": 25040, "s": 25012, "text": "Socket Programming in C/C++" }, { "code": null, "e": 25068, "s": 25040, "text": "Operator Overloading in C++" }, { "code": null, "e": 25092, "s": 25068, "text": "Copy Constructor in C++" }, { "code": null, "e": 25116, "s": 25092, "text": "Virtual Function in C++" }, { "code": null, "e": 25150, "s": 25116, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 25178, "s": 25150, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25209, "s": 25178, "text": "Templates in C++ with Examples" } ]
How can we perform ROLLBACK transactions inside a MySQL stored procedure?
As we know that ROLLBACK will revert any changes made to the database after the transaction has been started. To perform the ROLLBACK in MySQL stored procedure we must have to declare EXIT handler. We can use a handler for either sqlexception or SQL warnings. It can be understood with the help of an example in which stored procedure having ROLLBACK created for the table having the following details − mysql> SHOW CREATE table gg\G *************************** 1. row *************************** Table: gg Create Table: CREATE TABLE `gg` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(30) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 1 row in set (0.00 sec) We can see that the column ‘name’ cannot have NULL values and table have the following data − mysql> Select * from employee.tbl; +----+---------+ | Id | Name | +----+---------+ | 1 | Mohan | | 2 | Gaurav | | 3 | Sohan | | 4 | Saurabh | | 5 | Yash | | 6 | Rahul | +----+---------+ 6 rows in set (0.00 sec) mysql> Delimiter // mysql> Create Procedure st_transaction_Rollback() -> BEGIN -> DECLARE exit handler for sqlexception -> BEGIN -> ROLLBACK; -> END; -> DECLARE exit handler for sqlwarning -> BEGIN -> ROLLBACK; -> END; -> START TRANSACTION; -> INSERT INTO employee.tbl(name) values(); -> UPDATE employee.tbl set name = 'YashPal' where id = 5; -> COMMIT; -> END // Query OK, 0 rows affected (0.02 sec) mysql> Delimiter ; mysql> CALL st_transaction_Rollback () Query OK, 0 rows affected (0.00 sec) mysql> Select * from employee.tbl; +----+---------+ | Id | Name | +----+---------+ | 1 | Mohan | | 2 | Gaurav | | 3 | Sohan | | 4 | Saurabh | | 5 | Yash | | 6 | Rahul | +----+---------+ 6 rows in set (0.00 sec) We can see from the above result set that the changes made by UPDATE statement have been ROLLBACKED because the first query of INSERT has thrown an error (trying to insert NULL values).
[ { "code": null, "e": 1466, "s": 1062, "text": "As we know that ROLLBACK will revert any changes made to the database after the transaction has been started. To perform the ROLLBACK in MySQL stored procedure we must have to declare EXIT handler. We can use a handler for either sqlexception or SQL warnings. It can be understood with the help of an example in which stored procedure having ROLLBACK created for the table having the following details −" }, { "code": null, "e": 1785, "s": 1466, "text": "mysql> SHOW CREATE table gg\\G\n*************************** 1. row ***************************\n Table: gg\nCreate Table: CREATE TABLE `gg` (\n `Id` int(11) NOT NULL AUTO_INCREMENT,\n `Name` varchar(30) NOT NULL,\n PRIMARY KEY (`Id`)\n) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1\n1 row in set (0.00 sec)" }, { "code": null, "e": 1879, "s": 1785, "text": "We can see that the column ‘name’ cannot have NULL values and table have the following data −" }, { "code": null, "e": 2109, "s": 1879, "text": "mysql> Select * from employee.tbl;\n+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | Mohan |\n| 2 | Gaurav |\n| 3 | Sohan |\n| 4 | Saurabh |\n| 5 | Yash |\n| 6 | Rahul |\n+----+---------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2893, "s": 2109, "text": "mysql> Delimiter //\nmysql> Create Procedure st_transaction_Rollback()\n -> BEGIN\n -> DECLARE exit handler for sqlexception\n -> BEGIN\n -> ROLLBACK;\n -> END;\n -> DECLARE exit handler for sqlwarning\n -> BEGIN\n -> ROLLBACK;\n -> END;\n -> START TRANSACTION;\n -> INSERT INTO employee.tbl(name) values();\n -> UPDATE employee.tbl set name = 'YashPal' where id = 5;\n -> COMMIT;\n -> END //\nQuery OK, 0 rows affected (0.02 sec)\n\nmysql> Delimiter ;\nmysql> CALL st_transaction_Rollback ()\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select * from employee.tbl;\n+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | Mohan |\n| 2 | Gaurav |\n| 3 | Sohan |\n| 4 | Saurabh |\n| 5 | Yash |\n| 6 | Rahul |\n+----+---------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3079, "s": 2893, "text": "We can see from the above result set that the changes made by UPDATE statement have been ROLLBACKED because the first query of INSERT has thrown an error (trying to insert NULL values)." } ]
C++ Tutorial
C++ is a popular programming language. C++ is used to create computer programs, and is one of the most used language in game development. Our "Try it Yourself" editor makes it easy to learn C++. You can edit C++ code and view the result in your browser. Click on the "Run example" button to see how it works. We recommend reading this tutorial, in the sequence listed in the left menu. C++ is an object oriented language and some concepts may be new. Take breaks when needed, and go over the examples as many times as needed. Insert the missing part of the code below to output "Hello World". int main() { << "Hello World!"; return 0; } Start the Exercise Learn by examples! This tutorial supplements all explanations with clarifying examples. See All C++ Examples Learn by taking a quiz! The quiz will give you a signal of how much you know, or do not know, about C++. Start C++ Quiz Get certified by completing the C++ course We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 39, "s": 0, "text": "C++ is a popular programming language." }, { "code": null, "e": 138, "s": 39, "text": "C++ is used to create computer programs, and is one of the most used language in game development." }, { "code": null, "e": 254, "s": 138, "text": "Our \"Try it Yourself\" editor makes it easy to learn C++. You can edit C++ code and view the result in your browser." }, { "code": null, "e": 309, "s": 254, "text": "Click on the \"Run example\" button to see how it works." }, { "code": null, "e": 386, "s": 309, "text": "We recommend reading this tutorial, in the sequence listed in the left menu." }, { "code": null, "e": 526, "s": 386, "text": "C++ is an object oriented language and some concepts may be new. Take breaks when needed, and go\nover the examples as many times as needed." }, { "code": null, "e": 593, "s": 526, "text": "Insert the missing part of the code below to output \"Hello World\"." }, { "code": null, "e": 643, "s": 593, "text": "int main() {\n << \"Hello World!\";\n return 0;\n}\n" }, { "code": null, "e": 662, "s": 643, "text": "Start the Exercise" }, { "code": null, "e": 750, "s": 662, "text": "Learn by examples! This tutorial supplements all explanations with clarifying examples." }, { "code": null, "e": 771, "s": 750, "text": "See All C++ Examples" }, { "code": null, "e": 876, "s": 771, "text": "Learn by taking a quiz! The quiz will give you a signal of how much you know, or do not know, about C++." }, { "code": null, "e": 891, "s": 876, "text": "Start C++ Quiz" }, { "code": null, "e": 934, "s": 891, "text": "Get certified by completing the C++ course" }, { "code": null, "e": 967, "s": 934, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1009, "s": 967, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1116, "s": 1009, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1135, "s": 1116, "text": "help@w3schools.com" } ]
Understanding Learning Rate. Originally published at OpenGenus IQ. | by Aditya Rakhecha | Towards Data Science
Originally published at OpenGenus IQ. When building a deep learning project the most common problem we all face is choosing the correct hyper-parameters (often known as optimizers). This is critical as the hyper-parameters determine the expertise of the machine learning model. In Machine Learning (ML hereafter), a hyper-parameter is a configuration variable that’s external to the model and whose value is not estimated from the data given. Hyper-parameters are an essential part of the process of estimating model parameters and are often defined by the practitioner. When an ML algorithm is used for a specific problem, for example when we are using a grid search or a random search algorithm, then we are actually tuning the hyper-parameters of the model to discover the values that help us to achieve the most accurate predictions. Learning rate (λ) is one such hyper-parameter that defines the adjustment in the weights of our network with respect to the loss gradient descent. It determines how fast or slow we will move towards the optimal weights The Gradient Descent Algorithm estimates the weights of the model in many iterations by minimizing a cost function at every step. Here is the algorithm: Repeat until convergence { Wj = Wj - λ θF(Wj)/θWj } Where: Wj is the weight θ is the theta F(Wj) is the cost function respectively. In order for Gradient Descent to work, we must set the learning rate to an appropriate value. This parameter determines how fast or slow we will move towards the optimal weights. If the learning rate is very large we will skip the optimal solution. If it is too small we will need too many iterations to converge to the best values. So using a good learning rate is crucial. In simple language, we can define learning rate as how quickly our network abandons the concepts it has learned up until now for new ones. To understand this better let’s consider an example. If a child sees ten dogs and all of them are black in color, he might believe that all dogs are black and would consider this as a feature when trying to identify a dog. Imagine he’s shown a white dog, and his parents tell him that it’s a dog. With a desirable learning rate, he would quickly understand that black color is not an important feature of dogs and would look for another feature. But with a low learning rate, he would consider the white dog as an outlier and would continue to believe that all dogs are black. And if the learning rate is too high, he would instantly start to believe that all dogs are white even though he has seen more black dogs than white ones. The point is it’s’ really important to achieve a desirable learning rate because: both low and high learning rates results in wasted time and resources A lower learning rate means more training time more time results in increased cloud GPU costs a higher rate could result in a model that might not be able to predict anything accurately A desirable learning rate is one that’s low enough so that the network converges to something useful but high enough so that it can be trained in a reasonable amount of time. The learning rate is the most important hyper-parameter for tuning neural networks. A good learning rate could be the difference between a model that doesn’t learn anything and a model that presents state-of-the-art results. The below diagram demonstrates the different scenarios one can fall into when configuring the learning rate. The obvious way to find a desirable or optimal learning rate is through trial and error. To do this efficiently, there are a few ways that we should adhere to. A learning rate of 0.01 and 0.011 are unlikely to yield vastly different results. Even if they did, searching in such small increments is very costly and inefficient: what if both learning rates caused the model to diverge? The time spent training would be a waste. A more efficient way is to try widely different learning rates to determine the range of learning rates you should explore and concentrate your efforts there. For instance, whenever I am trying to tune the learning rate, I generally start off by searching across the learning rates 1e-7, 1e-6, 1e-5, ... 0.01, 0.1, 1. In other words, I search across various orders of 10 to find an optimal range of learning rates. Then, I search in smaller increments. For instance, if I found the optimal range to be somewhere between 0.01 and 0.1, I would then start searching learning rates in that range such as 0.03. This is exactly similar to the idea behind binary search and is a widely applicable technique. Starting off with the entire dataset is likely to be a waste of time. Chances are, some learning rates will cause your loss to diverge or fluctuate and some learning rates are likely to train very slowly, so these orders of learning rates can be removed from your search after a few iterations. Although trial and error is a relatively fail-proof way of tuning the learning rate, a more efficient way which does minimal training to find the best learning rate to start from is “Learning Rate Test”. The basic idea is that you want to efficiently find the maximum learning rate you can use which will improve the loss. In order to find that value, you train slightly with multiple learning rates and see how the loss changes. The actual procedure is: Choose a minimum and maximum learning rate to search through (e.g. 1e-7 and 0.1) Train the model for several epochs using SGD while linearly increasing the learning rate from the minimum to maximum learning rate. At each iteration, record the accuracy (or loss). Plot the test accuracy, and see where the loss/accuracy starts to improve, and when it starts to get worse/plateau/to become ragged. The latter learning rate is the maximum learning rate that converges and is a good value for your initial learning rate. The former learning rate, or 1/3–1/4 of the maximum learning rates is a good minimum learning rate that you can decrease if you are using learning rate decay. If the test accuracy curve looks like the above diagram, a good learning rate to begin from would be 0.006, where the loss starts to become jagged. This method of improving the convergence rate of hyper-parameters reduces the need for the manual tuning of the initial learning rate. This method works by dynamically updating the learning rate during optimization using the gradient with respect to the learning rate of the update rule itself. Computing this “hyper-gradient” needs little additional computation, requires only one extra copy of the original gradient to be stored in memory, and relies upon nothing more than what is provided by reverse-mode automatic differentiation. It’s clear that configuring a model’s learning rate is a crucial task, and whatever approach you opt for, it will be time-consuming and challenging. A powerful technique that involves selecting a range of learning rates for a neural network has been discussed in the paper “Cyclical Learning Rates for Training Neural Networks” by Leslie N. Smith.
[ { "code": null, "e": 210, "s": 172, "text": "Originally published at OpenGenus IQ." }, { "code": null, "e": 450, "s": 210, "text": "When building a deep learning project the most common problem we all face is choosing the correct hyper-parameters (often known as optimizers). This is critical as the hyper-parameters determine the expertise of the machine learning model." }, { "code": null, "e": 743, "s": 450, "text": "In Machine Learning (ML hereafter), a hyper-parameter is a configuration variable that’s external to the model and whose value is not estimated from the data given. Hyper-parameters are an essential part of the process of estimating model parameters and are often defined by the practitioner." }, { "code": null, "e": 1010, "s": 743, "text": "When an ML algorithm is used for a specific problem, for example when we are using a grid search or a random search algorithm, then we are actually tuning the hyper-parameters of the model to discover the values that help us to achieve the most accurate predictions." }, { "code": null, "e": 1229, "s": 1010, "text": "Learning rate (λ) is one such hyper-parameter that defines the adjustment in the weights of our network with respect to the loss gradient descent. It determines how fast or slow we will move towards the optimal weights" }, { "code": null, "e": 1359, "s": 1229, "text": "The Gradient Descent Algorithm estimates the weights of the model in many iterations by minimizing a cost function at every step." }, { "code": null, "e": 1382, "s": 1359, "text": "Here is the algorithm:" }, { "code": null, "e": 1439, "s": 1382, "text": "Repeat until convergence { Wj = Wj - λ θF(Wj)/θWj }" }, { "code": null, "e": 1446, "s": 1439, "text": "Where:" }, { "code": null, "e": 1463, "s": 1446, "text": "Wj is the weight" }, { "code": null, "e": 1478, "s": 1463, "text": "θ is the theta" }, { "code": null, "e": 1519, "s": 1478, "text": "F(Wj) is the cost function respectively." }, { "code": null, "e": 1894, "s": 1519, "text": "In order for Gradient Descent to work, we must set the learning rate to an appropriate value. This parameter determines how fast or slow we will move towards the optimal weights. If the learning rate is very large we will skip the optimal solution. If it is too small we will need too many iterations to converge to the best values. So using a good learning rate is crucial." }, { "code": null, "e": 2033, "s": 1894, "text": "In simple language, we can define learning rate as how quickly our network abandons the concepts it has learned up until now for new ones." }, { "code": null, "e": 2086, "s": 2033, "text": "To understand this better let’s consider an example." }, { "code": null, "e": 2256, "s": 2086, "text": "If a child sees ten dogs and all of them are black in color, he might believe that all dogs are black and would consider this as a feature when trying to identify a dog." }, { "code": null, "e": 2479, "s": 2256, "text": "Imagine he’s shown a white dog, and his parents tell him that it’s a dog. With a desirable learning rate, he would quickly understand that black color is not an important feature of dogs and would look for another feature." }, { "code": null, "e": 2610, "s": 2479, "text": "But with a low learning rate, he would consider the white dog as an outlier and would continue to believe that all dogs are black." }, { "code": null, "e": 2765, "s": 2610, "text": "And if the learning rate is too high, he would instantly start to believe that all dogs are white even though he has seen more black dogs than white ones." }, { "code": null, "e": 2847, "s": 2765, "text": "The point is it’s’ really important to achieve a desirable learning rate because:" }, { "code": null, "e": 2917, "s": 2847, "text": "both low and high learning rates results in wasted time and resources" }, { "code": null, "e": 2964, "s": 2917, "text": "A lower learning rate means more training time" }, { "code": null, "e": 3011, "s": 2964, "text": "more time results in increased cloud GPU costs" }, { "code": null, "e": 3103, "s": 3011, "text": "a higher rate could result in a model that might not be able to predict anything accurately" }, { "code": null, "e": 3278, "s": 3103, "text": "A desirable learning rate is one that’s low enough so that the network converges to something useful but high enough so that it can be trained in a reasonable amount of time." }, { "code": null, "e": 3503, "s": 3278, "text": "The learning rate is the most important hyper-parameter for tuning neural networks. A good learning rate could be the difference between a model that doesn’t learn anything and a model that presents state-of-the-art results." }, { "code": null, "e": 3612, "s": 3503, "text": "The below diagram demonstrates the different scenarios one can fall into when configuring the learning rate." }, { "code": null, "e": 3772, "s": 3612, "text": "The obvious way to find a desirable or optimal learning rate is through trial and error. To do this efficiently, there are a few ways that we should adhere to." }, { "code": null, "e": 4038, "s": 3772, "text": "A learning rate of 0.01 and 0.011 are unlikely to yield vastly different results. Even if they did, searching in such small increments is very costly and inefficient: what if both learning rates caused the model to diverge? The time spent training would be a waste." }, { "code": null, "e": 4197, "s": 4038, "text": "A more efficient way is to try widely different learning rates to determine the range of learning rates you should explore and concentrate your efforts there." }, { "code": null, "e": 4739, "s": 4197, "text": "For instance, whenever I am trying to tune the learning rate, I generally start off by searching across the learning rates 1e-7, 1e-6, 1e-5, ... 0.01, 0.1, 1. In other words, I search across various orders of 10 to find an optimal range of learning rates. Then, I search in smaller increments. For instance, if I found the optimal range to be somewhere between 0.01 and 0.1, I would then start searching learning rates in that range such as 0.03. This is exactly similar to the idea behind binary search and is a widely applicable technique." }, { "code": null, "e": 5034, "s": 4739, "text": "Starting off with the entire dataset is likely to be a waste of time. Chances are, some learning rates will cause your loss to diverge or fluctuate and some learning rates are likely to train very slowly, so these orders of learning rates can be removed from your search after a few iterations." }, { "code": null, "e": 5489, "s": 5034, "text": "Although trial and error is a relatively fail-proof way of tuning the learning rate, a more efficient way which does minimal training to find the best learning rate to start from is “Learning Rate Test”. The basic idea is that you want to efficiently find the maximum learning rate you can use which will improve the loss. In order to find that value, you train slightly with multiple learning rates and see how the loss changes. The actual procedure is:" }, { "code": null, "e": 5702, "s": 5489, "text": "Choose a minimum and maximum learning rate to search through (e.g. 1e-7 and 0.1) Train the model for several epochs using SGD while linearly increasing the learning rate from the minimum to maximum learning rate." }, { "code": null, "e": 5752, "s": 5702, "text": "At each iteration, record the accuracy (or loss)." }, { "code": null, "e": 6165, "s": 5752, "text": "Plot the test accuracy, and see where the loss/accuracy starts to improve, and when it starts to get worse/plateau/to become ragged. The latter learning rate is the maximum learning rate that converges and is a good value for your initial learning rate. The former learning rate, or 1/3–1/4 of the maximum learning rates is a good minimum learning rate that you can decrease if you are using learning rate decay." }, { "code": null, "e": 6313, "s": 6165, "text": "If the test accuracy curve looks like the above diagram, a good learning rate to begin from would be 0.006, where the loss starts to become jagged." }, { "code": null, "e": 6849, "s": 6313, "text": "This method of improving the convergence rate of hyper-parameters reduces the need for the manual tuning of the initial learning rate. This method works by dynamically updating the learning rate during optimization using the gradient with respect to the learning rate of the update rule itself. Computing this “hyper-gradient” needs little additional computation, requires only one extra copy of the original gradient to be stored in memory, and relies upon nothing more than what is provided by reverse-mode automatic differentiation." }, { "code": null, "e": 6998, "s": 6849, "text": "It’s clear that configuring a model’s learning rate is a crucial task, and whatever approach you opt for, it will be time-consuming and challenging." } ]
Haskell - Monads
Monads are nothing but a type of Applicative Functor with some extra features. It is a Type class which governs three basic rules known as monadic rules. All the three rules are strictly applicable over a Monad declaration which is as follows − class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b x >> y = x >>= \_ -> y fail :: String -> m a fail msg = error msg The three basic laws that are applicable over a Monad declaration are − Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "return >=> mf = mf". Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "return >=> mf = mf". Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "mf >=> return = mf". Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "mf >=> return = mf". Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as "( f >==>g) >=> h =f >= >(g >=h)". Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as "( f >==>g) >=> h =f >= >(g >=h)". The first two laws iterate the same point, i.e., a return should have identity behavior on both sides of the bind operator. We have already used lots of Monads in our previous examples without realizing that they are Monad. Consider the following example where we are using a List Monad to generate a specific list. main = do print([1..10] >>= (\x -> if odd x then [x*2] else [])) This code will produce the following output − [2,6,10,14,18] Print Add Notes Bookmark this page
[ { "code": null, "e": 2069, "s": 1915, "text": "Monads are nothing but a type of Applicative Functor with some extra features. It is a Type class which governs three basic rules known as monadic rules." }, { "code": null, "e": 2160, "s": 2069, "text": "All the three rules are strictly applicable over a Monad declaration which is as follows −" }, { "code": null, "e": 2352, "s": 2160, "text": "class Monad m where \n return :: a -> m a \n (>>=) :: m a -> (a -> m b) -> m b \n (>>) :: m a -> m b -> m b \n x >> y = x >>= \\_ -> y \n fail :: String -> m a \n fail msg = error msg " }, { "code": null, "e": 2424, "s": 2352, "text": "The three basic laws that are applicable over a Monad declaration are −" }, { "code": null, "e": 2583, "s": 2424, "text": "Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"return >=> mf = mf\"." }, { "code": null, "e": 2742, "s": 2583, "text": "Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"return >=> mf = mf\"." }, { "code": null, "e": 2902, "s": 2742, "text": "Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"mf >=> return = mf\"." }, { "code": null, "e": 3062, "s": 2902, "text": "Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"mf >=> return = mf\"." }, { "code": null, "e": 3239, "s": 3062, "text": "Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as \"( f >==>g) >=> h =f >= >(g >=h)\"." }, { "code": null, "e": 3416, "s": 3239, "text": "Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as \"( f >==>g) >=> h =f >= >(g >=h)\"." }, { "code": null, "e": 3540, "s": 3416, "text": "The first two laws iterate the same point, i.e., a return should have identity behavior on both sides of the bind operator." }, { "code": null, "e": 3732, "s": 3540, "text": "We have already used lots of Monads in our previous examples without realizing that they are Monad. Consider the following example where we are using a List Monad to generate a specific list." }, { "code": null, "e": 3800, "s": 3732, "text": "main = do\n print([1..10] >>= (\\x -> if odd x then [x*2] else []))" }, { "code": null, "e": 3846, "s": 3800, "text": "This code will produce the following output −" }, { "code": null, "e": 3862, "s": 3846, "text": "[2,6,10,14,18]\n" }, { "code": null, "e": 3869, "s": 3862, "text": " Print" }, { "code": null, "e": 3880, "s": 3869, "text": " Add Notes" } ]
HTML5 - URL
It accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format. <!DOCTYPE HTML> <html> <body> <form action = "/cgi-bin/html5.cgi" method = "get"> Enter URL : <input type = "url" name = "newinput" /> <input type = "submit" value = "submit" /> </form> </body> </html> 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2850, "s": 2608, "text": "It accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format." }, { "code": null, "e": 3091, "s": 2850, "text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Enter URL : <input type = \"url\" name = \"newinput\" />\n <input type = \"submit\" value = \"submit\" />\n </form>\n\n </body>\n</html>" }, { "code": null, "e": 3124, "s": 3091, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3138, "s": 3124, "text": " Anadi Sharma" }, { "code": null, "e": 3173, "s": 3138, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3187, "s": 3173, "text": " Anadi Sharma" }, { "code": null, "e": 3222, "s": 3187, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3239, "s": 3222, "text": " Frahaan Hussain" }, { "code": null, "e": 3274, "s": 3239, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3305, "s": 3274, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3338, "s": 3305, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3369, "s": 3338, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3404, "s": 3369, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3435, "s": 3404, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3442, "s": 3435, "text": " Print" }, { "code": null, "e": 3453, "s": 3442, "text": " Add Notes" } ]
Argparse VS Docopt VS Click - Comparing Python Command-Line Parsing Libraries - GeeksforGeeks
11 Aug, 2021 Before knowing about the Python parsing libraries we must have prior knowledge about Command Line User Interface. A Command Line Interface (CLI) provides a user-friendly interface for the Command-line programs, which is most commonly favored by the developers or the programmers who prefer keyboard programming, instead of using the mouse. By building Command-line interfaces user can interact through the consoles, shells or terminals more efficiently. There are plenty of Python libraries to build command line applications such as Argparse, Docopt, Click, Client and many more. Now, let us know more on frequently used Python libraries – Argparse, Docopt and Click. Argparse is a user-friendly command line interface. The argparse module parses the command-line arguments and options/flags. Installation: There many ways to install argparse module, the easy way is by using pip $ pip install argparse Initialize Argparse import argparse parser=argparse.ArgumentParser(description="Program description") Adding positional/optional arguments: Using add_argument() we can add positional/optional parameters to the parser. parser.add_argument(‘-parameterName’,’–optionalName’,help=”message”) Here, -parameterName is a short hand notation. –optionalName is the optional parameter. -h –help monitors the help. Command Line Usage $ python [file].py [command] [options] name Example: Python3 # argparse_example.py import argparse if __name__=='__main__': #Initialize parser=argparse.ArgumentParser(description="Simple calculator") #Adding optional parameters parser.add_argument('-n1', '--num1', help="Number 1", type=float) parser.add_argument('-n2', '--num2', help="Number 2", type=float) parser.add_argument('-op', '--operation', help="operator", default="*") #Parsing the argument args=parser.parse_args() print(args) #Initialize result to None result =None #Simple calculator operations if args.operation == '+': result=args.num1+args.num2 if args.operation == '-': result=args.num1-args.num2 if args.operation == '/': result=args.num1/args.num2 if args.operation == '*': result=args.num1*args.num2 if args.operation == 'pow': result=pow(args.num1,args.num2) #Print the result print("Result = " ,result) Output: Docopt creates command line interface for the command line app, it automatically generates a parser for it. The main idea of docopt is to describe the interface literally with text, as in docstring. Installation: To install this module type the below command in the terminal. $pip install docopt It is most commonly used to display the help messages and it is invoked with -h or –help option. docopt gives you strong control over your help page and it consists of the usage keyword which is case-insensitive that is followed by the program name. A simple usage pattern is as follows: Usage : my_program command --option Example: Python3 #docopt_example.py #usage patternusage=''' Usage: docopt_example.py command --option <argument> docopt_example.py <argument> <repeating-argument> docopt_example.py --version Options: -h, --help Display help -o, --option Display options -l, --all List all -q, --quit exit --version Version 3.6.1 ''' #Initialization from docopt import docopt args=docopt(usage)print(args) Output: Click is a Command Line Interface Creation Kit, it helps in arbitrary nesting of commands, automatic help page generation, supports lazy loading of subcommands at runtime. It aims to make the process of writing command-line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API. It comes with useful common helpers (getting terminal dimensions, ANSI colors, fetching direct keyboard input, screen clearing, finding config paths, launching apps and editors, etc.) Installation: To install this module type the below command in the terminal. $pip install click Example: Python3 # click_example.py import click # initialize result to 0result=0 @click.command()@click.option('--num1', default=1, help='Enter a float value', type=float) @click.option('--num2', default=1, help='Enter a float value', type=float) @click.option('--op', default='+', help='Enter the operator') # Calculator functiondef calculator(num1,num2,op): if op=='+': result=num1+num2 if op=='*': result=num1*num2 if op=='-': result=num1-num2 if op=='/': result=num1/num2 # print the result click.echo("Result is %f" %result) if __name__ =='__main__': calculator() Output: After seeing the implementations of the above library we can conclude that: Argparse: It is a standard library (included with Python) and very simple to use because of the work that happens behind the scenes. For example, this library can differentiate between both the arguments and options that are defined using add_arguments() method automatically. Docopt: This library is used for when writing documentation. Moreover, this library is used in multiple languages i.e. you can learn this library and use it in multiple languages. Click: This library provides the decorator style implementation which is very useful as you can decorate the function you want to use. This also makes reading of code very easy. simmytarika5 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23943, "s": 23915, "text": "\n11 Aug, 2021" }, { "code": null, "e": 24397, "s": 23943, "text": "Before knowing about the Python parsing libraries we must have prior knowledge about Command Line User Interface. A Command Line Interface (CLI) provides a user-friendly interface for the Command-line programs, which is most commonly favored by the developers or the programmers who prefer keyboard programming, instead of using the mouse. By building Command-line interfaces user can interact through the consoles, shells or terminals more efficiently." }, { "code": null, "e": 24612, "s": 24397, "text": "There are plenty of Python libraries to build command line applications such as Argparse, Docopt, Click, Client and many more. Now, let us know more on frequently used Python libraries – Argparse, Docopt and Click." }, { "code": null, "e": 24737, "s": 24612, "text": "Argparse is a user-friendly command line interface. The argparse module parses the command-line arguments and options/flags." }, { "code": null, "e": 24751, "s": 24737, "text": "Installation:" }, { "code": null, "e": 24824, "s": 24751, "text": "There many ways to install argparse module, the easy way is by using pip" }, { "code": null, "e": 24847, "s": 24824, "text": "$ pip install argparse" }, { "code": null, "e": 24867, "s": 24847, "text": "Initialize Argparse" }, { "code": null, "e": 24949, "s": 24867, "text": "import argparse\nparser=argparse.ArgumentParser(description=\"Program description\")" }, { "code": null, "e": 25066, "s": 24949, "text": "Adding positional/optional arguments: Using add_argument() we can add positional/optional parameters to the parser. " }, { "code": null, "e": 25135, "s": 25066, "text": "parser.add_argument(‘-parameterName’,’–optionalName’,help=”message”)" }, { "code": null, "e": 25251, "s": 25135, "text": "Here, -parameterName is a short hand notation. –optionalName is the optional parameter. -h –help monitors the help." }, { "code": null, "e": 25270, "s": 25251, "text": "Command Line Usage" }, { "code": null, "e": 25314, "s": 25270, "text": "$ python [file].py [command] [options] name" }, { "code": null, "e": 25324, "s": 25314, "text": "Example: " }, { "code": null, "e": 25332, "s": 25324, "text": "Python3" }, { "code": "# argparse_example.py import argparse if __name__=='__main__': #Initialize parser=argparse.ArgumentParser(description=\"Simple calculator\") #Adding optional parameters parser.add_argument('-n1', '--num1', help=\"Number 1\", type=float) parser.add_argument('-n2', '--num2', help=\"Number 2\", type=float) parser.add_argument('-op', '--operation', help=\"operator\", default=\"*\") #Parsing the argument args=parser.parse_args() print(args) #Initialize result to None result =None #Simple calculator operations if args.operation == '+': result=args.num1+args.num2 if args.operation == '-': result=args.num1-args.num2 if args.operation == '/': result=args.num1/args.num2 if args.operation == '*': result=args.num1*args.num2 if args.operation == 'pow': result=pow(args.num1,args.num2) #Print the result print(\"Result = \" ,result)", "e": 26478, "s": 25332, "text": null }, { "code": null, "e": 26490, "s": 26481, "text": "Output: " }, { "code": null, "e": 26691, "s": 26490, "text": "Docopt creates command line interface for the command line app, it automatically generates a parser for it. The main idea of docopt is to describe the interface literally with text, as in docstring. " }, { "code": null, "e": 26705, "s": 26691, "text": "Installation:" }, { "code": null, "e": 26769, "s": 26705, "text": "To install this module type the below command in the terminal. " }, { "code": null, "e": 26790, "s": 26769, "text": "$pip install docopt " }, { "code": null, "e": 27079, "s": 26790, "text": "It is most commonly used to display the help messages and it is invoked with -h or –help option. docopt gives you strong control over your help page and it consists of the usage keyword which is case-insensitive that is followed by the program name. A simple usage pattern is as follows: " }, { "code": null, "e": 27117, "s": 27079, "text": "Usage : my_program command --option " }, { "code": null, "e": 27128, "s": 27117, "text": "Example: " }, { "code": null, "e": 27136, "s": 27128, "text": "Python3" }, { "code": "#docopt_example.py #usage patternusage=''' Usage: docopt_example.py command --option <argument> docopt_example.py <argument> <repeating-argument> docopt_example.py --version Options: -h, --help Display help -o, --option Display options -l, --all List all -q, --quit exit --version Version 3.6.1 ''' #Initialization from docopt import docopt args=docopt(usage)print(args)", "e": 27542, "s": 27136, "text": null }, { "code": null, "e": 27550, "s": 27542, "text": "Output:" }, { "code": null, "e": 28075, "s": 27550, "text": "Click is a Command Line Interface Creation Kit, it helps in arbitrary nesting of commands, automatic help page generation, supports lazy loading of subcommands at runtime. It aims to make the process of writing command-line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API. It comes with useful common helpers (getting terminal dimensions, ANSI colors, fetching direct keyboard input, screen clearing, finding config paths, launching apps and editors, etc.) " }, { "code": null, "e": 28089, "s": 28075, "text": "Installation:" }, { "code": null, "e": 28152, "s": 28089, "text": "To install this module type the below command in the terminal." }, { "code": null, "e": 28171, "s": 28152, "text": "$pip install click" }, { "code": null, "e": 28181, "s": 28171, "text": "Example: " }, { "code": null, "e": 28189, "s": 28181, "text": "Python3" }, { "code": "# click_example.py import click # initialize result to 0result=0 @click.command()@click.option('--num1', default=1, help='Enter a float value', type=float) @click.option('--num2', default=1, help='Enter a float value', type=float) @click.option('--op', default='+', help='Enter the operator') # Calculator functiondef calculator(num1,num2,op): if op=='+': result=num1+num2 if op=='*': result=num1*num2 if op=='-': result=num1-num2 if op=='/': result=num1/num2 # print the result click.echo(\"Result is %f\" %result) if __name__ =='__main__': calculator()", "e": 28899, "s": 28189, "text": null }, { "code": null, "e": 28907, "s": 28899, "text": "Output:" }, { "code": null, "e": 28987, "s": 28909, "text": "After seeing the implementations of the above library we can conclude that: " }, { "code": null, "e": 29265, "s": 28987, "text": "Argparse: It is a standard library (included with Python) and very simple to use because of the work that happens behind the scenes. For example, this library can differentiate between both the arguments and options that are defined using add_arguments() method automatically. " }, { "code": null, "e": 29446, "s": 29265, "text": "Docopt: This library is used for when writing documentation. Moreover, this library is used in multiple languages i.e. you can learn this library and use it in multiple languages. " }, { "code": null, "e": 29626, "s": 29446, "text": "Click: This library provides the decorator style implementation which is very useful as you can decorate the function you want to use. This also makes reading of code very easy. " }, { "code": null, "e": 29639, "s": 29626, "text": "simmytarika5" }, { "code": null, "e": 29654, "s": 29639, "text": "python-utility" }, { "code": null, "e": 29661, "s": 29654, "text": "Python" }, { "code": null, "e": 29759, "s": 29661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29768, "s": 29759, "text": "Comments" }, { "code": null, "e": 29781, "s": 29768, "text": "Old Comments" }, { "code": null, "e": 29799, "s": 29781, "text": "Python Dictionary" }, { "code": null, "e": 29834, "s": 29799, "text": "Read a file line by line in Python" }, { "code": null, "e": 29856, "s": 29834, "text": "Enumerate() in Python" }, { "code": null, "e": 29888, "s": 29856, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29918, "s": 29888, "text": "Iterate over a list in Python" }, { "code": null, "e": 29960, "s": 29918, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29986, "s": 29960, "text": "Python String | replace()" }, { "code": null, "e": 30029, "s": 29986, "text": "Python program to convert a list to string" }, { "code": null, "e": 30073, "s": 30029, "text": "Reading and Writing to text files in Python" } ]
Screen Orientations in Android with Examples - GeeksforGeeks
23 Feb, 2021 Screen Orientation, also known as screen rotation, is the attribute of activity element in android. When screen orientation change from one state to other, it is also known as configuration change. States of Screen orientationThere are various possible screen orientation states for any android application, such as: ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED ActivityInfo.SCREEN_ORIENTATION_USER ActivityInfo.SCREEN_ORIENTATION_SENSOR ActivityInfo.SCREEN_ORIENTATION_BEHIND ActivityInfo.SCREEN_ORIENTATION_NOSENSOR ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT The initial orientation of the Screen has to be defined in the AndroidManifest.xml file. Syntax: AndroidManifest.xml <activity android:name="package_name.Your_ActivityName" android:screenOrientation="orientation_type"> </activity> Example: android:screenOrientation="orientation_type"> How to change Screen orientation?Here is an example of an Android application that changes screen orientation for Landscape and Portrait mode. We will create two activities of different screen orientation. The first activity will be as “portrait” orientation and Second activity as “landscape” orientation state. Step-by-Step demonstration: Creating the activities: There will be two activities and hence two XML files, one for each activity.activity_main.xml: XML file for first activity consist of constraint layout with Button and Text View in it. This activity is in Landscape state.activity_next.xml: XML file for second activity consist of constraint layout with Text View in it. This activity is in Landscape state.Below is the code for both activities:activity_main.xmlactivity_next.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?> <!--Constraint Layout--><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.geeksforgeeks.screenorientation.MainActivity"> <!--Button to launch next activity with onClick--> <Button android:id="@+id/b1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next Activity" android:layout_marginTop="100dp" android:onClick="onClick" android:layout_marginBottom="10dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintVertical_bias="0.613" app:layout_constraintHorizontal_bias="0.612" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv1" /> <!--TextView --> <TextView android:text="Potrait orientation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="124dp" android:textSize="25dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> activity_next.xml<?xml version="1.0" encoding="utf-8"?> <!--Constraint layout--> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.geeksforgeeks.screenorientation.NextActivity"> <!--TextView--> <TextView android:id="@+id/tv" android:text="Landscape orientation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="170dp" android:textSize="22dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> activity_main.xml: XML file for first activity consist of constraint layout with Button and Text View in it. This activity is in Landscape state.activity_next.xml: XML file for second activity consist of constraint layout with Text View in it. This activity is in Landscape state. activity_main.xml: XML file for first activity consist of constraint layout with Button and Text View in it. This activity is in Landscape state. activity_next.xml: XML file for second activity consist of constraint layout with Text View in it. This activity is in Landscape state. Below is the code for both activities: activity_main.xml activity_next.xml <?xml version="1.0" encoding="utf-8"?> <!--Constraint Layout--><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.geeksforgeeks.screenorientation.MainActivity"> <!--Button to launch next activity with onClick--> <Button android:id="@+id/b1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next Activity" android:layout_marginTop="100dp" android:onClick="onClick" android:layout_marginBottom="10dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintVertical_bias="0.613" app:layout_constraintHorizontal_bias="0.612" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv1" /> <!--TextView --> <TextView android:text="Potrait orientation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="124dp" android:textSize="25dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> <?xml version="1.0" encoding="utf-8"?> <!--Constraint layout--> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.geeksforgeeks.screenorientation.NextActivity"> <!--TextView--> <TextView android:id="@+id/tv" android:text="Landscape orientation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="170dp" android:textSize="22dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> Creating the Java file: There will be two activities and hence two Java files, one for each activity.MainActivity.java: Java file for Main Activity, in which setOnClick() listener is attached to the button to launch next activity with different orientation.NextActivity.java: Java file for Next Activity which is in Landscape mode.MainActivity.javaNextActivity.javaMainActivity.javapackage com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { // declare button variable Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise button with id button = findViewById(R.id.b1); } // onClickListener attached to button // to send intent to next activity public void onClick(View v) { // Create instance of intent and // startActivity with intent object Intent intent = new Intent( MainActivity.this, NextActivity.class); startActivity(intent); }}NextActivity.javapackage com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} MainActivity.java: Java file for Main Activity, in which setOnClick() listener is attached to the button to launch next activity with different orientation.NextActivity.java: Java file for Next Activity which is in Landscape mode. MainActivity.java: Java file for Main Activity, in which setOnClick() listener is attached to the button to launch next activity with different orientation. NextActivity.java: Java file for Next Activity which is in Landscape mode. MainActivity.java NextActivity.java package com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { // declare button variable Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise button with id button = findViewById(R.id.b1); } // onClickListener attached to button // to send intent to next activity public void onClick(View v) { // Create instance of intent and // startActivity with intent object Intent intent = new Intent( MainActivity.this, NextActivity.class); startActivity(intent); }} package com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} Updating the AndroidManifest file: In AndroidManifest.xml file, add the screenOrientation state in activity along with its orientation. Here, we provide “portrait” orientation for MainActivity and “landscape” for NextActivity.Below is the code for AndroidManifest file:AndroidManifest.xmlAndroidManifest.xml<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.screenorientation"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <!-Define potrait orientation for Main activity--> <activity android:name="com.geeksforgeeks.screenorientation.MainActivity" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--Define landscape orientation for NextActivity--> <activity android:name=".NextActivity" android:screenOrientation="landscape"> </activity> </application> </manifest> Below is the code for AndroidManifest file: AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.screenorientation"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <!-Define potrait orientation for Main activity--> <activity android:name="com.geeksforgeeks.screenorientation.MainActivity" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--Define landscape orientation for NextActivity--> <activity android:name=".NextActivity" android:screenOrientation="landscape"> </activity> </application> </manifest> Output:Activity 1:Activity 2: Activity 1:Activity 2: Activity 1: Activity 2: Android-Misc Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Android RecyclerView in Kotlin CardView in Android With Example Content Providers in Android with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24409, "s": 24381, "text": "\n23 Feb, 2021" }, { "code": null, "e": 24607, "s": 24409, "text": "Screen Orientation, also known as screen rotation, is the attribute of activity element in android. When screen orientation change from one state to other, it is also known as configuration change." }, { "code": null, "e": 24726, "s": 24607, "text": "States of Screen orientationThere are various possible screen orientation states for any android application, such as:" }, { "code": null, "e": 24768, "s": 24726, "text": "ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE" }, { "code": null, "e": 24809, "s": 24768, "text": "ActivityInfo.SCREEN_ORIENTATION_PORTRAIT" }, { "code": null, "e": 24853, "s": 24809, "text": "ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED" }, { "code": null, "e": 24890, "s": 24853, "text": "ActivityInfo.SCREEN_ORIENTATION_USER" }, { "code": null, "e": 24929, "s": 24890, "text": "ActivityInfo.SCREEN_ORIENTATION_SENSOR" }, { "code": null, "e": 24968, "s": 24929, "text": "ActivityInfo.SCREEN_ORIENTATION_BEHIND" }, { "code": null, "e": 25009, "s": 24968, "text": "ActivityInfo.SCREEN_ORIENTATION_NOSENSOR" }, { "code": null, "e": 25058, "s": 25009, "text": "ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE" }, { "code": null, "e": 25106, "s": 25058, "text": "ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT" }, { "code": null, "e": 25155, "s": 25106, "text": "ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT" }, { "code": null, "e": 25244, "s": 25155, "text": "The initial orientation of the Screen has to be defined in the AndroidManifest.xml file." }, { "code": null, "e": 25252, "s": 25244, "text": "Syntax:" }, { "code": null, "e": 25272, "s": 25252, "text": "AndroidManifest.xml" }, { "code": "<activity android:name=\"package_name.Your_ActivityName\" android:screenOrientation=\"orientation_type\"> </activity> ", "e": 25394, "s": 25272, "text": null }, { "code": null, "e": 25403, "s": 25394, "text": "Example:" }, { "code": null, "e": 25454, "s": 25403, "text": " android:screenOrientation=\"orientation_type\">\n" }, { "code": null, "e": 25597, "s": 25454, "text": "How to change Screen orientation?Here is an example of an Android application that changes screen orientation for Landscape and Portrait mode." }, { "code": null, "e": 25660, "s": 25597, "text": "We will create two activities of different screen orientation." }, { "code": null, "e": 25717, "s": 25660, "text": "The first activity will be as “portrait” orientation and" }, { "code": null, "e": 25767, "s": 25717, "text": "Second activity as “landscape” orientation state." }, { "code": null, "e": 25795, "s": 25767, "text": "Step-by-Step demonstration:" }, { "code": null, "e": 28936, "s": 25795, "text": "Creating the activities: There will be two activities and hence two XML files, one for each activity.activity_main.xml: XML file for first activity consist of constraint layout with Button and Text View in it. This activity is in Landscape state.activity_next.xml: XML file for second activity consist of constraint layout with Text View in it. This activity is in Landscape state.Below is the code for both activities:activity_main.xmlactivity_next.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Constraint Layout--><android.support.constraint.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.geeksforgeeks.screenorientation.MainActivity\"> <!--Button to launch next activity with onClick--> <Button android:id=\"@+id/b1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Next Activity\" android:layout_marginTop=\"100dp\" android:onClick=\"onClick\" android:layout_marginBottom=\"10dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintVertical_bias=\"0.613\" app:layout_constraintHorizontal_bias=\"0.612\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/tv1\" /> <!--TextView --> <TextView android:text=\"Potrait orientation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"124dp\" android:textSize=\"25dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.502\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </android.support.constraint.ConstraintLayout> activity_next.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Constraint layout--> <android.support.constraint.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_height=\"match_parent\" android:layout_width=\"match_parent\" tools:context=\"com.geeksforgeeks.screenorientation.NextActivity\"> <!--TextView--> <TextView android:id=\"@+id/tv\" android:text=\"Landscape orientation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"170dp\" android:textSize=\"22dp\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.502\" app:layout_constraintTop_toTopOf=\"parent\" /> </android.support.constraint.ConstraintLayout> " }, { "code": null, "e": 29217, "s": 28936, "text": "activity_main.xml: XML file for first activity consist of constraint layout with Button and Text View in it. This activity is in Landscape state.activity_next.xml: XML file for second activity consist of constraint layout with Text View in it. This activity is in Landscape state." }, { "code": null, "e": 29363, "s": 29217, "text": "activity_main.xml: XML file for first activity consist of constraint layout with Button and Text View in it. This activity is in Landscape state." }, { "code": null, "e": 29499, "s": 29363, "text": "activity_next.xml: XML file for second activity consist of constraint layout with Text View in it. This activity is in Landscape state." }, { "code": null, "e": 29538, "s": 29499, "text": "Below is the code for both activities:" }, { "code": null, "e": 29556, "s": 29538, "text": "activity_main.xml" }, { "code": null, "e": 29574, "s": 29556, "text": "activity_next.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Constraint Layout--><android.support.constraint.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\"com.geeksforgeeks.screenorientation.MainActivity\"> <!--Button to launch next activity with onClick--> <Button android:id=\"@+id/b1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Next Activity\" android:layout_marginTop=\"100dp\" android:onClick=\"onClick\" android:layout_marginBottom=\"10dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintVertical_bias=\"0.613\" app:layout_constraintHorizontal_bias=\"0.612\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/tv1\" /> <!--TextView --> <TextView android:text=\"Potrait orientation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"124dp\" android:textSize=\"25dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.502\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </android.support.constraint.ConstraintLayout> ", "e": 31245, "s": 29574, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--Constraint layout--> <android.support.constraint.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_height=\"match_parent\" android:layout_width=\"match_parent\" tools:context=\"com.geeksforgeeks.screenorientation.NextActivity\"> <!--TextView--> <TextView android:id=\"@+id/tv\" android:text=\"Landscape orientation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"170dp\" android:textSize=\"22dp\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.502\" app:layout_constraintTop_toTopOf=\"parent\" /> </android.support.constraint.ConstraintLayout> ", "e": 32229, "s": 31245, "text": null }, { "code": null, "e": 33829, "s": 32229, "text": "Creating the Java file: There will be two activities and hence two Java files, one for each activity.MainActivity.java: Java file for Main Activity, in which setOnClick() listener is attached to the button to launch next activity with different orientation.NextActivity.java: Java file for Next Activity which is in Landscape mode.MainActivity.javaNextActivity.javaMainActivity.javapackage com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { // declare button variable Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise button with id button = findViewById(R.id.b1); } // onClickListener attached to button // to send intent to next activity public void onClick(View v) { // Create instance of intent and // startActivity with intent object Intent intent = new Intent( MainActivity.this, NextActivity.class); startActivity(intent); }}NextActivity.javapackage com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}" }, { "code": null, "e": 34060, "s": 33829, "text": "MainActivity.java: Java file for Main Activity, in which setOnClick() listener is attached to the button to launch next activity with different orientation.NextActivity.java: Java file for Next Activity which is in Landscape mode." }, { "code": null, "e": 34217, "s": 34060, "text": "MainActivity.java: Java file for Main Activity, in which setOnClick() listener is attached to the button to launch next activity with different orientation." }, { "code": null, "e": 34292, "s": 34217, "text": "NextActivity.java: Java file for Next Activity which is in Landscape mode." }, { "code": null, "e": 34310, "s": 34292, "text": "MainActivity.java" }, { "code": null, "e": 34328, "s": 34310, "text": "NextActivity.java" }, { "code": "package com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity;import android.content.Intent;import android.view.View;import android.widget.Button; public class MainActivity extends AppCompatActivity { // declare button variable Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise button with id button = findViewById(R.id.b1); } // onClickListener attached to button // to send intent to next activity public void onClick(View v) { // Create instance of intent and // startActivity with intent object Intent intent = new Intent( MainActivity.this, NextActivity.class); startActivity(intent); }}", "e": 35210, "s": 34328, "text": null }, { "code": "package com.geeksforgeeks.screenorientation; import android.support.v7.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}", "e": 35530, "s": 35210, "text": null }, { "code": null, "e": 36926, "s": 35530, "text": "Updating the AndroidManifest file: In AndroidManifest.xml file, add the screenOrientation state in activity along with its orientation. Here, we provide “portrait” orientation for MainActivity and “landscape” for NextActivity.Below is the code for AndroidManifest file:AndroidManifest.xmlAndroidManifest.xml<?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.screenorientation\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <!-Define potrait orientation for Main activity--> <activity android:name=\"com.geeksforgeeks.screenorientation.MainActivity\" android:screenOrientation=\"portrait\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <!--Define landscape orientation for NextActivity--> <activity android:name=\".NextActivity\" android:screenOrientation=\"landscape\"> </activity> </application> </manifest> " }, { "code": null, "e": 36970, "s": 36926, "text": "Below is the code for AndroidManifest file:" }, { "code": null, "e": 36990, "s": 36970, "text": "AndroidManifest.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.screenorientation\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <!-Define potrait orientation for Main activity--> <activity android:name=\"com.geeksforgeeks.screenorientation.MainActivity\" android:screenOrientation=\"portrait\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <!--Define landscape orientation for NextActivity--> <activity android:name=\".NextActivity\" android:screenOrientation=\"landscape\"> </activity> </application> </manifest> ", "e": 38079, "s": 36990, "text": null }, { "code": null, "e": 38109, "s": 38079, "text": "Output:Activity 1:Activity 2:" }, { "code": null, "e": 38132, "s": 38109, "text": "Activity 1:Activity 2:" }, { "code": null, "e": 38144, "s": 38132, "text": "Activity 1:" }, { "code": null, "e": 38156, "s": 38144, "text": "Activity 2:" }, { "code": null, "e": 38169, "s": 38156, "text": "Android-Misc" }, { "code": null, "e": 38177, "s": 38169, "text": "Android" }, { "code": null, "e": 38182, "s": 38177, "text": "Java" }, { "code": null, "e": 38187, "s": 38182, "text": "Java" }, { "code": null, "e": 38195, "s": 38187, "text": "Android" }, { "code": null, "e": 38293, "s": 38195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38302, "s": 38293, "text": "Comments" }, { "code": null, "e": 38315, "s": 38302, "text": "Old Comments" }, { "code": null, "e": 38373, "s": 38315, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 38416, "s": 38373, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 38447, "s": 38416, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 38480, "s": 38447, "text": "CardView in Android With Example" }, { "code": null, "e": 38522, "s": 38480, "text": "Content Providers in Android with Example" }, { "code": null, "e": 38537, "s": 38522, "text": "Arrays in Java" }, { "code": null, "e": 38581, "s": 38537, "text": "Split() String method in Java with examples" }, { "code": null, "e": 38603, "s": 38581, "text": "For-each loop in Java" }, { "code": null, "e": 38628, "s": 38603, "text": "Reverse a string in Java" } ]
Print pair with maximum AND value in an array in C Program.
According to the problem we are given an array of n positive integers, we have to find a pair with maximum AND value from the array. Input: arr[] = { 4, 8, 12, 16 } Output: pair = 8 12 The maximum and value= 8 Input:arr[] = { 4, 8, 16, 2 } Output: pair = No possible AND The maximum and value = 0 For finding Maximum AND value is similar to find out Maximum AND value in an array. Program must find out the pair of elements resulting in obtained AND value. For finding the elements, simply traverse the whole array and find the AND value of each element with the obtained maximum AND value (result) and if arr[i] & result == result, that means arr[i] is the element which will generate maximum AND value. Also, in the case if maximum AND value (result) is zero then we should print “Not possible” in that case. int checkBit(int pattern, int arr[], int n) START STEP 1: DECLARE AND INITIALIZE count AS 0 STEP 2: LOOP FOR i = 0 AND i < n AND i++ IF (pattern & arr[i]) == pattern THEN, INCREMENT count BY 1 STEP 3: RETURN count STOP int maxAND(int arr[], int n) START STEP 1: DECLARE AND INITIALIZE res = 0 AND count STEP 2: LOOP FOR bit = 31 AND bit >= 0 AND bit-- count = GOTO FUNCTION checkBit(res | (1 << bit), arr,n) IF count >= 2 THEN, res |= (1 << bit); END IF IF res == 0 PRINT "no possible AND” ELSE PRINT "Pair with maximum AND= " count = 0; LOOP FOR int i = 0 AND i < n && count < 2 AND i++ IF (arr[i] & res) == res THEN, INCREMENT count BY 1 PRINT arr[i] END IF END FOR END FOR RETURN res STOP #include <stdio.h> int checkBit(int pattern, int arr[], int n){ int count = 0; for (int i = 0; i < n; i++) if ((pattern & arr[i]) == pattern) count++; return count; } // Function for finding maximum AND value pair int maxAND(int arr[], int n){ int res = 0, count; for (int bit = 31; bit >= 0; bit--) { count = checkBit(res | (1 << bit), arr, n); if (count >= 2) res |= (1 << bit); } if (res == 0) //if there is no pair available printf("no possible and\n"); else { //Printing the pair available printf("Pair with maximum AND= "); count = 0; for (int i = 0; i < n && count < 2; i++) { // incremnent count value after // printing element if ((arr[i] & res) == res) { count++; printf("%d ", arr[i]); } } } return res; } int main(int argc, char const *argv[]){ int arr[] = {5, 6, 2, 8, 9, 12}; int n = sizeof(arr)/sizeof(arr[0]); int ma = maxAND(arr, n); printf("\nThe maximum AND value= %d ", ma); return 0; } If we run the above program then it will generate the following output − pair = 8 9 The maximum and value= 8
[ { "code": null, "e": 1195, "s": 1062, "text": "According to the problem we are given an array of n positive integers, we have to find a pair with maximum AND value from the array." }, { "code": null, "e": 1360, "s": 1195, "text": "Input: arr[] = { 4, 8, 12, 16 }\nOutput: pair = 8 12\nThe maximum and value= 8\n\nInput:arr[] = { 4, 8, 16, 2 }\nOutput: pair = No possible AND\nThe maximum and value = 0" }, { "code": null, "e": 1874, "s": 1360, "text": "For finding Maximum AND value is similar to find out Maximum AND value in an array. Program must find out the pair of elements resulting in obtained AND value. For finding the elements, simply traverse the whole array and find the AND value of each element with the obtained maximum AND value (result) and if arr[i] & result == result, that means arr[i] is the element which will generate maximum AND value. Also, in the case if maximum AND value (result) is zero then we should print “Not possible” in that case." }, { "code": null, "e": 2647, "s": 1874, "text": "int checkBit(int pattern, int arr[], int n)\nSTART\nSTEP 1: DECLARE AND INITIALIZE count AS 0\nSTEP 2: LOOP FOR i = 0 AND i < n AND i++\n IF (pattern & arr[i]) == pattern THEN,\n INCREMENT count BY 1\nSTEP 3: RETURN count\nSTOP\nint maxAND(int arr[], int n)\nSTART\nSTEP 1: DECLARE AND INITIALIZE res = 0 AND count\nSTEP 2: LOOP FOR bit = 31 AND bit >= 0 AND bit--\n count = GOTO FUNCTION checkBit(res | (1 << bit), arr,n)\n IF count >= 2 THEN,\n res |= (1 << bit);\n END IF\n IF res == 0\n PRINT \"no possible AND”\n ELSE\n PRINT \"Pair with maximum AND= \"\n count = 0;\n LOOP FOR int i = 0 AND i < n && count < 2 AND i++\n IF (arr[i] & res) == res THEN,\n INCREMENT count BY 1\n PRINT arr[i]\n END IF\n END FOR\nEND FOR\nRETURN res\nSTOP" }, { "code": null, "e": 3727, "s": 2647, "text": "#include <stdio.h>\nint checkBit(int pattern, int arr[], int n){\n int count = 0;\n for (int i = 0; i < n; i++)\n if ((pattern & arr[i]) == pattern)\n count++;\n return count;\n}\n// Function for finding maximum AND value pair\nint maxAND(int arr[], int n){\n int res = 0, count;\n for (int bit = 31; bit >= 0; bit--) {\n count = checkBit(res | (1 << bit), arr, n); \n if (count >= 2)\n res |= (1 << bit);\n }\n if (res == 0) //if there is no pair available\n printf(\"no possible and\\n\");\n else { //Printing the pair available\n printf(\"Pair with maximum AND= \");\n count = 0;\n for (int i = 0; i < n && count < 2; i++) {\n // incremnent count value after\n // printing element\n if ((arr[i] & res) == res) {\n count++;\n printf(\"%d \", arr[i]);\n }\n }\n }\n return res;\n}\nint main(int argc, char const *argv[]){\n int arr[] = {5, 6, 2, 8, 9, 12};\n int n = sizeof(arr)/sizeof(arr[0]);\n int ma = maxAND(arr, n);\n printf(\"\\nThe maximum AND value= %d \", ma);\n return 0;\n}" }, { "code": null, "e": 3800, "s": 3727, "text": "If we run the above program then it will generate the following output −" }, { "code": null, "e": 3836, "s": 3800, "text": "pair = 8 9\nThe maximum and value= 8" } ]
Explain Stack in Python with examples
A stack is a linear data structure that works on the Last In First Out mechanism(LIFO). The element which enters first in the stack is the last to be processed. The stack data structure can be understood with the help of the example of a stack of dishes. The dishes are piled up one upon the another. The first plate or dish is at the bottom of the pile and the last dish placed is on the top of the pile or stack. Whenever we need a plate, we will pick up the plate at the top of the stack which is the plate inserted or placed at the last. The plate which was placed first will be the last one to be picked up. Thus, the LAST IN FIRST OUT mechanism is followed. The Stack in Python can be implemented in various ways using other linear data structures or in-built modules in Python library. The stack in Python can be implemented using list. But, using list to implement stack is not much efficient and hence not recommended. append() − This function adds an element at the end of the stack. pop() − This function removes and returns the last or the top element in the stack.This function pops the elements in LIFO order. Live Demo stack=[] stack.append(1) stack.append(2) stack.append(3) print("Intial Stack",stack) print("Element popped from the stack") print(stack.pop()) print(stack.pop()) print("Stack after popping some elements",stack) Intial Stack [1, 2, 3] Element popped from the stack 3 2 Stack after popping some elements [1] You can’t remove more elements once the stack is empty. Doing so results in exception. stack.pop() IndexError: pop from empty list This is the way to implement stack using inbuilt module from python. We need to import LifoQueue from queue. We can initialize LifoQueue or stack with some specific size . A size of zero means an infinite stack. maxsize − maximum number of elements allowed in a stack get() − remove and return the last or top element from the stack.If stack is empty, wait until stack has atleast one element. get_nowait() − remove and return the last element from the stack.If stack is empty, raise an exception. put(item) − append an element at the end of the stack.If stack is full, wait until a free slot is availabe. put_nowait(item) − append an element at the end of the stack.If stack is full, raise an exception. full() − returns true if the stack is full, else return false. empty() − return True if the stack is empty, else false qsize() − returns the number of elements present in the stack Live Demo from queue import LifoQueue s=LifoQueue(maxsize=3) s.put(1) s.put(2) s.put(3) print("Is stack full",s.full()) print("Element popped from the stack") print(s.get()) print(s.get()) print("Number of elements in stack",s.qsize()) print("Is stack empty",s.empty()) Is stack full True Element popped from the stack 3 2 Number of elements in stack 1 Is stack empty False This is another way to implement stack in Python. We need to import deque from collections module. append() − This function adds an element at the end of the stack. pop() − This function removes and returns the last element in the stack in O(1) time complexity. Live Demo from collections import deque stack=deque() stack.append(1) stack.append(2) stack.append(3) print("Intial stack: ",stack) print("Element popped from the stack") print(stack.pop()) print(stack.pop()) print("Stack after popping some elements: ",stack) Intial stack: deque([1, 2, 3]) Element popped from the stack 3 2 Stack after popping some elements: deque([1]) Using pop() function on an empty deque will raise an exception.
[ { "code": null, "e": 1223, "s": 1062, "text": "A stack is a linear data structure that works on the Last In First Out mechanism(LIFO). The element which enters first in the stack is the last to be processed." }, { "code": null, "e": 1317, "s": 1223, "text": "The stack data structure can be understood with the help of the example of a stack of dishes." }, { "code": null, "e": 1726, "s": 1317, "text": "The dishes are piled up one upon the another. The first plate or dish is at the bottom of the pile and the last dish placed is on the top of the pile or stack. Whenever we need a plate, we will pick up the plate at the top of the stack which is the plate inserted or placed at the last. The plate which was placed first will be the last one to be picked up. Thus, the LAST IN FIRST OUT mechanism is followed." }, { "code": null, "e": 1855, "s": 1726, "text": "The Stack in Python can be implemented in various ways using other linear data structures or in-built modules in Python library." }, { "code": null, "e": 1990, "s": 1855, "text": "The stack in Python can be implemented using list. But, using list to implement stack is not much efficient and hence not recommended." }, { "code": null, "e": 2056, "s": 1990, "text": "append() − This function adds an element at the end of the stack." }, { "code": null, "e": 2186, "s": 2056, "text": "pop() − This function removes and returns the last or the top element in the stack.This function pops the elements in LIFO order." }, { "code": null, "e": 2197, "s": 2186, "text": " Live Demo" }, { "code": null, "e": 2408, "s": 2197, "text": "stack=[]\nstack.append(1)\nstack.append(2)\nstack.append(3)\nprint(\"Intial Stack\",stack)\nprint(\"Element popped from the stack\")\nprint(stack.pop())\nprint(stack.pop())\nprint(\"Stack after popping some elements\",stack)" }, { "code": null, "e": 2503, "s": 2408, "text": "Intial Stack [1, 2, 3]\nElement popped from the stack\n3\n2\nStack after popping some elements [1]" }, { "code": null, "e": 2590, "s": 2503, "text": "You can’t remove more elements once the stack is empty. Doing so results in exception." }, { "code": null, "e": 2634, "s": 2590, "text": "stack.pop()\nIndexError: pop from empty list" }, { "code": null, "e": 2846, "s": 2634, "text": "This is the way to implement stack using inbuilt module from python. We need to import LifoQueue from queue. We can initialize LifoQueue or stack with some specific size . A size of zero means an infinite stack." }, { "code": null, "e": 2902, "s": 2846, "text": "maxsize − maximum number of elements allowed in a stack" }, { "code": null, "e": 3028, "s": 2902, "text": "get() − remove and return the last or top element from the stack.If stack is empty, wait until stack has atleast one element." }, { "code": null, "e": 3132, "s": 3028, "text": "get_nowait() − remove and return the last element from the stack.If stack is empty, raise an exception." }, { "code": null, "e": 3240, "s": 3132, "text": "put(item) − append an element at the end of the stack.If stack is full, wait until a free slot is availabe." }, { "code": null, "e": 3339, "s": 3240, "text": "put_nowait(item) − append an element at the end of the stack.If stack is full, raise an exception." }, { "code": null, "e": 3402, "s": 3339, "text": "full() − returns true if the stack is full, else return false." }, { "code": null, "e": 3458, "s": 3402, "text": "empty() − return True if the stack is empty, else false" }, { "code": null, "e": 3520, "s": 3458, "text": "qsize() − returns the number of elements present in the stack" }, { "code": null, "e": 3531, "s": 3520, "text": " Live Demo" }, { "code": null, "e": 3791, "s": 3531, "text": "from queue import LifoQueue\ns=LifoQueue(maxsize=3)\ns.put(1)\ns.put(2)\ns.put(3)\nprint(\"Is stack full\",s.full())\nprint(\"Element popped from the stack\")\nprint(s.get())\nprint(s.get())\nprint(\"Number of elements in stack\",s.qsize())\nprint(\"Is stack empty\",s.empty())" }, { "code": null, "e": 3895, "s": 3791, "text": "Is stack full True\nElement popped from the stack\n3\n2\nNumber of elements in stack 1\nIs stack empty False" }, { "code": null, "e": 3994, "s": 3895, "text": "This is another way to implement stack in Python. We need to import deque from collections module." }, { "code": null, "e": 4060, "s": 3994, "text": "append() − This function adds an element at the end of the stack." }, { "code": null, "e": 4157, "s": 4060, "text": "pop() − This function removes and returns the last element in the stack in O(1) time complexity." }, { "code": null, "e": 4168, "s": 4157, "text": " Live Demo" }, { "code": null, "e": 4418, "s": 4168, "text": "from collections import deque\nstack=deque()\nstack.append(1)\nstack.append(2)\nstack.append(3)\nprint(\"Intial stack: \",stack)\nprint(\"Element popped from the stack\")\nprint(stack.pop())\nprint(stack.pop())\nprint(\"Stack after popping some elements: \",stack)" }, { "code": null, "e": 4529, "s": 4418, "text": "Intial stack: deque([1, 2, 3])\nElement popped from the stack\n3\n2\nStack after popping some elements: deque([1])" }, { "code": null, "e": 4593, "s": 4529, "text": "Using pop() function on an empty deque will raise an exception." } ]
Distance between centers of two intersecting circles if the radii and common chord length is given - GeeksforGeeks
05 Nov, 2021 Given are two circles, with given radii, which intersect each other and have a common chord. The length of the common chord is given. The task is to find the distance between the center of the two circles. Examples: Input: r1 = 24, r2 = 37, x = 40 Output: 44 Input: r1 = 14, r2 = 7, x = 10 Output: 17 Approach: let the length of common chord AB = x Let the radius of the circle with center O is OA = r2 Radius of circle with center P is AP = r1 From the figure, OP is perpendicular ABAC = CBAC = x/2 (Since AB = x) In triangle ACP,AP^2 = PC^2+ AC^2 [By Pythagoras theorem]r1^2 = PC^2 + (x/2)^2PC^2 = r1^2 – x^2/4 Consider triangle ACOr2^2 = OC^2+ AC^2[By Pythagoras theorem]r2^2 = OC^2+ (x/2)^2OC^2 = r2^2 – x^2/4 From the figure, OP = OC + PCOP = √( r1^2 – x^2/4 ) + √(r2^2 – x^2/4)Distance between the centers = sqrt((radius of one circle)^2 – (half of the length of the common chord )^2) + sqrt((radius of the second circle)^2 – (half of the length of the common chord )^2)Below is the implementation of the above approach:C++JavaPython3C#C++// C++ program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is given #include <bits/stdc++.h>using namespace std; void distcenter(int r1, int r2, int x){ int z = sqrt((r1 * r1) - (x / 2 * x / 2)) + sqrt((r2 * r2) - (x / 2 * x / 2)); cout << "distance between the" << " centers is " << z << endl;} // Driver codeint main(){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x); return 0;}Java// Java program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenimport java.lang.Math; import java.io.*; class GFG { static double distcenter(int r1, int r2, int x){ double z = (Math.sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.sqrt((r2 * r2) - (x / 2 * x / 2))); System.out.println ("distance between the" + " centers is "+ (int)z ); return 0;} // Driver codepublic static void main (String[] args) { int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_t.Python3 # Python program to find# the distance between centers# of two intersecting circles# if the radii and common chord length is given def distcenter(r1, r2, x): z = (((r1 * r1) - (x / 2 * x / 2))**(1/2)) +\ (((r2 * r2)- (x / 2 * x / 2))**(1/2)); print("distance between thecenters is ",end=""); print(int(z)); # Driver coder1 = 24; r2 = 37; x = 40;distcenter(r1, r2, x); # This code has been contributed by 29AjayKumarC#// C# program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenusing System; class GFG{ static double distcenter(int r1, int r2, int x){ double z = (Math.Sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.Sqrt((r2 * r2) - (x / 2 * x / 2))); Console.WriteLine("distance between the" + " centers is "+ (int)z ); return 0;} // Driver codestatic public void Main (){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_tOutput:distance between the centers is 44 My Personal Notes arrow_drop_upSave Distance between the centers = sqrt((radius of one circle)^2 – (half of the length of the common chord )^2) + sqrt((radius of the second circle)^2 – (half of the length of the common chord )^2) Below is the implementation of the above approach: C++ Java Python3 C# // C++ program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is given #include <bits/stdc++.h>using namespace std; void distcenter(int r1, int r2, int x){ int z = sqrt((r1 * r1) - (x / 2 * x / 2)) + sqrt((r2 * r2) - (x / 2 * x / 2)); cout << "distance between the" << " centers is " << z << endl;} // Driver codeint main(){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x); return 0;} // Java program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenimport java.lang.Math; import java.io.*; class GFG { static double distcenter(int r1, int r2, int x){ double z = (Math.sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.sqrt((r2 * r2) - (x / 2 * x / 2))); System.out.println ("distance between the" + " centers is "+ (int)z ); return 0;} // Driver codepublic static void main (String[] args) { int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_t. # Python program to find# the distance between centers# of two intersecting circles# if the radii and common chord length is given def distcenter(r1, r2, x): z = (((r1 * r1) - (x / 2 * x / 2))**(1/2)) +\ (((r2 * r2)- (x / 2 * x / 2))**(1/2)); print("distance between thecenters is ",end=""); print(int(z)); # Driver coder1 = 24; r2 = 37; x = 40;distcenter(r1, r2, x); # This code has been contributed by 29AjayKumar // C# program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenusing System; class GFG{ static double distcenter(int r1, int r2, int x){ double z = (Math.Sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.Sqrt((r2 * r2) - (x / 2 * x / 2))); Console.WriteLine("distance between the" + " centers is "+ (int)z ); return 0;} // Driver codestatic public void Main (){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_t distance between the centers is 44 jit_t 29AjayKumar chhabradhanvi Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26807, "s": 26779, "text": "\n05 Nov, 2021" }, { "code": null, "e": 27013, "s": 26807, "text": "Given are two circles, with given radii, which intersect each other and have a common chord. The length of the common chord is given. The task is to find the distance between the center of the two circles." }, { "code": null, "e": 27023, "s": 27013, "text": "Examples:" }, { "code": null, "e": 27111, "s": 27023, "text": "Input: r1 = 24, r2 = 37, x = 40\nOutput: 44\n\nInput: r1 = 14, r2 = 7, x = 10\nOutput: 17\n" }, { "code": null, "e": 27121, "s": 27111, "text": "Approach:" }, { "code": null, "e": 27159, "s": 27121, "text": "let the length of common chord AB = x" }, { "code": null, "e": 27213, "s": 27159, "text": "Let the radius of the circle with center O is OA = r2" }, { "code": null, "e": 27255, "s": 27213, "text": "Radius of circle with center P is AP = r1" }, { "code": null, "e": 27325, "s": 27255, "text": "From the figure, OP is perpendicular ABAC = CBAC = x/2 (Since AB = x)" }, { "code": null, "e": 27423, "s": 27325, "text": "In triangle ACP,AP^2 = PC^2+ AC^2 [By Pythagoras theorem]r1^2 = PC^2 + (x/2)^2PC^2 = r1^2 – x^2/4" }, { "code": null, "e": 27524, "s": 27423, "text": "Consider triangle ACOr2^2 = OC^2+ AC^2[By Pythagoras theorem]r2^2 = OC^2+ (x/2)^2OC^2 = r2^2 – x^2/4" }, { "code": null, "e": 30169, "s": 27524, "text": "From the figure, OP = OC + PCOP = √( r1^2 – x^2/4 ) + √(r2^2 – x^2/4)Distance between the centers = sqrt((radius of one circle)^2 – (half of the length of the common chord )^2) + sqrt((radius of the second circle)^2 – (half of the length of the common chord )^2)Below is the implementation of the above approach:C++JavaPython3C#C++// C++ program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is given #include <bits/stdc++.h>using namespace std; void distcenter(int r1, int r2, int x){ int z = sqrt((r1 * r1) - (x / 2 * x / 2)) + sqrt((r2 * r2) - (x / 2 * x / 2)); cout << \"distance between the\" << \" centers is \" << z << endl;} // Driver codeint main(){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x); return 0;}Java// Java program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenimport java.lang.Math; import java.io.*; class GFG { static double distcenter(int r1, int r2, int x){ double z = (Math.sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.sqrt((r2 * r2) - (x / 2 * x / 2))); System.out.println (\"distance between the\" + \" centers is \"+ (int)z ); return 0;} // Driver codepublic static void main (String[] args) { int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_t.Python3 # Python program to find# the distance between centers# of two intersecting circles# if the radii and common chord length is given def distcenter(r1, r2, x): z = (((r1 * r1) - (x / 2 * x / 2))**(1/2)) +\\ (((r2 * r2)- (x / 2 * x / 2))**(1/2)); print(\"distance between thecenters is \",end=\"\"); print(int(z)); # Driver coder1 = 24; r2 = 37; x = 40;distcenter(r1, r2, x); # This code has been contributed by 29AjayKumarC#// C# program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenusing System; class GFG{ static double distcenter(int r1, int r2, int x){ double z = (Math.Sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.Sqrt((r2 * r2) - (x / 2 * x / 2))); Console.WriteLine(\"distance between the\" + \" centers is \"+ (int)z ); return 0;} // Driver codestatic public void Main (){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_tOutput:distance between the centers is 44\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30363, "s": 30169, "text": "Distance between the centers = sqrt((radius of one circle)^2 – (half of the length of the common chord )^2) + sqrt((radius of the second circle)^2 – (half of the length of the common chord )^2)" }, { "code": null, "e": 30414, "s": 30363, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30418, "s": 30414, "text": "C++" }, { "code": null, "e": 30423, "s": 30418, "text": "Java" }, { "code": null, "e": 30431, "s": 30423, "text": "Python3" }, { "code": null, "e": 30434, "s": 30431, "text": "C#" }, { "code": "// C++ program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is given #include <bits/stdc++.h>using namespace std; void distcenter(int r1, int r2, int x){ int z = sqrt((r1 * r1) - (x / 2 * x / 2)) + sqrt((r2 * r2) - (x / 2 * x / 2)); cout << \"distance between the\" << \" centers is \" << z << endl;} // Driver codeint main(){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x); return 0;}", "e": 30965, "s": 30434, "text": null }, { "code": "// Java program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenimport java.lang.Math; import java.io.*; class GFG { static double distcenter(int r1, int r2, int x){ double z = (Math.sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.sqrt((r2 * r2) - (x / 2 * x / 2))); System.out.println (\"distance between the\" + \" centers is \"+ (int)z ); return 0;} // Driver codepublic static void main (String[] args) { int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_t.", "e": 31615, "s": 30965, "text": null }, { "code": " # Python program to find# the distance between centers# of two intersecting circles# if the radii and common chord length is given def distcenter(r1, r2, x): z = (((r1 * r1) - (x / 2 * x / 2))**(1/2)) +\\ (((r2 * r2)- (x / 2 * x / 2))**(1/2)); print(\"distance between thecenters is \",end=\"\"); print(int(z)); # Driver coder1 = 24; r2 = 37; x = 40;distcenter(r1, r2, x); # This code has been contributed by 29AjayKumar", "e": 32054, "s": 31615, "text": null }, { "code": "// C# program to find// the distance between centers// of two intersecting circles// if the radii and common chord length is givenusing System; class GFG{ static double distcenter(int r1, int r2, int x){ double z = (Math.Sqrt((r1 * r1) - (x / 2 * x / 2))) + (Math.Sqrt((r2 * r2) - (x / 2 * x / 2))); Console.WriteLine(\"distance between the\" + \" centers is \"+ (int)z ); return 0;} // Driver codestatic public void Main (){ int r1 = 24, r2 = 37, x = 40; distcenter(r1, r2, x);}} // This code is contributed by jit_t", "e": 32661, "s": 32054, "text": null }, { "code": null, "e": 32697, "s": 32661, "text": "distance between the centers is 44\n" }, { "code": null, "e": 32703, "s": 32697, "text": "jit_t" }, { "code": null, "e": 32715, "s": 32703, "text": "29AjayKumar" }, { "code": null, "e": 32729, "s": 32715, "text": "chhabradhanvi" }, { "code": null, "e": 32739, "s": 32729, "text": "Geometric" }, { "code": null, "e": 32752, "s": 32739, "text": "Mathematical" }, { "code": null, "e": 32765, "s": 32752, "text": "Mathematical" }, { "code": null, "e": 32775, "s": 32765, "text": "Geometric" }, { "code": null, "e": 32873, "s": 32775, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32922, "s": 32873, "text": "Program for distance between two points on earth" }, { "code": null, "e": 32975, "s": 32922, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 33026, "s": 32975, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 33060, "s": 33026, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 33118, "s": 33060, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 33148, "s": 33118, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33208, "s": 33148, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33223, "s": 33208, "text": "C++ Data Types" }, { "code": null, "e": 33266, "s": 33223, "text": "Set in C++ Standard Template Library (STL)" } ]
Apache HttpClient - Quick Guide
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web (i.e., Internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extensions of its request methods, error codes, and headers. Basically, HTTP is a TCP/IP based communication protocol, that is used to deliver data (HTML files, image files, query results, etc.) on the World Wide Web. The default port is TCP 80, but other ports can be used as well. It provides a standardized way for computers to communicate with each other. HTTP specification defines how clients' request data will be constructed and sent to the server, and how the servers respond to these requests. Http client is a transfer library, it resides on the client side, sends and receives HTTP messages. It provides up to date, feature-rich and, efficient implementation which meets the recent HTTP standards. In addition to this using client library, one can build HTTP based applications such as web browsers, web service clients, etc. Following are the prominent features of Http client − HttpClient library implements all the available HTTP methods. HttpClient library implements all the available HTTP methods. HttpClient library provides APIs to secure the requests using the Secure Socket Layer protocol. HttpClient library provides APIs to secure the requests using the Secure Socket Layer protocol. Using HttpClient, you can establish connections using proxies. Using HttpClient, you can establish connections using proxies. You can authenticate connections using authentication schemes such as Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session etc. You can authenticate connections using authentication schemes such as Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session etc. HttpClient library supports sending requests through multiple threads. It manages multiple connections established from various threads using ClientConnectionPoolManager. HttpClient library supports sending requests through multiple threads. It manages multiple connections established from various threads using ClientConnectionPoolManager. Using Apache HttpClient library, you can set connection timeouts. Using Apache HttpClient library, you can set connection timeouts. In this chapter, we will explain how to set an environment for HttpClient in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse. For more information on Eclipse, please refer to our Eclipse Tutorial. Open the official homepage of the HttpClient (components) website and go to the download page Then, download the latest stable version of HttpClient. Here, throughout the tutorial, we are using the version 4.5.6 hence download the file 4.5.6.zip. Within the downloaded folder, you will find a folder named lib and this contains the required Jar files that are to be added in the classpath of your project, to work with HttpClient. Open eclipse and create a sample project. Right click on the project select the option Build Path → Configure Build Path as shown below. In the Java Build Path frame in the Libraries tab, click on Add External JARs. And select all the jar files in the lib folder and, click on Apply and Close. You are all set to work with HttpClient library in eclipse. The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. The HttpClient API provides a class named HttpGet which represents the get request method. Follow the steps given below to send a get request using HttpClient library The createDefault() method of the HttpClients class returns a CloseableHttpClient object, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object as shown below − CloseableHttpClient httpclient = HttpClients.createDefault(); The HttpGet class represents the HTTPGET request which retrieves the information of the given server using a URI. Create a HTTP GET request by instantiating this class. The constructor of this class accepts a String value representing the URI. HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/"); The execute() method of the CloseableHttpClient class accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object. Execute the request using this method as shown below − HttpResponse httpresponse = httpclient.execute(httpget); Following is an example which demonstrates the execution of the HTTP GET request using HttpClient library. import java.util.Scanner; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpGetExample { public static void main(String args[]) throws Exception{ //Creating a HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating a HttpGet object HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/ "); //Printing the method used System.out.println("Request Type: "+httpget.getMethod()); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); Scanner sc = new Scanner(httpresponse.getEntity().getContent()); //Printing the status line System.out.println(httpresponse.getStatusLine()); while(sc.hasNext()) { System.out.println(sc.nextLine()); } } } The above program generates the following output − Request Type: GET <!DOCTYPE html> <!--[if IE 8]><html class = "ie ie8"> <![endif]--> <!--[if IE 9]><html class = "ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html lang = "en-US"> <!--<![endif]--> <head> <!-- Basic --> <meta charset = "utf-8"> <title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Apache Commons Collections</title> <meta name = "Description" content = "Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC), Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/> <meta name = "Keywords" content = "Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson, TestLink, Inter Process Communication (IPC), Logo"/> <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> <meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes"> <link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css" rel = "stylesheet" type = "text/css" /> <link rel = "stylesheet" href="/questions/css/home.css?v = 3" /> <script src = "/questions/js/jquery.min.js"></script> <script src = "/questions/js/fontawesome.js"></script> <script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </script> </body> </html> A POST request is used to send data to the server; for example, customer information, file upload, etc., using HTML forms. The HttpClient API provides a class named HttpPost which represents the POST request. Follow the steps given below to send a HTTP POST request using HttpClient library. The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object. CloseableHttpClient httpClient = HttpClients.createDefault(); The HttpPost class represents the HTTP POST request. This sends required data and retrieves the information of the given server using a URI. Create this request by instantiating the HttpPost class and pass a string value representing the URI, as a parameter to its constructor. HttpGet httpGet = new HttpGet("http://www.tutorialspoint.com/"); The execute() method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object. HttpResponse httpResponse = httpclient.execute(httpget); Following is an example which demonstrates the execution of the HTTP POST request using HttpClient library. import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpPostExample { public static void main(String args[]) throws Exception{ //Creating a HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating a HttpGet object HttpPost httppost = new HttpPost("https://www.tutorialspoint.com/"); //Printing the method used System.out.println("Request Type: "+httppost.getMethod()); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httppost); Scanner sc = new Scanner(httpresponse.getEntity().getContent()); //Printing the status line System.out.println(httpresponse.getStatusLine()); while(sc.hasNext()) { System.out.println(sc.nextLine()); } } } The above program generates the following output. Request Type: POST <!DOCTYPE html> <!--[if IE 8]><html class = "ie ie8"> <![endif]--> <!--[if IE 9]><html class = "ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html lang = "en-US"> <!--<![endif]--> <head> <!-- Basic --> <meta charset = "utf-8"> <title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Apache Commons Collections</title> <meta name = "Description" content = "Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC), Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/> <meta name = "Keywords" content="Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson, TestLink, Inter Process Communication (IPC), Logo"/> <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> <meta name = "viewport" conten t= "width = device-width,initial-scale = 1.0,userscalable = yes"> <link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css" rel = "stylesheet" type = "text/css" /> <link rel = "stylesheet" href = "/questions/css/home.css?v = 3" /> <script src = "/questions/js/jquery.min.js"></script> <script src = "/questions/js/fontawesome.js"></script> <script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </script> </body> </html> Processing the HTTP responses using the response handlers is recommended. In this chapter, we are going to discuss how to create response handlers and how to use them to process a response. If you use the response handler, all the HTTP connections will be released automatically. The HttpClient API provides an interface known as ResponseHandler in the package org.apache.http.client. In order to create a response handler, implement this interface and override its handleResponse() method. Every response has a status code and if the status code is in between 200 and 300, that means the action was successfully received, understood, and accepted. Therefore, in our example, we will handle the entities of the responses with such status codes. Follow the steps given below to execute the request using a response handler. The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method create an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); Instantiate the response handler object created above using the following line of code − ResponseHandler<String> responseHandler = new MyResponseHandler(); The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI. Create an HttpGet request by instantiating the HttpGet class and by passing a string representing the URI as a parameter to its constructor. ResponseHandler<String> responseHandler = new MyResponseHandler(); The CloseableHttpClient class has a variant of execute() method which accepts two objects ResponseHandler and HttpUriRequest, and returns a response object. String httpResponse = httpclient.execute(httpget, responseHandler); Following example demonstrates the usage of response handlers. import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; class MyResponseHandler implements ResponseHandler<String>{ public String handleResponse(final HttpResponse response) throws IOException{ //Get the status of the response int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); if(entity == null) { return ""; } else { return EntityUtils.toString(entity); } } else { return ""+status; } } } public class ResponseHandlerExample { public static void main(String args[]) throws Exception{ //Create an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //instantiate the response handler ResponseHandler<String> responseHandler = new MyResponseHandler(); //Create an HttpGet object HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/"); //Execute the Get request by passing the response handler object and HttpGet object String httpresponse = httpclient.execute(httpget, responseHandler); System.out.println(httpresponse); } } The above programs generate the following output − <!DOCTYPE html> <!--[if IE 8]><html class = "ie ie8"> <![endif]--> <!--[if IE 9]><html class = "ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html lang = "en-US"> <!--<![endif]--> <head> <!-- Basic --> <meta charset = "utf-8"> <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> <meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes"> <link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css" rel = "stylesheet" type = "text/css" /> <link rel = "stylesheet" href = "/questions/css/home.css?v = 3" /> <script src = "/questions/js/jquery.min.js"></script> <script src = "/questions/js/fontawesome.js"></script> <script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . <script> window.dataLayer = window.dataLayer || []; function gtag() {dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-232293-17'); </script> </body> If you are processing HTTP responses manually instead of using a response handler, you need to close all the http connections by yourself. This chapter explains how to close the connections manually. While closing HTTP connections manually follow the steps given below − The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object as shown below − CloseableHttpClient httpClient = HttpClients.createDefault(); Start a try-finally block, write the remaining code in the programs in the try block and close the CloseableHttpClient object in the finally block. CloseableHttpClient httpClient = HttpClients.createDefault(); try{ //Remaining code . . . . . . . . . . . . . . . }finally{ httpClient.close(); } The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI. Create a HTTP GET request by instantiating the HttpGet class by passing a string representing the URI. HttpGet httpGet = new HttpGet("http://www.tutorialspoint.com/"); The execute() method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object. Execute the request using the given method − HttpResponse httpResponse = httpclient.execute(httpGet); Start another try-finally block (nested within the previous try-finally), write the remaining code in the programs in this try block and close the HttpResponse object in the finally block. CloseableHttpClient httpclient = HttpClients.createDefault(); try{ . . . . . . . . . . . . . . CloseableHttpResponse httpresponse = httpclient.execute(httpget); try{ . . . . . . . . . . . . . . }finally{ httpresponse.close(); } }finally{ httpclient.close(); } Whenever you create/obtain objects such as request, response stream, etc., start a try finally block in the next line, write the remaining code within the try and close the respective object in the finally block as demonstrated in the following program − import java.util.Scanner; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class CloseConnectionExample { public static void main(String args[])throws Exception{ //Create an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); try{ //Create an HttpGet object HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/"); //Execute the Get request CloseableHttpResponse httpresponse = httpclient.execute(httpget); try{ Scanner sc = new Scanner(httpresponse.getEntity().getContent()); while(sc.hasNext()) { System.out.println(sc.nextLine()); } }finally{ httpresponse.close(); } }finally{ httpclient.close(); } } } On executing the above program, the following output is generated − <!DOCTYPE html> <!--[if IE 8]><html class = "ie ie8"> <![endif]--> <!--[if IE 9]><html class = "ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html lang = "en-US"> <!--<![endif]--> <head> <!-- Basic --> <meta charset = "utf-8"> <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> <meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes"> <link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css" rel = "stylesheet" type = "text/css" /> <link rel = "stylesheet" href = "/questions/css/home.css?v = 3" /> <script src = "/questions/js/jquery.min.js"></script> <script src = "/questions/js/fontawesome.js"></script> <script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . <script> window.dataLayer = window.dataLayer || []; function gtag() {dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-232293-17'); </script> </body> </html> You can abort the current HTTP request using the abort() method, i.e., after invoking this method, on a particular request, execution of it will be aborted. If this method is invoked after one execution, responses of that execution will not be affected and the subsequent executions will be aborted. If you observe the following example, we have created a HttpGet request, printed the request format used using the getMethod(). Then, we have carried out another execution with the same request. Printed the status line using the 1st execution again. Finally, printed the status line of the second execution. As discussed, the responses of the 1st execution (execution before abort method) are printed (including the second status line that is written after the abort method) and, all the subsequent executions of the current request after the abort method are failed invoking an exception. import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpGetExample { public static void main(String args[]) throws Exception{ //Creating an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating an HttpGet object HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/"); //Printing the method used System.out.println(httpget.getMethod()); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); //Printing the status line System.out.println(httpresponse.getStatusLine()); httpget.abort(); System.out.println(httpresponse.getEntity().getContentLength()); //Executing the Get request HttpResponse httpresponse2 = httpclient.execute(httpget); System.out.println(httpresponse2.getStatusLine()); } } On executing, the above program generates the following output − On executing, the above program generates the following output. GET HTTP/1.1 200 OK -1 Exception in thread "main" org.apache.http.impl.execchain.RequestAbortedException: Request aborted at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:180) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108) at HttpGetExample.main(HttpGetExample.java:32) Interceptors are those which helps to obstruct or change requests or responses. Protocol interceptors in general act upon a specific header or a group of related headers. HttpClient library provides support for interceptors. The HttpRequestInterceptor interface represents the request interceptors. This interface contains a method known as a process in which you need to write the chunk of code to intercept the requests. On the client side, this method verifies/processes the requests before sending them to the server and, on the server side, this method is executed before evaluating the body of the request. You can create a request interceptor by following the steps given below. Step 1 - Create an object of HttpRequestInterceptor Create an object of the HttpRequestInterceptor interface by implementing its abstract method process. HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { //Method implementation . . . . . }; Step 2 - Instantiate CloseableHttpClient object Build a custom CloseableHttpClient object by adding above created interceptor to it as shown below − //Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(requestInterceptor).build(); Using this object, you can carry out the request executions as usual. Following example demonstrates the usage of request interceptors. In this example, we have created a HTTP GET request object and added three headers: sample-header, demoheader, and test-header to it. In the processor() method of the interceptor, we are verifying the headers of the request sent; if any of those headers is sample-header, we are trying to remove it and display the list of headers of that particular request. import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HttpContext; public class InterceptorsExample { public static void main(String args[]) throws Exception{ //Creating an HttpRequestInterceptor HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if(request.containsHeader("sample-header")) { System.out.println("Contains header sample-header, removing it.."); request.removeHeaders("sample-header"); } //Printing remaining list of headers Header[] headers= request.getAllHeaders(); for (int i = 0; i<headers.length;i++) { System.out.println(headers[i].getName()); } } }; //Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(requestInterceptor).build(); //Creating a request object HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/"); //Setting the header to it httpget1.setHeader(new BasicHeader("sample-header","My first header")); httpget1.setHeader(new BasicHeader("demo-header","My second header")); httpget1.setHeader(new BasicHeader("test-header","My third header")); //Executing the request HttpResponse httpresponse = httpclient.execute(httpget1); //Printing the status line System.out.println(httpresponse.getStatusLine()); } } On executing the above program, the following output is generated − Contains header sample-header, removing it.. demo-header test-header HTTP/1.1 200 OK The HttpResponseInterceptor interface represents the response interceptors. This interface contains a method known as process(). In this method, you need to write the chunk of code to intercept the responses. On the server side, this method verifies/processes the response before sending them to the client, and on the client side, this method is executed before evaluating the body of the response. You can create a response interceptor by following the steps given below − Step 1 - Create an object of HttpResponseInterceptor Create an object of the HttpResponseInterceptor interface by implementing its abstract method process. HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { //Method implementation . . . . . . . . } }; Build a custom CloseableHttpClient object by adding above created interceptor to it, as shown below − //Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build(); Using this object, you can carry out the request executions as usual. The following example demonstrates the usage of response interceptors. In this example, we have added three headers: sample-header, demo-header, and test-header to the response in the processor. After executing the request and obtaining the response, we printed names of all the headers of the response using the getAllHeaders() method. And in the output, you can observe the names of three headers in the list. import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HttpContext; public class ResponseInterceptorsExample { public static void main(String args[]) throws Exception{ //Creating an HttpRequestInterceptor HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { System.out.println("Adding header sample_header, demo-header, test_header to the response"); response.setHeader("sample-header", "My first header"); response.setHeader("demo-header", "My second header"); response.setHeader("test-header", "My third header"); } }; //Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build(); //Creating a request object HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/"); //Executing the request HttpResponse httpresponse = httpclient.execute(httpget1); //Printing remaining list of headers Header[] headers = httpresponse.getAllHeaders(); for (int i = 0; i<headers.length;i++) { System.out.println(headers[i].getName()); } } } On executing, the above program generates the following result − On executing the above program generates the following output. Adding header sample_header, demo-header, test_header to the response Accept-Ranges Access-Control-Allow-Headers Access-Control-Allow-Origin Cache-Control Content-Type Date Expires Last-Modified Server Vary X-Cache sample-header demo-header test-header Using HttpClient, you can connect to a website which needed username and password. This chapter explains, how to execute a client request against a site that asks for username and password. The CredentialsProvider Interface maintains a collection to hold the user login credentials. You can create its object by instantiating the BasicCredentialsProvider class, the default implementation of this interface. CredentialsProvider credentialsPovider = new BasicCredentialsProvider(); You can set the required credentials to the CredentialsProvider object using the setCredentials() method. This method accepts two objects as given below − AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name. AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name. Credentials object − Specifying the credentials (username, password). Credentials object − Specifying the credentials (username, password). Set the credentials using the setCredentials() method for both host and proxy as shown below − credsProvider.setCredentials(new AuthScope("example.com", 80), new UsernamePasswordCredentials("user", "mypass")); credsProvider.setCredentials(new AuthScope("localhost", 8000), new UsernamePasswordCredentials("abc", "passwd")); Create a HttpClientBuilder using the custom() method of the HttpClients class. //Creating the HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); You can set the above created credentialsPovider object to a HttpClientBuilder using the setDefaultCredentialsProvider() method. Set the CredentialProvider object created in the previous step to the client builder by passing it to the CredentialsProvider object() method as shown below. clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider); Build the CloseableHttpClient object using the build() method of the HttpClientBuilder class. CloseableHttpClient httpclient = clientbuilder.build() Create a HttpRequest object by instantiating the HttpGet class. Execute this request using the execute() method. //Creating a HttpGet object HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/ "); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); Following is an example program which demonstrates the execution of a HTTP request against a target site that requires user authentication. import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; public class UserAuthenticationExample { public static void main(String args[]) throws Exception{ //Create an object of credentialsProvider CredentialsProvider credentialsPovider = new BasicCredentialsProvider(); //Set the credentials AuthScope scope = new AuthScope("https://www.tutorialspoint.com/questions/", 80); Credentials credentials = new UsernamePasswordCredentials("USERNAME", "PASSWORD"); credentialsPovider.setCredentials(scope,credentials); //Creating the HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); //Setting the credentials clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider); //Building the CloseableHttpClient object CloseableHttpClient httpclient = clientbuilder.build(); //Creating a HttpGet object HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/questions/index.php"); //Printing the method used System.out.println(httpget.getMethod()); //Executing the Get request HttpResponse httpresponse = httpclient.execute(httpget); //Printing the status line System.out.println(httpresponse.getStatusLine()); int statusCode = httpresponse.getStatusLine().getStatusCode(); System.out.println(statusCode); Header[] headers= httpresponse.getAllHeaders(); for (int i = 0; i<headers.length;i++) { System.out.println(headers[i].getName()); } } } On executing, the above program generates the following output. GET HTTP/1.1 200 OK 200 A Proxy server is an intermediary server between the client and the internet. Proxy servers offer the following basic functionalities − Firewall and network data filtering Firewall and network data filtering Network connection sharing Network connection sharing Data caching Data caching Using HttpClient library, you can send a HTTP request using a proxy. Follow the steps given below − Instantiate the HttpHost class of the org.apache.http package by passing a string parameter representing the name of the proxy host, (from which you need the requests to be sent) to its constructor. //Creating an HttpHost object for proxy HttpHost proxyHost = new HttpHost("localhost"); In the same way, create another HttpHost object to represent the target host to which requests need to be sent. //Creating an HttpHost object for target HttpHost targetHost = new HttpHost("google.com"); The HttpRoutePlanner interface computes a route to a specified host. Create an object of this interface by instantiating the DefaultProxyRoutePlanner class, an implementation of this interface. As a parameter to its constructor, pass the above created proxy host − //creating a RoutePlanner object HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost); Using the custom() method of the HttpClients class, create a HttpClientBuilder object and, to this object set the route planner created above, using the setRoutePlanner() method. //Setting the route planner to the HttpClientBuilder object HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder = clientBuilder.setRoutePlanner(routePlanner); Build the CloseableHttpClient object by calling the build() method. //Building a CloseableHttpClient CloseableHttpClient httpClient = clientBuilder.build(); Create a HTTP GET request by instantiating the HttpGet class. //Creating an HttpGet object HttpGet httpGet = new HttpGet("/"); One of the variants of the execute() method accepts an HttpHost and HttpRequest objects and executes the request. Execute the request using this method − //Executing the Get request HttpResponse httpResponse = httpclient.execute(targetHost, httpGet); Following example demonstrates how to send a HTTP request to a server via proxy. In this example, we are sending a HTTP GET request to google.com via localhost. We have printed the headers of the response and the body of the response. import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; import org.apache.http.util.EntityUtils; public class RequestViaProxyExample { public static void main(String args[]) throws Exception{ //Creating an HttpHost object for proxy HttpHost proxyhost = new HttpHost("localhost"); //Creating an HttpHost object for target HttpHost targethost = new HttpHost("google.com"); //creating a RoutePlanner object HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost); //Setting the route planner to the HttpClientBuilder object HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder = clientBuilder.setRoutePlanner(routePlanner); //Building a CloseableHttpClient CloseableHttpClient httpclient = clientBuilder.build(); //Creating an HttpGet object HttpGet httpget = new HttpGet("/"); //Executing the Get request HttpResponse httpresponse = httpclient.execute(targethost, httpget); //Printing the status line System.out.println(httpresponse.getStatusLine()); //Printing all the headers of the response Header[] headers = httpresponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } //Printing the body of the response HttpEntity entity = httpresponse.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } } On executing, the above program generates the following output − HTTP/1.1 200 OK Date: Sun, 23 Dec 2018 10:21:47 GMT Server: Apache/2.4.9 (Win64) PHP/5.5.13 Last-Modified: Tue, 24 Jun 2014 10:46:24 GMT ETag: "2e-4fc92abc3c000" Accept-Ranges: bytes Content-Length: 46 Content-Type: text/html <html><body><h1>It works!</h1></body></html> In this chapter, we will learn how to create a HttpRequest authenticated using username and password and tunnel it through a proxy to a target host, using an example. The CredentialsProvider Interface maintains a collection to hold the user login credentials. You can create its object by instantiating the BasicCredentialsProvider class, the default implementation of this interface. CredentialsProvider credentialsPovider = new BasicCredentialsProvider(); You can set the required credentials to the CredentialsProvider object using the setCredentials() method. This method accepts two objects − AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name. AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name. Credentials object − Specifying the credentials (username, password). Set the credentials using the setCredentials() method for both host and proxy as shown below. Credentials object − Specifying the credentials (username, password). Set the credentials using the setCredentials() method for both host and proxy as shown below. credsProvider.setCredentials(new AuthScope("example.com", 80), new UsernamePasswordCredentials("user", "mypass")); credsProvider.setCredentials(new AuthScope("localhost", 8000), new UsernamePasswordCredentials("abc", "passwd")); Create a HttpClientBuilder using the custom() method of the HttpClients class as shown below − //Creating the HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); You can set the CredentialsProvider object to a HttpClientBuilder object using the setDefaultCredentialsProvider() method. Pass the previously created CredentialsProvider object to this method. clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider); Build the CloseableHttpClient object using the build() method. CloseableHttpClient httpclient = clientbuilder.build(); Create the target and proxy hosts by instantiating the HttpHost class. //Creating the target and proxy hosts HttpHost target = new HttpHost("example.com", 80, "http"); HttpHost proxy = new HttpHost("localhost", 8000, "http"); Create a RequestConfig.Builder object using the custom() method. Set the previously created proxyHost object to the RequestConfig.Builder using the setProxy() method. Finally, build the RequestConfig object using the build() method. RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom(); reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost); RequestConfig config = reqconfigconbuilder.build(); Create a HttpGet object by instantiating the HttpGet class. Set the config object created in the previous step to this object using the setConfig() method. //Create the HttpGet request object HttpGet httpGet = new HttpGet("/"); //Setting the config to the request httpget.setConfig(config); Execute the request by passing the HttpHost object (target) and request (HttpGet) as parameters to the execute() method. HttpResponse httpResponse = httpclient.execute(targetHost, httpget); Following example demonstrates how to execute a HTTP request through a proxy using username and password. import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; public class ProxyAuthenticationExample { public static void main(String[] args) throws Exception { //Creating the CredentialsProvider object CredentialsProvider credsProvider = new BasicCredentialsProvider(); //Setting the credentials credsProvider.setCredentials(new AuthScope("example.com", 80), new UsernamePasswordCredentials("user", "mypass")); credsProvider.setCredentials(new AuthScope("localhost", 8000), new UsernamePasswordCredentials("abc", "passwd")); //Creating the HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); //Setting the credentials clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider); //Building the CloseableHttpClient object CloseableHttpClient httpclient = clientbuilder.build(); //Create the target and proxy hosts HttpHost targetHost = new HttpHost("example.com", 80, "http"); HttpHost proxyHost = new HttpHost("localhost", 8000, "http"); //Setting the proxy RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom(); reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost); RequestConfig config = reqconfigconbuilder.build(); //Create the HttpGet request object HttpGet httpget = new HttpGet("/"); //Setting the config to the request httpget.setConfig(config); //Printing the status line HttpResponse response = httpclient.execute(targetHost, httpget); System.out.println(response.getStatusLine()); } } On executing, the above program generates the following output − HTTP/1.1 200 OK Using the HttpClient library you can send a request or, login to a form by passing parameters. Follow the steps given below to login to a form. The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object − CloseableHttpClient httpClient = HttpClients.createDefault(); The class RequestBuilder is used to build request by adding parameters to it. If the request type is PUT or POST, it adds the parameters to the request as URL encoded entity Create a RequestBuilder object (of type POST) using the post() method. //Building the post request object RequestBuilder reqbuilder = RequestBuilder.post(); Set the URI and parameters to the RequestBuilder object using the setUri() and addParameter() methods of the RequestBuilder class. //Set URI and parameters RequestBuilder reqbuilder = reqbuilder.setUri("http://httpbin.org/post"); reqbuilder = reqbuilder1.addParameter("Name", "username").addParameter("password", "password"); After setting the required parameters, build the HttpUriRequest object using the build() method. //Building the HttpUriRequest object HttpUriRequest httppost = reqbuilder2.build(); The execute method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object. Execute the HttpUriRequest created in the previous steps by passing it to the execute() method. //Execute the request HttpResponse httpresponse = httpclient.execute(httppost); Following example demonstrates how to logon to a form by sending login credentials. Here, we have sent two parameters − username and password to a form and tried to print the message entity and status of the request. import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URISyntaxException; public class FormLoginExample { public static void main(String args[]) throws Exception { //Creating CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating the RequestBuilder object RequestBuilder reqbuilder = RequestBuilder.post(); //Setting URI and parameters RequestBuilder reqbuilder1 = reqbuilder.setUri("http://httpbin.org/post"); RequestBuilder reqbuilder2 = reqbuilder1.addParameter("Name", "username").addParameter("password", "password"); //Building the HttpUriRequest object HttpUriRequest httppost = reqbuilder2.build(); //Executing the request HttpResponse httpresponse = httpclient.execute(httppost); //Printing the status and the contents of the response System.out.println(EntityUtils.toString(httpresponse.getEntity())); System.out.println(httpresponse.getStatusLine()); } } On executing, the above program generates the following output − { "args": {}, "data": "", "files": {}, "form": { "Name": "username", "password": "password" }, "headers": { "Accept-Encoding": "gzip,deflate", "Connection": "close", "Content-Length": "31", "Content-Type": "application/x-www-form-urlencoded; charset = UTF-8", "Host": "httpbin.org", "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)" }, "json": null, "origin": "117.216.245.180", "url": "http://httpbin.org/post" } HTTP/1.1 200 OK If your form stores cookies, instead of creating default CloseableHttpClient object. Create a CookieStore object by instantiating the BasicCookieStore class. //Creating a BasicCookieStore object BasicCookieStore cookieStore = new BasicCookieStore(); Create a HttpClientBuilder using the custom() method of the HttpClients class. //Creating an HttpClientBuilder object HttpClientBuilder clientbuilder = HttpClients.custom(); Set the cookie store to the client builder using the setDefaultCookieStore() method. //Setting default cookie store to the client builder object Clientbuilder = clientbuilder.setDefaultCookieStore(cookieStore); Build the CloseableHttpClient object using the build() method. //Building the CloseableHttpClient object CloseableHttpClient httpclient = clientbuilder1.build(); Build the HttpUriRequest object as specified above by passing execute the request. If the page stores cookies, the parameters you have passed will be added to the cookie store. You can print the contents of the CookieStore object where you can see your parameters (along with the previous ones the page stored in case). To print the cookies, get all the cookies from the CookieStore object using the getCookies() method. This method returns a List object. Using Iterator, print the list objects contents as shown below − //Printing the cookies List list = cookieStore.getCookies(); System.out.println("list of cookies"); Iterator it = list.iterator(); if(it.hasNext()) { System.out.println(it.next()); } Cookies are text files stored on the client computer and they are kept for various information tracking purpose. HttpClient provides support for cookies you can create and manage cookies. Follow the steps given below to create a cookie using HttpClient library. The CookieStore interface represents the abstract store for Cookie objects. You can create a cookie store by instantiating the BasicCookieStore class, a default implementation of this interface. //Creating the CookieStore object CookieStore cookieStore = new BasicCookieStore(); In addition to the functionalities of a cookie, ClientCookie can get the original cookies in the server. You can create a client cookie by instantiating the BasicClientCookie class. To the constructor of this class, you need to pass the key-value pair that you desired to store in that particular cookie. //Creating client cookie BasicClientCookie clientCookie = new BasicClientCookie("name","Raju"); To a client cookie, you can set/remove path, value, version, expiry date, domain, comment, and attribute using the respective methods. Calendar myCal = new GregorianCalendar(2018, 9, 26); Date expiryDate = myCal.getTime(); clientcookie.setExpiryDate(expiryDate); clientcookie.setPath("/"); clientcookie.setSecure(true); clientcookie.setValue("25"); clientcookie.setVersion(5); You can add cookies to the cookie store using the addCookie() method of the BasicCookieStore class. Add the required cookies to the Cookiestore. //Adding the created cookies to cookie store cookiestore.addCookie(clientcookie); Following example demonstrates how to create cookies and add them to a cookie store. Here, we created a cookie store, a bunch of cookies by setting the domain and path values, and added these to the cookie store. import org.apache.http.client.CookieStore; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.cookie.BasicClientCookie; public class CookieHandlingExample { public static void main(String args[]) throws Exception{ //Creating the CookieStore object CookieStore cookiestore = new BasicCookieStore(); //Creating client cookies BasicClientCookie clientcookie1 = new BasicClientCookie("name","Raju"); BasicClientCookie clientcookie2 = new BasicClientCookie("age","28"); BasicClientCookie clientcookie3 = new BasicClientCookie("place","Hyderabad"); //Setting domains and paths to the created cookies clientcookie1.setDomain(".sample.com"); clientcookie2.setDomain(".sample.com"); clientcookie3.setDomain(".sample.com"); clientcookie1.setPath("/"); clientcookie2.setPath("/"); clientcookie3.setPath("/"); //Adding the created cookies to cookie store cookiestore.addCookie(clientcookie1); cookiestore.addCookie(clientcookie2); cookiestore.addCookie(clientcookie3); } } You can get the cookies added to a cookie store using getCookies() method of the asicCookieStore class. This method returns a list which holds all the cookies in the cookie store. You can print the contents of a cookie store using the Iterator as shown below − //Retrieving the cookies List list = cookieStore.getCookies(); //Creating an iterator to the obtained list Iterator it = list.iterator(); while(it.hasNext()) { System.out.println(it.next()); } Following example demonstrates how to retrieve cookies from a cookie store. Here, we are adding a bunch of cookies to a cookie store and retrieving them back. import org.apache.http.client.CookieStore; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.cookie.BasicClientCookie; public class CookieHandlingExample { public static void main(String args[]) throws Exception{ //Creating the CookieStore object CookieStore cookiestore = new BasicCookieStore(); //Creating client cookies BasicClientCookie clientcookie1 = new BasicClientCookie("name","Raju"); BasicClientCookie clientcookie2 = new BasicClientCookie("age","28"); BasicClientCookie clientcookie3 = new BasicClientCookie("place","Hyderabad"); //Setting domains and paths to the created cookies clientcookie1.setDomain(".sample.com"); clientcookie2.setDomain(".sample.com"); clientcookie3.setDomain(".sample.com"); clientcookie1.setPath("/"); clientcookie2.setPath("/"); clientcookie3.setPath("/"); //Adding the created cookies to cookie store cookiestore.addCookie(clientcookie1); cookiestore.addCookie(clientcookie2); cookiestore.addCookie(clientcookie3); } } On executing, this program generates the following output − [version: 0][name: age][value: 28][domain: .sample.com][path: /][expiry: null] [version: 0][name: name][value: Raju][domain: my.example.com][path: /][expiry: null] [version: 0][name: place][value: Hyderabad][domain: .sample.com][path: /][expiry: null] A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources. You can execute requests from multiple threads by writing a multithreaded HttpClient program. If you want to execute multiple client requests from threads consecutively, you need to create a ClientConnectionPoolManager. It maintains a pool of HttpClientConnections and serves multiple requests from threads. The connections manager pools the connections based on the route. If the manager has connections for a particular route, then it serves new requests in those routes by leasing an existing connection from the pool, instead of creating a new one. Follow the steps to execute requests from multiple threads − Create the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); Set the maximum number of connections in the pool using the setMaxTotal() method. //Set the maximum number of connections in the pool connManager.setMaxTotal(100); Create a ClientBuilder Object by setting the connection manager using the setConnectionManager() method as shown below − HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager); Instantiate the HttpGet class by passing the desired URI to its constructor as a parameter. HttpGet httpget1 = new HttpGet("URI1"); HttpGet httpget2 = new HttpGet("URI2"); . . . . . . . . . . . . Make sure that you have created a class, made it a thread (either by extending the thread class or, by implementing the Runnable interface) and implemented the run method. public class ClientMultiThreaded extends Thread { public void run() { //Run method implementation . . . . . . . . . . } } Create thread objects by instantiating the Thread class (ClientMultiThreaded) created above. Pass a HttpClient object, respective HttpGet object and, an integer representing the ID to these threads. ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1); ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2); . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Start all the threads using start() method and join them using the join method(). thread1.start(); thread2.start(); . . . . . . . . thread1.join(); thread2.join(); . . . . . . . . . . . . Within the run method, execute the request, retrieve the response and print the results. Following example demonstrates the execution of HTTP requests simultaneously from multiple threads. In this example, we are trying to execute various requests from various threads and trying to print the status, and the number of bytes read by each client. import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; public class ClientMultiThreaded extends Thread { CloseableHttpClient httpClient; HttpGet httpget; int id; public ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpget, int id) { this.httpClient = httpClient; this.httpget = httpget; this.id = id; } @Override public void run() { try{ //Executing the request CloseableHttpResponse httpresponse = httpClient.execute(httpget); //Displaying the status of the request. System.out.println("status of thread "+id+":"+httpresponse.getStatusLine()); //Retrieving the HttpEntity and displaying the no.of bytes read HttpEntity entity = httpresponse.getEntity(); if (entity != null) { System.out.println("Bytes read by thread thread "+id+": "+EntityUtils.toByteArray(entity).length); } }catch(Exception e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { //Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); //Set the maximum number of connections in the pool connManager.setMaxTotal(100); //Create a ClientBuilder Object by setting the connection manager HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager); //Build the CloseableHttpClient object using the build() method. CloseableHttpClient httpclient = clientbuilder.build(); //Creating the HttpGet requests HttpGet httpget1 = new HttpGet("http://www.tutorialspoint.com/"); HttpGet httpget2 = new HttpGet("http://www.google.com/"); HttpGet httpget3 = new HttpGet("https://www.qries.com/"); HttpGet httpget4 = new HttpGet("https://in.yahoo.com/"); //Creating the Thread objects ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1); ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2); ClientMultiThreaded thread3 = new ClientMultiThreaded(httpclient,httpget3, 3); ClientMultiThreaded thread4 = new ClientMultiThreaded(httpclient,httpget4, 4); //Starting all the threads thread1.start(); thread2.start(); thread3.start(); thread4.start(); //Joining all the threads thread1.join(); thread2.join(); thread3.join(); thread4.join(); } } On executing, the above program generates the following output − status of thread 1: HTTP/1.1 200 OK Bytes read by thread thread 1: 36907 status of thread 2: HTTP/1.1 200 OK Bytes read by thread thread 2: 13725 status of thread 3: HTTP/1.1 200 OK Bytes read by thread thread 3: 17319 status of thread 4: HTTP/1.1 200 OK Bytes read by thread thread 4: 127018 Using Secure Socket Layer, you can establish a secured connection between the client and server. It helps to safeguard sensitive information such as credit card numbers, usernames, passwords, pins, etc. You can make connections more secure by creating your own SSL context using the HttpClient library. Follow the steps given below to customize SSLContext using HttpClient library − SSLContextBuilder is the builder for the SSLContext objects. Create its object using the custom() method of the SSLContexts class. //Creating SSLContextBuilder object SSLContextBuilder SSLBuilder = SSLContexts.custom(); In the path Java_home_directory/jre/lib/security/, you can find a file named cacerts. Save this as your key store file (with extension .jks). Load the keystore file and, its password (which is changeit by default) using the loadTrustMaterial() method of the SSLContextBuilder class. //Loading the Keystore file File file = new File("mykeystore.jks"); SSLBuilder = SSLBuilder.loadTrustMaterial(file, "changeit".toCharArray()); An SSLContext object represents a secure socket protocol implementation. Build an SSLContext using the build() method. //Building the SSLContext SSLContext sslContext = SSLBuilder.build(); SSLConnectionSocketFactory is a layered socket factory for TSL and SSL connections. Using this, you can verify the Https server using a list of trusted certificates and authenticate the given Https server. You can create this in many ways. Depending on the way you create an SSLConnectionSocketFactory object, you can allow all hosts, allow only self-signed certificates, allow only particular protocols, etc. To allow only particular protocols, create SSLConnectionSocketFactory object by passing an SSLContext object, string array representing the protocols need to be supported, string array representing the cipher suits need to be supported and a HostnameVerifier object to its constructor. new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); To allow all hosts, create SSLConnectionSocketFactory object by passing a SSLContext object and a NoopHostnameVerifier object. //Creating SSLConnectionSocketFactory SSLConnectionSocketFactory object SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); Create an HttpClientBuilder object using the custom() method of the HttpClients class. //Creating HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); Set the SSLConnectionSocketFactory object to the HttpClientBuilder using the setSSLSocketFactory() method. //Setting the SSLConnectionSocketFactory clientbuilder = clientbuilder.setSSLSocketFactory(sslConSocFactory); Build the CloseableHttpClient object by calling the build() method. //Building the CloseableHttpClient CloseableHttpClient httpclient = clientbuilder.build(); The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI. Create a HTTP GET request by instantiating the HttpGet class by passing a string representing the URI. //Creating the HttpGet request HttpGet httpget = new HttpGet("https://example.com/"); Execute the request using the execute() method. //Executing the request HttpResponse httpresponse = httpclient.execute(httpget); Following example demonstrates the customization of the SSLContrext − import java.io.File; import javax.net.ssl.SSLContext; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; public class ClientCustomSSL { public final static void main(String[] args) throws Exception { //Creating SSLContextBuilder object SSLContextBuilder SSLBuilder = SSLContexts.custom(); //Loading the Keystore file File file = new File("mykeystore.jks"); SSLBuilder = SSLBuilder.loadTrustMaterial(file, "changeit".toCharArray()); //Building the SSLContext usiong the build() method SSLContext sslcontext = SSLBuilder.build(); //Creating SSLConnectionSocketFactory object SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); //Creating HttpClientBuilder HttpClientBuilder clientbuilder = HttpClients.custom(); //Setting the SSLConnectionSocketFactory clientbuilder = clientbuilder.setSSLSocketFactory(sslConSocFactory); //Building the CloseableHttpClient CloseableHttpClient httpclient = clientbuilder.build(); //Creating the HttpGet request HttpGet httpget = new HttpGet("https://example.com/"); //Executing the request HttpResponse httpresponse = httpclient.execute(httpget); //printing the status line System.out.println(httpresponse.getStatusLine()); //Retrieving the HttpEntity and displaying the no.of bytes read HttpEntity entity = httpresponse.getEntity(); if (entity != null) { System.out.println(EntityUtils.toByteArray(entity).length); } } } On executing, the above program generates the following output. HTTP/1.1 200 OK 1270 Using HttpClient, we can perform Multipart upload, i.e., we can upload larger objects in smaller parts. In this chapter, we demonstrate the multipart upload in HTTP client by uploading a simple text file. In general, any multipart upload contains three parts. Initiation of the upload Initiation of the upload Uploading the object parts Uploading the object parts Completing the Multipart upload Completing the Multipart upload For the multipart upload using HttpClient, we need to follow the below steps − Create a multipart builder. Create a multipart builder. Add desired parts to it. Add desired parts to it. Complete the build and obtain a multipart HttpEntity. Complete the build and obtain a multipart HttpEntity. Build request by setting the above muti-part entity. Build request by setting the above muti-part entity. Execute the request. Execute the request. Following are the steps to upload a multipart entity using the HttpClient library. The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object − //Creating CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); FileBody class represents the binary body part backed by a file. Instantiate this class by passing a File object and a ContentType object representing the type of the content. //Creating a File object File file = new File("sample.txt"); //Creating the FileBody object FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY); The MultipartEntityBuilder class is used to build the multi-part HttpEntity object. Create its object using the create() method (of the same class). //Creating the MultipartEntityBuilder MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); A MultipartEntityBuilder has three modes: STRICT, RFC6532, and BROWSER_COMPATIBLE. Set it to the desired mode using the setMode() method. //Setting the mode entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); Using the methods addTextBody(), addPart() and, addBinaryBody(), you can add simple text, files, streams, and other objects to a MultipartBuilder. Add the desired contents using these methods. //Adding text entitybuilder.addTextBody("sample_text", "This is the text part of our file"); //Adding a file entitybuilder.addBinaryBody("image", new File("logo.png")); You can build all these parts to a single entity using the build() method of the MultipartEntityBuilder class. Using this method, build all the parts into a single HttpEntity. //Building a single entity using the parts HttpEntity mutiPartHttpEntity = entityBuilder.build(); The class RequestBuilder is used to build request by adding parameters to it. If the request is of type PUT or POST, it adds the parameters to the request as URL encoded entity. Create a RequestBuilder object (of type POST) using the post() method. And pass the Uri to which you wanted to send the request it as a parameter. //Building the post request object RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post"); Set the above created multipart entity to the RequestBuilder using the setEntity() method of the RequestBuilder class. //Setting the entity object to the RequestBuilder reqbuilder.setEntity(mutiPartHttpEntity); Build a HttpUriRequest request object using the build() method of the RequestBuilder class. //Building the request HttpUriRequest multipartRequest = reqbuilder.build(); Using the execute() method, execute the request built in the previous step (bypassing the request as a parameter to this method). //Executing the request HttpResponse httpresponse = httpclient.execute(multipartRequest); Following example demonstrates how to send a multipart request using the HttpClient library. In this example, we are trying to send a multipart request backed by a file. import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; public class MultipartUploadExample { public static void main(String args[]) throws Exception{ //Creating CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //Creating a file object File file = new File("sample.txt"); //Creating the FileBody object FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY); //Creating the MultipartEntityBuilder MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); //Setting the mode entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //Adding text entitybuilder.addTextBody("sample_text", "This is the text part of our file"); //Adding a file entitybuilder.addBinaryBody("image", new File("logo.png")); //Building a single entity using the parts HttpEntity mutiPartHttpEntity = entitybuilder.build(); //Building the RequestBuilder request object RequestBuilder reqbuilder = RequestBuilder.post("http://httpbin.org/post"); //Set the entity object to the RequestBuilder reqbuilder.setEntity(mutiPartHttpEntity); //Building the request HttpUriRequest multipartRequest = reqbuilder.build(); //Executing the request HttpResponse httpresponse = httpclient.execute(multipartRequest); //Printing the status and the contents of the response System.out.println(EntityUtils.toString(httpresponse.getEntity())); System.out.println(httpresponse.getStatusLine()); } } On executing, the above program generates the following output − { "args": {}, "data": "", "files": { "image": "data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE lFTkSuQmCC" }, "form": { "sample_text": "This is the text part of our file" }, "headers": { "Accept-Encoding": "gzip,deflate", "Connection": "close", "Content-Length": "11104", "Content-Type": "multipart/form-data; boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt", "Host": "httpbin.org", "User-Agent": "Apache-HttpClient/4.5.6 (Java/1.8.0_91)" }, "json": null, "origin": "117.216.245.180", "url": "http://httpbin.org/post" } HTTP/1.1 200 OK 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2214, "s": 1827, "text": "The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed,\ncollaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web (i.e., Internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extensions of its request methods, error codes, and headers." }, { "code": null, "e": 2657, "s": 2214, "text": "Basically, HTTP is a TCP/IP based communication protocol, that is used to deliver data (HTML files, image files, query results, etc.) on the World Wide Web. The default port is TCP 80, but other ports can be used as well. It provides a standardized way for computers to communicate with each other. HTTP specification defines how clients' request data will be constructed and sent to the server, and how the servers respond to these requests." }, { "code": null, "e": 2863, "s": 2657, "text": "Http client is a transfer library, it resides on the client side, sends and receives HTTP\nmessages. It provides up to date, feature-rich and, efficient implementation which meets the recent HTTP standards." }, { "code": null, "e": 2991, "s": 2863, "text": "In addition to this using client library, one can build HTTP based applications such as web\nbrowsers, web service clients, etc." }, { "code": null, "e": 3045, "s": 2991, "text": "Following are the prominent features of Http client −" }, { "code": null, "e": 3107, "s": 3045, "text": "HttpClient library implements all the available HTTP methods." }, { "code": null, "e": 3169, "s": 3107, "text": "HttpClient library implements all the available HTTP methods." }, { "code": null, "e": 3265, "s": 3169, "text": "HttpClient library provides APIs to secure the requests using the Secure Socket Layer protocol." }, { "code": null, "e": 3361, "s": 3265, "text": "HttpClient library provides APIs to secure the requests using the Secure Socket Layer protocol." }, { "code": null, "e": 3424, "s": 3361, "text": "Using HttpClient, you can establish connections using proxies." }, { "code": null, "e": 3487, "s": 3424, "text": "Using HttpClient, you can establish connections using proxies." }, { "code": null, "e": 3607, "s": 3487, "text": "You can authenticate connections using authentication schemes such as Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session etc." }, { "code": null, "e": 3727, "s": 3607, "text": "You can authenticate connections using authentication schemes such as Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session etc." }, { "code": null, "e": 3898, "s": 3727, "text": "HttpClient library supports sending requests through multiple threads. It manages multiple connections established from various threads using ClientConnectionPoolManager." }, { "code": null, "e": 4069, "s": 3898, "text": "HttpClient library supports sending requests through multiple threads. It manages multiple connections established from various threads using ClientConnectionPoolManager." }, { "code": null, "e": 4135, "s": 4069, "text": "Using Apache HttpClient library, you can set connection timeouts." }, { "code": null, "e": 4201, "s": 4135, "text": "Using Apache HttpClient library, you can set connection timeouts." }, { "code": null, "e": 4436, "s": 4201, "text": "In this chapter, we will explain how to set an environment for HttpClient in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse." }, { "code": null, "e": 4507, "s": 4436, "text": "For more information on Eclipse, please refer to our Eclipse Tutorial." }, { "code": null, "e": 4601, "s": 4507, "text": "Open the official homepage of the HttpClient (components) website and go to the download page" }, { "code": null, "e": 4754, "s": 4601, "text": "Then, download the latest stable version of HttpClient. Here, throughout the tutorial, we are using the version 4.5.6 hence download the file 4.5.6.zip." }, { "code": null, "e": 4938, "s": 4754, "text": "Within the downloaded folder, you will find a folder named lib and this contains the required Jar files that are to be added in the classpath of your project, to work with HttpClient." }, { "code": null, "e": 5075, "s": 4938, "text": "Open eclipse and create a sample project. Right click on the project select the option Build Path → Configure Build Path as shown below." }, { "code": null, "e": 5154, "s": 5075, "text": "In the Java Build Path frame in the Libraries tab, click on Add External JARs." }, { "code": null, "e": 5232, "s": 5154, "text": "And select all the jar files in the lib folder and, click on Apply and Close." }, { "code": null, "e": 5292, "s": 5232, "text": "You are all set to work with HttpClient library in eclipse." }, { "code": null, "e": 5470, "s": 5292, "text": "The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data." }, { "code": null, "e": 5561, "s": 5470, "text": "The HttpClient API provides a class named HttpGet which represents the get request method." }, { "code": null, "e": 5637, "s": 5561, "text": "Follow the steps given below to send a get request using HttpClient library" }, { "code": null, "e": 5789, "s": 5637, "text": "The createDefault() method of the HttpClients class returns a CloseableHttpClient object, which is the base implementation of the HttpClient interface." }, { "code": null, "e": 5853, "s": 5789, "text": "Using this method, create an HttpClient object as shown below −" }, { "code": null, "e": 5916, "s": 5853, "text": "CloseableHttpClient httpclient = HttpClients.createDefault();\n" }, { "code": null, "e": 6030, "s": 5916, "text": "The HttpGet class represents the HTTPGET request which retrieves the information of the given server using a URI." }, { "code": null, "e": 6160, "s": 6030, "text": "Create a HTTP GET request by instantiating this class. The constructor of this class accepts\na String value representing the URI." }, { "code": null, "e": 6226, "s": 6160, "text": "HttpGet httpget = new HttpGet(\"http://www.tutorialspoint.com/\");\n" }, { "code": null, "e": 6404, "s": 6226, "text": "The execute() method of the CloseableHttpClient class accepts a HttpUriRequest\n(interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response\nobject." }, { "code": null, "e": 6459, "s": 6404, "text": "Execute the request using this method as shown below −" }, { "code": null, "e": 6517, "s": 6459, "text": "HttpResponse httpresponse = httpclient.execute(httpget);\n" }, { "code": null, "e": 6624, "s": 6517, "text": "Following is an example which demonstrates the execution of the HTTP GET request using HttpClient library." }, { "code": null, "e": 7592, "s": 6624, "text": "import java.util.Scanner;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\n\npublic class HttpGetExample {\n \n public static void main(String args[]) throws Exception{\n \n //Creating a HttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n //Creating a HttpGet object\n HttpGet httpget = new HttpGet(\"https://www.tutorialspoint.com/ \");\n\n //Printing the method used\n System.out.println(\"Request Type: \"+httpget.getMethod());\n\n //Executing the Get request\n HttpResponse httpresponse = httpclient.execute(httpget);\n\n Scanner sc = new Scanner(httpresponse.getEntity().getContent());\n\n //Printing the status line\n System.out.println(httpresponse.getStatusLine());\n while(sc.hasNext()) {\n System.out.println(sc.nextLine());\n }\n }\n} " }, { "code": null, "e": 7643, "s": 7592, "text": "The above program generates the following output −" }, { "code": null, "e": 9438, "s": 7643, "text": "Request Type: GET\n<!DOCTYPE html>\n<!--[if IE 8]><html class = \"ie ie8\"> <![endif]-->\n<!--[if IE 9]><html class = \"ie ie9\"> <![endif]-->\n<!--[if gt IE 9]><!-->\n<html lang = \"en-US\"> <!--<![endif]-->\n<head>\n<!-- Basic -->\n<meta charset = \"utf-8\">\n<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java\ni18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,\nLOLCODE, Current Affairs 2018, Apache Commons Collections</title>\n<meta name = \"Description\" content = \"Parallax Scrolling, Java Cryptography, YAML,\nPython Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common\nCLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache\nCommons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC),\nLogo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow\"/>\n<meta name = \"Keywords\" content = \"Python Data Science, Java i18n, GitLab,\nTestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson,\nTestLink, Inter Process Communication (IPC), Logo\"/>\n<meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\">\n<meta name = \"viewport\" content = \"width = device-width,initial-scale = 1.0,userscalable = yes\">\n<link href = \"https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css\"\nrel = \"stylesheet\" type = \"text/css\" />\n<link rel = \"stylesheet\" href=\"/questions/css/home.css?v = 3\" />\n<script src = \"/questions/js/jquery.min.js\"></script>\n<script src = \"/questions/js/fontawesome.js\"></script>\n<script src = \"https://cdn.muicss.com/mui-0.9.39/js/mui.min.js\"></script>\n</head>\n. . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . .\n</script>\n</body>\n</html>\n" }, { "code": null, "e": 9561, "s": 9438, "text": "A POST request is used to send data to the server; for example, customer information, file\nupload, etc., using HTML forms." }, { "code": null, "e": 9647, "s": 9561, "text": "The HttpClient API provides a class named HttpPost which represents the POST request." }, { "code": null, "e": 9730, "s": 9647, "text": "Follow the steps given below to send a HTTP POST request using HttpClient library." }, { "code": null, "e": 9896, "s": 9730, "text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface." }, { "code": null, "e": 9944, "s": 9896, "text": "Using this method, create an HttpClient object." }, { "code": null, "e": 10007, "s": 9944, "text": "CloseableHttpClient httpClient = HttpClients.createDefault();\n" }, { "code": null, "e": 10148, "s": 10007, "text": "The HttpPost class represents the HTTP POST request. This sends required data and retrieves the information of the given server using a URI." }, { "code": null, "e": 10285, "s": 10148, "text": "Create this request by instantiating the HttpPost class and pass a string value representing the URI, as a parameter to its constructor." }, { "code": null, "e": 10351, "s": 10285, "text": "HttpGet httpGet = new HttpGet(\"http://www.tutorialspoint.com/\");\n" }, { "code": null, "e": 10530, "s": 10351, "text": "The execute() method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object." }, { "code": null, "e": 10588, "s": 10530, "text": "HttpResponse httpResponse = httpclient.execute(httpget);\n" }, { "code": null, "e": 10696, "s": 10588, "text": "Following is an example which demonstrates the execution of the HTTP POST request using\nHttpClient library." }, { "code": null, "e": 11643, "s": 10696, "text": "import org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\n\npublic class HttpPostExample {\n \n public static void main(String args[]) throws Exception{\n \n //Creating a HttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n //Creating a HttpGet object\n HttpPost httppost = new HttpPost(\"https://www.tutorialspoint.com/\");\n\n //Printing the method used\n System.out.println(\"Request Type: \"+httppost.getMethod());\n\n //Executing the Get request\n HttpResponse httpresponse = httpclient.execute(httppost);\n\n Scanner sc = new Scanner(httpresponse.getEntity().getContent());\n\n //Printing the status line\n System.out.println(httpresponse.getStatusLine());\n while(sc.hasNext()) {\n System.out.println(sc.nextLine());\n }\n }\n}" }, { "code": null, "e": 11693, "s": 11643, "text": "The above program generates the following output." }, { "code": null, "e": 13490, "s": 11693, "text": "Request Type: POST\n<!DOCTYPE html>\n<!--[if IE 8]><html class = \"ie ie8\"> <![endif]-->\n<!--[if IE 9]><html class = \"ie ie9\"> <![endif]-->\n<!--[if gt IE 9]><!--> \n<html lang = \"en-US\"> <!--<![endif]-->\n<head>\n<!-- Basic -->\n<meta charset = \"utf-8\">\n<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java\ni18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,\nLOLCODE, Current Affairs 2018, Apache Commons Collections</title>\n<meta name = \"Description\" content = \"Parallax Scrolling, Java Cryptography, YAML,\nPython Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common\nCLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache\nCommons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC),\nLogo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow\"/>\n<meta name = \"Keywords\" content=\"Python Data Science, Java i18n, GitLab,\nTestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson,\nTestLink, Inter Process Communication (IPC), Logo\"/>\n<meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\">\n<meta name = \"viewport\" conten t= \"width = device-width,initial-scale = 1.0,userscalable = yes\">\n<link href = \"https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css\"\nrel = \"stylesheet\" type = \"text/css\" />\n<link rel = \"stylesheet\" href = \"/questions/css/home.css?v = 3\" />\n<script src = \"/questions/js/jquery.min.js\"></script>\n<script src = \"/questions/js/fontawesome.js\"></script>\n<script src = \"https://cdn.muicss.com/mui-0.9.39/js/mui.min.js\"></script>\n</head>\n. . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . .\n</script>\n</body>\n</html>\n" }, { "code": null, "e": 13680, "s": 13490, "text": "Processing the HTTP responses using the response handlers is recommended. In this chapter, we are going to discuss how to create response handlers and how to use them to process a response." }, { "code": null, "e": 13771, "s": 13680, "text": "If you use the response handler, all the HTTP connections will be released automatically.\n" }, { "code": null, "e": 13982, "s": 13771, "text": "The HttpClient API provides an interface known as ResponseHandler in the package org.apache.http.client. In order to create a response handler, implement this interface\nand override its handleResponse() method." }, { "code": null, "e": 14236, "s": 13982, "text": "Every response has a status code and if the status code is in between 200 and 300, that means the action was successfully received, understood, and accepted. Therefore, in our example, we will handle the entities of the responses with such status codes." }, { "code": null, "e": 14314, "s": 14236, "text": "Follow the steps given below to execute the request using a response handler." }, { "code": null, "e": 14526, "s": 14314, "text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method create an HttpClient object" }, { "code": null, "e": 14589, "s": 14526, "text": "CloseableHttpClient httpclient = HttpClients.createDefault();\n" }, { "code": null, "e": 14678, "s": 14589, "text": "Instantiate the response handler object created above using the following line of code −" }, { "code": null, "e": 14747, "s": 14678, "text": "ResponseHandler<String> responseHandler = new MyResponseHandler(); \n" }, { "code": null, "e": 14862, "s": 14747, "text": "The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI." }, { "code": null, "e": 15003, "s": 14862, "text": "Create an HttpGet request by instantiating the HttpGet class and by passing a string representing the URI as a parameter to its constructor." }, { "code": null, "e": 15072, "s": 15003, "text": "ResponseHandler<String> responseHandler = new MyResponseHandler(); \n" }, { "code": null, "e": 15229, "s": 15072, "text": "The CloseableHttpClient class has a variant of execute() method which accepts two objects ResponseHandler and HttpUriRequest, and returns a response object." }, { "code": null, "e": 15298, "s": 15229, "text": "String httpResponse = httpclient.execute(httpget, responseHandler);\n" }, { "code": null, "e": 15361, "s": 15298, "text": "Following example demonstrates the usage of response handlers." }, { "code": null, "e": 16870, "s": 15361, "text": "import java.io.IOException;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.ResponseHandler;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\n\nclass MyResponseHandler implements ResponseHandler<String>{\n \n public String handleResponse(final HttpResponse response) throws IOException{\n\n //Get the status of the response\n int status = response.getStatusLine().getStatusCode();\n if (status >= 200 && status < 300) {\n HttpEntity entity = response.getEntity();\n if(entity == null) {\n return \"\";\n } else {\n return EntityUtils.toString(entity);\n }\n\n } else {\n return \"\"+status;\n }\n }\n}\n\npublic class ResponseHandlerExample {\n \n public static void main(String args[]) throws Exception{\n \n //Create an HttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n //instantiate the response handler\n ResponseHandler<String> responseHandler = new MyResponseHandler();\n\n //Create an HttpGet object\n HttpGet httpget = new HttpGet(\"http://www.tutorialspoint.com/\");\n\n //Execute the Get request by passing the response handler object and HttpGet object\n String httpresponse = httpclient.execute(httpget, responseHandler);\n\n System.out.println(httpresponse);\n }\n}" }, { "code": null, "e": 16921, "s": 16870, "text": "The above programs generate the following output −" }, { "code": null, "e": 18046, "s": 16921, "text": "<!DOCTYPE html>\n<!--[if IE 8]><html class = \"ie ie8\"> <![endif]-->\n<!--[if IE 9]><html class = \"ie ie9\"> <![endif]-->\n<!--[if gt IE 9]><!-->\n<html lang = \"en-US\"> <!--<![endif]-->\n<head>\n<!-- Basic -->\n<meta charset = \"utf-8\">\n<meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\">\n<meta name = \"viewport\" content = \"width = device-width,initial-scale = 1.0,userscalable = yes\">\n<link href = \"https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css\"\nrel = \"stylesheet\" type = \"text/css\" />\n<link rel = \"stylesheet\" href = \"/questions/css/home.css?v = 3\" />\n<script src = \"/questions/js/jquery.min.js\"></script>\n<script src = \"/questions/js/fontawesome.js\"></script>\n<script src = \"https://cdn.muicss.com/mui-0.9.39/js/mui.min.js\"></script>\n</head>\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n<script>\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag() {dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'UA-232293-17');\n</script>\n</body>\n" }, { "code": null, "e": 18246, "s": 18046, "text": "If you are processing HTTP responses manually instead of using a response handler, you need to close all the http connections by yourself. This chapter explains how to close the connections manually." }, { "code": null, "e": 18317, "s": 18246, "text": "While closing HTTP connections manually follow the steps given below −" }, { "code": null, "e": 18483, "s": 18317, "text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface." }, { "code": null, "e": 18547, "s": 18483, "text": "Using this method, create an HttpClient object as shown below −" }, { "code": null, "e": 18610, "s": 18547, "text": "CloseableHttpClient httpClient = HttpClients.createDefault();\n" }, { "code": null, "e": 18758, "s": 18610, "text": "Start a try-finally block, write the remaining code in the programs in the try block and close the CloseableHttpClient object in the finally block." }, { "code": null, "e": 18910, "s": 18758, "text": "CloseableHttpClient httpClient = HttpClients.createDefault();\ntry{\n //Remaining code . . . . . . . . . . . . . . .\n}finally{\n httpClient.close();\n}" }, { "code": null, "e": 19025, "s": 18910, "text": "The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI." }, { "code": null, "e": 19128, "s": 19025, "text": "Create a HTTP GET request by instantiating the HttpGet class by passing a string representing the URI." }, { "code": null, "e": 19194, "s": 19128, "text": "HttpGet httpGet = new HttpGet(\"http://www.tutorialspoint.com/\");\n" }, { "code": null, "e": 19373, "s": 19194, "text": "The execute() method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object." }, { "code": null, "e": 19418, "s": 19373, "text": "Execute the request using the given method −" }, { "code": null, "e": 19476, "s": 19418, "text": "HttpResponse httpResponse = httpclient.execute(httpGet);\n" }, { "code": null, "e": 19665, "s": 19476, "text": "Start another try-finally block (nested within the previous try-finally), write the remaining code in the programs in this try block and close the HttpResponse object in the finally block." }, { "code": null, "e": 19964, "s": 19665, "text": "CloseableHttpClient httpclient = HttpClients.createDefault();\ntry{\n . . . . . . .\n . . . . . . .\n CloseableHttpResponse httpresponse = httpclient.execute(httpget);\n try{\n . . . . . . .\n . . . . . . .\n }finally{\n httpresponse.close();\n }\n}finally{\n httpclient.close();\n}" }, { "code": null, "e": 20219, "s": 19964, "text": "Whenever you create/obtain objects such as request, response stream, etc., start a try finally block in the next line, write the remaining code within the try and close the respective object in the finally block as demonstrated in the following program −" }, { "code": null, "e": 21212, "s": 20219, "text": "import java.util.Scanner;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\n\npublic class CloseConnectionExample {\n \n public static void main(String args[])throws Exception{\n \n //Create an HttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n try{\n //Create an HttpGet object\n HttpGet httpget = new HttpGet(\"http://www.tutorialspoint.com/\");\n\n //Execute the Get request\n CloseableHttpResponse httpresponse = httpclient.execute(httpget);\n\n try{\n Scanner sc = new Scanner(httpresponse.getEntity().getContent());\n while(sc.hasNext()) {\n System.out.println(sc.nextLine());\n }\n }finally{\n httpresponse.close();\n }\n }finally{\n httpclient.close();\n }\n }\n}" }, { "code": null, "e": 21280, "s": 21212, "text": "On executing the above program, the following output is generated −" }, { "code": null, "e": 22414, "s": 21280, "text": "<!DOCTYPE html>\n<!--[if IE 8]><html class = \"ie ie8\"> <![endif]-->\n<!--[if IE 9]><html class = \"ie ie9\"> <![endif]-->\n<!--[if gt IE 9]><!-->\n<html lang = \"en-US\"> <!--<![endif]-->\n<head>\n<!-- Basic -->\n<meta charset = \"utf-8\">\n<meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\">\n<meta name = \"viewport\" content = \"width = device-width,initial-scale = 1.0,userscalable = yes\">\n<link href = \"https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css\"\nrel = \"stylesheet\" type = \"text/css\" />\n<link rel = \"stylesheet\" href = \"/questions/css/home.css?v = 3\" />\n<script src = \"/questions/js/jquery.min.js\"></script>\n<script src = \"/questions/js/fontawesome.js\"></script>\n<script src = \"https://cdn.muicss.com/mui-0.9.39/js/mui.min.js\"></script>\n</head>\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . . \n<script>\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag() {dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'UA-232293-17');\n</script>\n</body>\n</html>\n" }, { "code": null, "e": 22571, "s": 22414, "text": "You can abort the current HTTP request using the abort() method, i.e., after invoking this method, on a particular request, execution of it will be aborted." }, { "code": null, "e": 22714, "s": 22571, "text": "If this method is invoked after one execution, responses of that execution will not be affected and the subsequent executions will be aborted." }, { "code": null, "e": 22842, "s": 22714, "text": "If you observe the following example, we have created a HttpGet request, printed the request format used using the getMethod()." }, { "code": null, "e": 23022, "s": 22842, "text": "Then, we have carried out another execution with the same request. Printed the status line using the 1st execution again. Finally, printed the status line of the second execution." }, { "code": null, "e": 23304, "s": 23022, "text": "As discussed, the responses of the 1st execution (execution before abort method) are printed (including the second status line that is written after the abort method) and, all the subsequent executions of the current request after the abort method are failed invoking an exception." }, { "code": null, "e": 24329, "s": 23304, "text": "import org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\n\npublic class HttpGetExample {\n public static void main(String args[]) throws Exception{\n \n //Creating an HttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n //Creating an HttpGet object\n HttpGet httpget = new HttpGet(\"http://www.tutorialspoint.com/\");\n\n //Printing the method used\n System.out.println(httpget.getMethod());\n \n //Executing the Get request\n HttpResponse httpresponse = httpclient.execute(httpget);\n\n //Printing the status line\n System.out.println(httpresponse.getStatusLine());\n\n httpget.abort();\n System.out.println(httpresponse.getEntity().getContentLength());\n \n //Executing the Get request\n HttpResponse httpresponse2 = httpclient.execute(httpget);\n System.out.println(httpresponse2.getStatusLine());\n }\n}" }, { "code": null, "e": 24394, "s": 24329, "text": "On executing, the above program generates the following output −" }, { "code": null, "e": 25203, "s": 24394, "text": "On executing, the above program generates the following output.\nGET\nHTTP/1.1 200 OK\n-1\nException in thread \"main\" org.apache.http.impl.execchain.RequestAbortedException:\nRequest aborted\nat org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:180)\nat org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)\nat org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)\nat org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)\nat org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)\nat org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)\nat org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)\nat HttpGetExample.main(HttpGetExample.java:32)\n" }, { "code": null, "e": 25428, "s": 25203, "text": "Interceptors are those which helps to obstruct or change requests or responses. Protocol interceptors in general act upon a specific header or a group of related headers. HttpClient library provides support for interceptors." }, { "code": null, "e": 25626, "s": 25428, "text": "The HttpRequestInterceptor interface represents the request interceptors. This interface contains a method known as a process in which you need to write the chunk of code to intercept the requests." }, { "code": null, "e": 25816, "s": 25626, "text": "On the client side, this method verifies/processes the requests before sending them to the server and, on the server side, this method is executed before evaluating the body of the request." }, { "code": null, "e": 25889, "s": 25816, "text": "You can create a request interceptor by following the steps given below." }, { "code": null, "e": 25941, "s": 25889, "text": "Step 1 - Create an object of HttpRequestInterceptor" }, { "code": null, "e": 26043, "s": 25941, "text": "Create an object of the HttpRequestInterceptor interface by implementing its abstract method process." }, { "code": null, "e": 26119, "s": 26043, "text": "HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {\n" }, { "code": null, "e": 26268, "s": 26119, "text": "@Override\n public void process(HttpRequest request, HttpContext context) throws\nHttpException, IOException {\n //Method implementation . . . . .\n};" }, { "code": null, "e": 26316, "s": 26268, "text": "Step 2 - Instantiate CloseableHttpClient object" }, { "code": null, "e": 26417, "s": 26316, "text": "Build a custom CloseableHttpClient object by adding above created interceptor to it as shown below −" }, { "code": null, "e": 26561, "s": 26417, "text": "//Creating a CloseableHttpClient object\nCloseableHttpClient httpclient =\nHttpClients.custom().addInterceptorFirst(requestInterceptor).build();\n" }, { "code": null, "e": 26631, "s": 26561, "text": "Using this object, you can carry out the request executions as usual." }, { "code": null, "e": 26831, "s": 26631, "text": "Following example demonstrates the usage of request interceptors. In this example, we have created a HTTP GET request object and added three headers: sample-header, demoheader, and test-header to it." }, { "code": null, "e": 27056, "s": 26831, "text": "In the processor() method of the interceptor, we are verifying the headers of the request sent; if any of those headers is sample-header, we are trying to remove it and display the list of headers of that particular request." }, { "code": null, "e": 29062, "s": 27056, "text": "import java.io.IOException;\nimport org.apache.http.Header;\nimport org.apache.http.HttpException;\nimport org.apache.http.HttpRequest;\nimport org.apache.http.HttpRequestInterceptor;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.message.BasicHeader;\nimport org.apache.http.protocol.HttpContext;\n\npublic class InterceptorsExample {\n \n public static void main(String args[]) throws Exception{\n \n //Creating an HttpRequestInterceptor\n HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {\n @Override\n public void process(HttpRequest request, HttpContext context) throws\n HttpException, IOException {\n if(request.containsHeader(\"sample-header\")) {\n System.out.println(\"Contains header sample-header, removing it..\");\n request.removeHeaders(\"sample-header\"); \n }\n //Printing remaining list of headers\n Header[] headers= request.getAllHeaders();\n for (int i = 0; i<headers.length;i++) {\n System.out.println(headers[i].getName());\n }\n }\n };\n\n //Creating a CloseableHttpClient object\n CloseableHttpClient httpclient =\n HttpClients.custom().addInterceptorFirst(requestInterceptor).build();\n\n //Creating a request object\n HttpGet httpget1 = new HttpGet(\"https://www.tutorialspoint.com/\");\n\n //Setting the header to it\n httpget1.setHeader(new BasicHeader(\"sample-header\",\"My first header\"));\n httpget1.setHeader(new BasicHeader(\"demo-header\",\"My second header\"));\n httpget1.setHeader(new BasicHeader(\"test-header\",\"My third header\"));\n\n //Executing the request\n HttpResponse httpresponse = httpclient.execute(httpget1);\n\n //Printing the status line\n System.out.println(httpresponse.getStatusLine());\n }\n}" }, { "code": null, "e": 29130, "s": 29062, "text": "On executing the above program, the following output is generated −" }, { "code": null, "e": 29216, "s": 29130, "text": "Contains header sample-header, removing it..\ndemo-header\ntest-header\nHTTP/1.1 200 OK\n" }, { "code": null, "e": 29425, "s": 29216, "text": "The HttpResponseInterceptor interface represents the response interceptors. This interface contains a method known as process(). In this method, you need to write the chunk of code to intercept the responses." }, { "code": null, "e": 29616, "s": 29425, "text": "On the server side, this method verifies/processes the response before sending them to the client, and on the client side, this method is executed before evaluating the body of the response." }, { "code": null, "e": 29691, "s": 29616, "text": "You can create a response interceptor by following the steps given below −" }, { "code": null, "e": 29744, "s": 29691, "text": "Step 1 - Create an object of HttpResponseInterceptor" }, { "code": null, "e": 29847, "s": 29744, "text": "Create an object of the HttpResponseInterceptor interface by implementing its abstract method process." }, { "code": null, "e": 30095, "s": 29847, "text": "HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {\n @Override\n public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {\n //Method implementation . . . . . . . .\n }\n};" }, { "code": null, "e": 30197, "s": 30095, "text": "Build a custom CloseableHttpClient object by adding above created interceptor to it, as\nshown below −" }, { "code": null, "e": 30342, "s": 30197, "text": "//Creating a CloseableHttpClient object\nCloseableHttpClient httpclient =\nHttpClients.custom().addInterceptorFirst(responseInterceptor).build();\n" }, { "code": null, "e": 30412, "s": 30342, "text": "Using this object, you can carry out the request executions as usual." }, { "code": null, "e": 30607, "s": 30412, "text": "The following example demonstrates the usage of response interceptors. In this example, we have added three headers: sample-header, demo-header, and test-header to the response in the processor." }, { "code": null, "e": 30749, "s": 30607, "text": "After executing the request and obtaining the response, we printed names of all the headers of the response using the getAllHeaders() method." }, { "code": null, "e": 30824, "s": 30749, "text": "And in the output, you can observe the names of three headers in the list." }, { "code": null, "e": 32479, "s": 30824, "text": "import java.io.IOException;\nimport org.apache.http.Header;\nimport org.apache.http.HttpException;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpResponseInterceptor;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.protocol.HttpContext;\n\npublic class ResponseInterceptorsExample {\n\n public static void main(String args[]) throws Exception{\n \n //Creating an HttpRequestInterceptor\n HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {\n @Override\n public void process(HttpResponse response, HttpContext context) throws\n HttpException, IOException {\n System.out.println(\"Adding header sample_header, demo-header, test_header to the response\");\n response.setHeader(\"sample-header\", \"My first header\");\n response.setHeader(\"demo-header\", \"My second header\");\n response.setHeader(\"test-header\", \"My third header\"); \n }\n };\n\n //Creating a CloseableHttpClient object\n CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build();\n\n //Creating a request object\n HttpGet httpget1 = new HttpGet(\"https://www.tutorialspoint.com/\");\n\n //Executing the request\n HttpResponse httpresponse = httpclient.execute(httpget1); \n\n //Printing remaining list of headers\n Header[] headers = httpresponse.getAllHeaders();\n \n for (int i = 0; i<headers.length;i++) {\n System.out.println(headers[i].getName());\n }\n }\n}" }, { "code": null, "e": 32544, "s": 32479, "text": "On executing, the above program generates the following result −" }, { "code": null, "e": 32861, "s": 32544, "text": "On executing the above program generates the following output.\nAdding header sample_header, demo-header, test_header to the response\nAccept-Ranges\nAccess-Control-Allow-Headers\nAccess-Control-Allow-Origin\nCache-Control\nContent-Type\nDate\nExpires\nLast-Modified\nServer\nVary\nX-Cache\nsample-header\ndemo-header\ntest-header\n" }, { "code": null, "e": 33051, "s": 32861, "text": "Using HttpClient, you can connect to a website which needed username and password. This chapter explains, how to execute a client request against a site that asks for username and password." }, { "code": null, "e": 33269, "s": 33051, "text": "The CredentialsProvider Interface maintains a collection to hold the user login credentials. You can create its object by instantiating the BasicCredentialsProvider class, the default implementation of this interface." }, { "code": null, "e": 33343, "s": 33269, "text": "CredentialsProvider credentialsPovider = new BasicCredentialsProvider();\n" }, { "code": null, "e": 33449, "s": 33343, "text": "You can set the required credentials to the CredentialsProvider object using the setCredentials() method." }, { "code": null, "e": 33498, "s": 33449, "text": "This method accepts two objects as given below −" }, { "code": null, "e": 33621, "s": 33498, "text": "AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name." }, { "code": null, "e": 33744, "s": 33621, "text": "AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name." }, { "code": null, "e": 33814, "s": 33744, "text": "Credentials object − Specifying the credentials (username, password)." }, { "code": null, "e": 33884, "s": 33814, "text": "Credentials object − Specifying the credentials (username, password)." }, { "code": null, "e": 33979, "s": 33884, "text": "Set the credentials using the setCredentials() method for both host and proxy as shown below −" }, { "code": null, "e": 34217, "s": 33979, "text": "credsProvider.setCredentials(new AuthScope(\"example.com\", 80), \n new UsernamePasswordCredentials(\"user\", \"mypass\"));\ncredsProvider.setCredentials(new AuthScope(\"localhost\", 8000), \n new UsernamePasswordCredentials(\"abc\", \"passwd\"));\n" }, { "code": null, "e": 34296, "s": 34217, "text": "Create a HttpClientBuilder using the custom() method of the HttpClients class." }, { "code": null, "e": 34386, "s": 34296, "text": "//Creating the HttpClientBuilder\nHttpClientBuilder clientbuilder = HttpClients.custom();\n" }, { "code": null, "e": 34515, "s": 34386, "text": "You can set the above created credentialsPovider object to a HttpClientBuilder using the setDefaultCredentialsProvider() method." }, { "code": null, "e": 34673, "s": 34515, "text": "Set the CredentialProvider object created in the previous step to the client builder by passing it to the CredentialsProvider object() method as shown below." }, { "code": null, "e": 34750, "s": 34673, "text": "clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);\n" }, { "code": null, "e": 34844, "s": 34750, "text": "Build the CloseableHttpClient object using the build() method of the HttpClientBuilder class." }, { "code": null, "e": 34900, "s": 34844, "text": "CloseableHttpClient httpclient = clientbuilder.build()\n" }, { "code": null, "e": 35013, "s": 34900, "text": "Create a HttpRequest object by instantiating the HttpGet class. Execute this request using\nthe execute() method." }, { "code": null, "e": 35195, "s": 35013, "text": "//Creating a HttpGet object\nHttpGet httpget = new HttpGet(\"https://www.tutorialspoint.com/ \");\n\n//Executing the Get request\nHttpResponse httpresponse = httpclient.execute(httpget);\n" }, { "code": null, "e": 35335, "s": 35195, "text": "Following is an example program which demonstrates the execution of a HTTP request against a target site that requires user authentication." }, { "code": null, "e": 37373, "s": 35335, "text": "import org.apache.http.Header;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.Credentials;\nimport org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.CredentialsProvider;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\n\npublic class UserAuthenticationExample {\n \n public static void main(String args[]) throws Exception{\n \n //Create an object of credentialsProvider\n CredentialsProvider credentialsPovider = new BasicCredentialsProvider();\n\n //Set the credentials\n AuthScope scope = new AuthScope(\"https://www.tutorialspoint.com/questions/\", 80);\n \n Credentials credentials = new UsernamePasswordCredentials(\"USERNAME\", \"PASSWORD\");\n credentialsPovider.setCredentials(scope,credentials);\n\n //Creating the HttpClientBuilder\n HttpClientBuilder clientbuilder = HttpClients.custom();\n\n //Setting the credentials\n clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider);\n\n //Building the CloseableHttpClient object\n CloseableHttpClient httpclient = clientbuilder.build();\n\n //Creating a HttpGet object\n HttpGet httpget = new HttpGet(\"https://www.tutorialspoint.com/questions/index.php\");\n\n //Printing the method used\n System.out.println(httpget.getMethod()); \n\n //Executing the Get request\n HttpResponse httpresponse = httpclient.execute(httpget);\n\n //Printing the status line\n System.out.println(httpresponse.getStatusLine());\n int statusCode = httpresponse.getStatusLine().getStatusCode();\n System.out.println(statusCode);\n\n Header[] headers= httpresponse.getAllHeaders();\n for (int i = 0; i<headers.length;i++) {\n System.out.println(headers[i].getName());\n }\n }\n}" }, { "code": null, "e": 37437, "s": 37373, "text": "On executing, the above program generates the following output." }, { "code": null, "e": 37462, "s": 37437, "text": "GET\nHTTP/1.1 200 OK\n200\n" }, { "code": null, "e": 37598, "s": 37462, "text": "A Proxy server is an intermediary server between the client and the internet. Proxy servers offer the following basic functionalities −" }, { "code": null, "e": 37634, "s": 37598, "text": "Firewall and network data filtering" }, { "code": null, "e": 37670, "s": 37634, "text": "Firewall and network data filtering" }, { "code": null, "e": 37697, "s": 37670, "text": "Network connection sharing" }, { "code": null, "e": 37724, "s": 37697, "text": "Network connection sharing" }, { "code": null, "e": 37737, "s": 37724, "text": "Data caching" }, { "code": null, "e": 37750, "s": 37737, "text": "Data caching" }, { "code": null, "e": 37850, "s": 37750, "text": "Using HttpClient library, you can send a HTTP request using a proxy. Follow the steps given below −" }, { "code": null, "e": 38049, "s": 37850, "text": "Instantiate the HttpHost class of the org.apache.http package by passing a string parameter representing the name of the proxy host, (from which you need the requests to be sent) to its constructor." }, { "code": null, "e": 38139, "s": 38049, "text": "//Creating an HttpHost object for proxy\nHttpHost proxyHost = new HttpHost(\"localhost\"); \n" }, { "code": null, "e": 38251, "s": 38139, "text": "In the same way, create another HttpHost object to represent the target host to which requests need to be sent." }, { "code": null, "e": 38343, "s": 38251, "text": "//Creating an HttpHost object for target\nHttpHost targetHost = new HttpHost(\"google.com\");\n" }, { "code": null, "e": 38608, "s": 38343, "text": "The HttpRoutePlanner interface computes a route to a specified host. Create an object of this interface by instantiating the DefaultProxyRoutePlanner class, an implementation of this interface. As a parameter to its constructor, pass the above created proxy host −" }, { "code": null, "e": 38715, "s": 38608, "text": "//creating a RoutePlanner object\nHttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost);\n" }, { "code": null, "e": 38894, "s": 38715, "text": "Using the custom() method of the HttpClients class, create a HttpClientBuilder object and, to this object set the route planner created above, using the setRoutePlanner() method." }, { "code": null, "e": 39073, "s": 38894, "text": "//Setting the route planner to the HttpClientBuilder object\nHttpClientBuilder clientBuilder = HttpClients.custom();\n\nclientBuilder = clientBuilder.setRoutePlanner(routePlanner);\n" }, { "code": null, "e": 39141, "s": 39073, "text": "Build the CloseableHttpClient object by calling the build() method." }, { "code": null, "e": 39231, "s": 39141, "text": "//Building a CloseableHttpClient\nCloseableHttpClient httpClient = clientBuilder.build();\n" }, { "code": null, "e": 39293, "s": 39231, "text": "Create a HTTP GET request by instantiating the HttpGet class." }, { "code": null, "e": 39359, "s": 39293, "text": "//Creating an HttpGet object\nHttpGet httpGet = new HttpGet(\"/\");\n" }, { "code": null, "e": 39513, "s": 39359, "text": "One of the variants of the execute() method accepts an HttpHost and HttpRequest objects and executes the request. Execute the request using this method −" }, { "code": null, "e": 39612, "s": 39513, "text": "//Executing the Get request\nHttpResponse httpResponse = httpclient.execute(targetHost, httpGet); \n" }, { "code": null, "e": 39847, "s": 39612, "text": "Following example demonstrates how to send a HTTP request to a server via proxy. In this\nexample, we are sending a HTTP GET request to google.com via localhost. We have printed the headers of the response and the body of the response." }, { "code": null, "e": 41753, "s": 39847, "text": "import org.apache.http.Header;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.conn.routing.HttpRoutePlanner;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.impl.conn.DefaultProxyRoutePlanner;\nimport org.apache.http.util.EntityUtils;\n\npublic class RequestViaProxyExample {\n\n public static void main(String args[]) throws Exception{\n \n //Creating an HttpHost object for proxy\n HttpHost proxyhost = new HttpHost(\"localhost\");\n\n //Creating an HttpHost object for target\n HttpHost targethost = new HttpHost(\"google.com\");\n \n //creating a RoutePlanner object\n HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyhost);\n\n //Setting the route planner to the HttpClientBuilder object\n HttpClientBuilder clientBuilder = HttpClients.custom();\n clientBuilder = clientBuilder.setRoutePlanner(routePlanner);\n\n //Building a CloseableHttpClient\n CloseableHttpClient httpclient = clientBuilder.build();\n\n //Creating an HttpGet object\n HttpGet httpget = new HttpGet(\"/\");\n\n //Executing the Get request\n HttpResponse httpresponse = httpclient.execute(targethost, httpget);\n\n //Printing the status line\n System.out.println(httpresponse.getStatusLine());\n\n //Printing all the headers of the response\n Header[] headers = httpresponse.getAllHeaders();\n \n for (int i = 0; i < headers.length; i++) {\n System.out.println(headers[i]);\n }\n \n //Printing the body of the response\n HttpEntity entity = httpresponse.getEntity();\n\n if (entity != null) {\n System.out.println(EntityUtils.toString(entity));\n }\n }\n}" }, { "code": null, "e": 41818, "s": 41753, "text": "On executing, the above program generates the following output −" }, { "code": null, "e": 42090, "s": 41818, "text": "HTTP/1.1 200 OK\nDate: Sun, 23 Dec 2018 10:21:47 GMT\nServer: Apache/2.4.9 (Win64) PHP/5.5.13\nLast-Modified: Tue, 24 Jun 2014 10:46:24 GMT\nETag: \"2e-4fc92abc3c000\"\nAccept-Ranges: bytes\nContent-Length: 46\nContent-Type: text/html\n<html><body><h1>It works!</h1></body></html>\n" }, { "code": null, "e": 42257, "s": 42090, "text": "In this chapter, we will learn how to create a HttpRequest authenticated using username and password and tunnel it through a proxy to a target host, using an example." }, { "code": null, "e": 42475, "s": 42257, "text": "The CredentialsProvider Interface maintains a collection to hold the user login credentials. You can create its object by instantiating the BasicCredentialsProvider class, the default implementation of this interface." }, { "code": null, "e": 42549, "s": 42475, "text": "CredentialsProvider credentialsPovider = new BasicCredentialsProvider();\n" }, { "code": null, "e": 42689, "s": 42549, "text": "You can set the required credentials to the CredentialsProvider object using the setCredentials() method. This method accepts two objects −" }, { "code": null, "e": 42812, "s": 42689, "text": "AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name." }, { "code": null, "e": 42935, "s": 42812, "text": "AuthScope object − Authentication scope specifying the details like hostname, port number, and authentication scheme name." }, { "code": null, "e": 43099, "s": 42935, "text": "Credentials object − Specifying the credentials (username, password). Set the credentials using the setCredentials() method for both host and proxy as shown below." }, { "code": null, "e": 43263, "s": 43099, "text": "Credentials object − Specifying the credentials (username, password). Set the credentials using the setCredentials() method for both host and proxy as shown below." }, { "code": null, "e": 43499, "s": 43263, "text": "credsProvider.setCredentials(new AuthScope(\"example.com\", 80), new\n UsernamePasswordCredentials(\"user\", \"mypass\"));\ncredsProvider.setCredentials(new AuthScope(\"localhost\", 8000), new\n UsernamePasswordCredentials(\"abc\", \"passwd\"));\n" }, { "code": null, "e": 43594, "s": 43499, "text": "Create a HttpClientBuilder using the custom() method of the HttpClients class as shown below −" }, { "code": null, "e": 43684, "s": 43594, "text": "//Creating the HttpClientBuilder\nHttpClientBuilder clientbuilder = HttpClients.custom();\n" }, { "code": null, "e": 43878, "s": 43684, "text": "You can set the CredentialsProvider object to a HttpClientBuilder object using the setDefaultCredentialsProvider() method. Pass the previously created CredentialsProvider object to this method." }, { "code": null, "e": 43955, "s": 43878, "text": "clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);\n" }, { "code": null, "e": 44018, "s": 43955, "text": "Build the CloseableHttpClient object using the build() method." }, { "code": null, "e": 44075, "s": 44018, "text": "CloseableHttpClient httpclient = clientbuilder.build();\n" }, { "code": null, "e": 44146, "s": 44075, "text": "Create the target and proxy hosts by instantiating the HttpHost class." }, { "code": null, "e": 44302, "s": 44146, "text": "//Creating the target and proxy hosts\nHttpHost target = new HttpHost(\"example.com\", 80, \"http\");\nHttpHost proxy = new HttpHost(\"localhost\", 8000, \"http\");\n" }, { "code": null, "e": 44535, "s": 44302, "text": "Create a RequestConfig.Builder object using the custom() method. Set the previously created proxyHost object to the RequestConfig.Builder using the setProxy() method. Finally, build the RequestConfig object using the build() method." }, { "code": null, "e": 44718, "s": 44535, "text": "RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();\nreqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);\nRequestConfig config = reqconfigconbuilder.build();\n" }, { "code": null, "e": 44874, "s": 44718, "text": "Create a HttpGet object by instantiating the HttpGet class. Set the config object created in the previous step to this object using the setConfig() method." }, { "code": null, "e": 45011, "s": 44874, "text": "//Create the HttpGet request object\nHttpGet httpGet = new HttpGet(\"/\");\n\n//Setting the config to the request\nhttpget.setConfig(config);\n" }, { "code": null, "e": 45132, "s": 45011, "text": "Execute the request by passing the HttpHost object (target) and request (HttpGet) as parameters to the execute() method." }, { "code": null, "e": 45202, "s": 45132, "text": "HttpResponse httpResponse = httpclient.execute(targetHost, httpget);\n" }, { "code": null, "e": 45308, "s": 45202, "text": "Following example demonstrates how to execute a HTTP request through a proxy using username and password." }, { "code": null, "e": 47433, "s": 45308, "text": "import org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.CredentialsProvider;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\n\npublic class ProxyAuthenticationExample {\n public static void main(String[] args) throws Exception {\n\n //Creating the CredentialsProvider object\n CredentialsProvider credsProvider = new BasicCredentialsProvider();\n\n //Setting the credentials\n credsProvider.setCredentials(new AuthScope(\"example.com\", 80), \n new UsernamePasswordCredentials(\"user\", \"mypass\"));\n credsProvider.setCredentials(new AuthScope(\"localhost\", 8000), \n new UsernamePasswordCredentials(\"abc\", \"passwd\"));\n\n //Creating the HttpClientBuilder\n HttpClientBuilder clientbuilder = HttpClients.custom();\n\n //Setting the credentials\n clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);\n \n //Building the CloseableHttpClient object\n CloseableHttpClient httpclient = clientbuilder.build();\n\n\n //Create the target and proxy hosts\n HttpHost targetHost = new HttpHost(\"example.com\", 80, \"http\");\n HttpHost proxyHost = new HttpHost(\"localhost\", 8000, \"http\");\n\n //Setting the proxy\n RequestConfig.Builder reqconfigconbuilder= RequestConfig.custom();\n reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost);\n RequestConfig config = reqconfigconbuilder.build();\n\n //Create the HttpGet request object\n HttpGet httpget = new HttpGet(\"/\");\n\n //Setting the config to the request\n httpget.setConfig(config);\n \n //Printing the status line\n HttpResponse response = httpclient.execute(targetHost, httpget);\n System.out.println(response.getStatusLine());\n\n }\n}" }, { "code": null, "e": 47498, "s": 47433, "text": "On executing, the above program generates the following output −" }, { "code": null, "e": 47515, "s": 47498, "text": "HTTP/1.1 200 OK\n" }, { "code": null, "e": 47610, "s": 47515, "text": "Using the HttpClient library you can send a request or, login to a form by passing parameters." }, { "code": null, "e": 47659, "s": 47610, "text": "Follow the steps given below to login to a form." }, { "code": null, "e": 47874, "s": 47659, "text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object −" }, { "code": null, "e": 47937, "s": 47874, "text": "CloseableHttpClient httpClient = HttpClients.createDefault();\n" }, { "code": null, "e": 48111, "s": 47937, "text": "The class RequestBuilder is used to build request by adding parameters to it. If the request type is PUT or POST, it adds the parameters to the request as URL encoded entity" }, { "code": null, "e": 48182, "s": 48111, "text": "Create a RequestBuilder object (of type POST) using the post() method." }, { "code": null, "e": 48269, "s": 48182, "text": "//Building the post request object\nRequestBuilder reqbuilder = RequestBuilder.post();\n" }, { "code": null, "e": 48400, "s": 48269, "text": "Set the URI and parameters to the RequestBuilder object using the setUri() and addParameter() methods of the RequestBuilder class." }, { "code": null, "e": 48596, "s": 48400, "text": "//Set URI and parameters\nRequestBuilder reqbuilder = reqbuilder.setUri(\"http://httpbin.org/post\");\nreqbuilder = reqbuilder1.addParameter(\"Name\", \"username\").addParameter(\"password\", \"password\");\n" }, { "code": null, "e": 48693, "s": 48596, "text": "After setting the required parameters, build the HttpUriRequest object using the build() method." }, { "code": null, "e": 48778, "s": 48693, "text": "//Building the HttpUriRequest object\nHttpUriRequest httppost = reqbuilder2.build();\n" }, { "code": null, "e": 48955, "s": 48778, "text": "The execute method of the CloseableHttpClient object accepts a HttpUriRequest (interface) object (i.e. HttpGet, HttpPost, HttpPut, HttpHead etc.) and returns a response object." }, { "code": null, "e": 49051, "s": 48955, "text": "Execute the HttpUriRequest created in the previous steps by passing it to the execute()\nmethod." }, { "code": null, "e": 49132, "s": 49051, "text": "//Execute the request\nHttpResponse httpresponse = httpclient.execute(httppost);\n" }, { "code": null, "e": 49349, "s": 49132, "text": "Following example demonstrates how to logon to a form by sending login credentials. Here, we have sent two parameters − username and password to a form and tried to print the message entity and status of the request." }, { "code": null, "e": 50650, "s": 49349, "text": "import org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.client.methods.RequestBuilder;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\n\npublic class FormLoginExample {\n \n public static void main(String args[]) throws Exception {\n\n //Creating CloseableHttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n \n //Creating the RequestBuilder object\n RequestBuilder reqbuilder = RequestBuilder.post();\n\n //Setting URI and parameters\n RequestBuilder reqbuilder1 = reqbuilder.setUri(\"http://httpbin.org/post\");\n RequestBuilder reqbuilder2 = reqbuilder1.addParameter(\"Name\", \n \"username\").addParameter(\"password\", \"password\");\n\n //Building the HttpUriRequest object\n HttpUriRequest httppost = reqbuilder2.build();\n\n //Executing the request\n HttpResponse httpresponse = httpclient.execute(httppost);\n\n //Printing the status and the contents of the response\n System.out.println(EntityUtils.toString(httpresponse.getEntity()));\n System.out.println(httpresponse.getStatusLine());\n }\n}" }, { "code": null, "e": 50715, "s": 50650, "text": "On executing, the above program generates the following output −" }, { "code": null, "e": 51230, "s": 50715, "text": "{\n \"args\": {},\n \"data\": \"\",\n \"files\": {},\n \"form\": {\n \"Name\": \"username\",\n \"password\": \"password\"\n },\n \"headers\": {\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Connection\": \"close\",\n \"Content-Length\": \"31\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset = UTF-8\",\n \"Host\": \"httpbin.org\",\n \"User-Agent\": \"Apache-HttpClient/4.5.6 (Java/1.8.0_91)\"\n },\n \"json\": null,\n \"origin\": \"117.216.245.180\",\n \"url\": \"http://httpbin.org/post\"\n}\nHTTP/1.1 200 OK\n" }, { "code": null, "e": 51315, "s": 51230, "text": "If your form stores cookies, instead of creating default CloseableHttpClient object." }, { "code": null, "e": 51388, "s": 51315, "text": "Create a CookieStore object by instantiating the BasicCookieStore class." }, { "code": null, "e": 51481, "s": 51388, "text": "//Creating a BasicCookieStore object\nBasicCookieStore cookieStore = new BasicCookieStore();\n" }, { "code": null, "e": 51560, "s": 51481, "text": "Create a HttpClientBuilder using the custom() method of the HttpClients class." }, { "code": null, "e": 51656, "s": 51560, "text": "//Creating an HttpClientBuilder object\nHttpClientBuilder clientbuilder = HttpClients.custom();\n" }, { "code": null, "e": 51741, "s": 51656, "text": "Set the cookie store to the client builder using the setDefaultCookieStore() method." }, { "code": null, "e": 51869, "s": 51741, "text": "//Setting default cookie store to the client builder object\nClientbuilder = clientbuilder.setDefaultCookieStore(cookieStore); \n" }, { "code": null, "e": 51932, "s": 51869, "text": "Build the CloseableHttpClient object using the build() method." }, { "code": null, "e": 52032, "s": 51932, "text": "//Building the CloseableHttpClient object\nCloseableHttpClient httpclient = clientbuilder1.build();\n" }, { "code": null, "e": 52115, "s": 52032, "text": "Build the HttpUriRequest object as specified above by passing execute the request." }, { "code": null, "e": 52209, "s": 52115, "text": "If the page stores cookies, the parameters you have passed will be added to the cookie store." }, { "code": null, "e": 52352, "s": 52209, "text": "You can print the contents of the CookieStore object where you can see your parameters (along with the previous ones the page stored in case)." }, { "code": null, "e": 52553, "s": 52352, "text": "To print the cookies, get all the cookies from the CookieStore object using the getCookies() method. This method returns a List object. Using Iterator, print the list objects contents as shown below −" }, { "code": null, "e": 52740, "s": 52553, "text": "//Printing the cookies\nList list = cookieStore.getCookies();\n\nSystem.out.println(\"list of cookies\");\nIterator it = list.iterator();\nif(it.hasNext()) {\n System.out.println(it.next());\n}" }, { "code": null, "e": 52853, "s": 52740, "text": "Cookies are text files stored on the client computer and they are kept for various information tracking purpose." }, { "code": null, "e": 52928, "s": 52853, "text": "HttpClient provides support for cookies you can create and manage cookies." }, { "code": null, "e": 53002, "s": 52928, "text": "Follow the steps given below to create a cookie using HttpClient library." }, { "code": null, "e": 53197, "s": 53002, "text": "The CookieStore interface represents the abstract store for Cookie objects. You can create a cookie store by instantiating the BasicCookieStore class, a default implementation of this interface." }, { "code": null, "e": 53282, "s": 53197, "text": "//Creating the CookieStore object\nCookieStore cookieStore = new BasicCookieStore();\n" }, { "code": null, "e": 53587, "s": 53282, "text": "In addition to the functionalities of a cookie, ClientCookie can get the original cookies in the server. You can create a client cookie by instantiating the BasicClientCookie class. To the constructor of this class, you need to pass the key-value pair that you desired to store in that particular cookie." }, { "code": null, "e": 53684, "s": 53587, "text": "//Creating client cookie\nBasicClientCookie clientCookie = new BasicClientCookie(\"name\",\"Raju\");\n" }, { "code": null, "e": 53819, "s": 53684, "text": "To a client cookie, you can set/remove path, value, version, expiry date, domain, comment, and attribute using the respective methods." }, { "code": null, "e": 54062, "s": 53819, "text": "Calendar myCal = new GregorianCalendar(2018, 9, 26);\nDate expiryDate = myCal.getTime();\nclientcookie.setExpiryDate(expiryDate);\nclientcookie.setPath(\"/\");\nclientcookie.setSecure(true);\nclientcookie.setValue(\"25\");\nclientcookie.setVersion(5);\n" }, { "code": null, "e": 54162, "s": 54062, "text": "You can add cookies to the cookie store using the addCookie() method of the BasicCookieStore class." }, { "code": null, "e": 54207, "s": 54162, "text": "Add the required cookies to the Cookiestore." }, { "code": null, "e": 54290, "s": 54207, "text": "//Adding the created cookies to cookie store\ncookiestore.addCookie(clientcookie);\n" }, { "code": null, "e": 54503, "s": 54290, "text": "Following example demonstrates how to create cookies and add them to a cookie store. Here, we created a cookie store, a bunch of cookies by setting the domain and path values, and added these to the cookie store." }, { "code": null, "e": 55620, "s": 54503, "text": "import org.apache.http.client.CookieStore;\nimport org.apache.http.impl.client.BasicCookieStore;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\npublic class CookieHandlingExample {\n \n public static void main(String args[]) throws Exception{\n \n //Creating the CookieStore object\n CookieStore cookiestore = new BasicCookieStore();\n \n //Creating client cookies\n BasicClientCookie clientcookie1 = new BasicClientCookie(\"name\",\"Raju\");\n BasicClientCookie clientcookie2 = new BasicClientCookie(\"age\",\"28\");\n BasicClientCookie clientcookie3 = new BasicClientCookie(\"place\",\"Hyderabad\");\n\n //Setting domains and paths to the created cookies\n clientcookie1.setDomain(\".sample.com\");\n clientcookie2.setDomain(\".sample.com\");\n clientcookie3.setDomain(\".sample.com\");\n\n clientcookie1.setPath(\"/\");\n clientcookie2.setPath(\"/\");\n clientcookie3.setPath(\"/\");\n \n //Adding the created cookies to cookie store\n cookiestore.addCookie(clientcookie1);\n cookiestore.addCookie(clientcookie2);\n cookiestore.addCookie(clientcookie3);\n }\n}" }, { "code": null, "e": 55800, "s": 55620, "text": "You can get the cookies added to a cookie store using getCookies() method of the asicCookieStore class. This method returns a list which holds all the cookies in the cookie store." }, { "code": null, "e": 55881, "s": 55800, "text": "You can print the contents of a cookie store using the Iterator as shown below −" }, { "code": null, "e": 56078, "s": 55881, "text": "//Retrieving the cookies\nList list = cookieStore.getCookies();\n\n//Creating an iterator to the obtained list\nIterator it = list.iterator();\nwhile(it.hasNext()) {\n System.out.println(it.next());\n}" }, { "code": null, "e": 56237, "s": 56078, "text": "Following example demonstrates how to retrieve cookies from a cookie store. Here, we are adding a bunch of cookies to a cookie store and retrieving them back." }, { "code": null, "e": 57357, "s": 56237, "text": "import org.apache.http.client.CookieStore;\nimport org.apache.http.impl.client.BasicCookieStore;\nimport org.apache.http.impl.cookie.BasicClientCookie;\n\npublic class CookieHandlingExample {\n \n public static void main(String args[]) throws Exception{\n \n //Creating the CookieStore object\n CookieStore cookiestore = new BasicCookieStore();\n \n //Creating client cookies\n BasicClientCookie clientcookie1 = new BasicClientCookie(\"name\",\"Raju\");\n BasicClientCookie clientcookie2 = new BasicClientCookie(\"age\",\"28\");\n BasicClientCookie clientcookie3 = new BasicClientCookie(\"place\",\"Hyderabad\");\n\n //Setting domains and paths to the created cookies\n clientcookie1.setDomain(\".sample.com\");\n clientcookie2.setDomain(\".sample.com\");\n clientcookie3.setDomain(\".sample.com\");\n\n clientcookie1.setPath(\"/\");\n clientcookie2.setPath(\"/\");\n clientcookie3.setPath(\"/\");\n \n //Adding the created cookies to cookie store\n cookiestore.addCookie(clientcookie1);\n cookiestore.addCookie(clientcookie2);\n cookiestore.addCookie(clientcookie3);\n }\n}" }, { "code": null, "e": 57417, "s": 57357, "text": "On executing, this program generates the following output −" }, { "code": null, "e": 57670, "s": 57417, "text": "[version: 0][name: age][value: 28][domain: .sample.com][path: /][expiry: null]\n[version: 0][name: name][value: Raju][domain: my.example.com][path: /][expiry:\nnull]\n[version: 0][name: place][value: Hyderabad][domain: .sample.com][path:\n/][expiry: null]\n" }, { "code": null, "e": 57854, "s": 57670, "text": "A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources." }, { "code": null, "e": 57949, "s": 57854, "text": "You can execute requests from multiple threads by writing a multithreaded HttpClient program.\n" }, { "code": null, "e": 58163, "s": 57949, "text": "If you want to execute multiple client requests from threads consecutively, you need to create a ClientConnectionPoolManager. It maintains a pool of HttpClientConnections and serves multiple requests from threads." }, { "code": null, "e": 58408, "s": 58163, "text": "The connections manager pools the connections based on the route. If the manager has connections for a particular route, then it serves new requests in those routes by leasing an existing connection from the pool, instead of creating a new one." }, { "code": null, "e": 58469, "s": 58408, "text": "Follow the steps to execute requests from multiple threads −" }, { "code": null, "e": 58574, "s": 58469, "text": "Create the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class." }, { "code": null, "e": 58670, "s": 58574, "text": "PoolingHttpClientConnectionManager connManager = new\n PoolingHttpClientConnectionManager(); \n" }, { "code": null, "e": 58752, "s": 58670, "text": "Set the maximum number of connections in the pool using the setMaxTotal() method." }, { "code": null, "e": 58836, "s": 58752, "text": "//Set the maximum number of connections in the pool\nconnManager.setMaxTotal(100); \n" }, { "code": null, "e": 58957, "s": 58836, "text": "Create a ClientBuilder Object by setting the connection manager using the setConnectionManager() method as shown below −" }, { "code": null, "e": 59048, "s": 58957, "text": "HttpClientBuilder clientbuilder =\nHttpClients.custom().setConnectionManager(connManager);\n" }, { "code": null, "e": 59141, "s": 59048, "text": "Instantiate the HttpGet class by passing the desired URI to its constructor as a parameter.\n" }, { "code": null, "e": 59247, "s": 59141, "text": "HttpGet httpget1 = new HttpGet(\"URI1\");\nHttpGet httpget2 = new HttpGet(\"URI2\");\n. . . . . . . . . . . . \n" }, { "code": null, "e": 59419, "s": 59247, "text": "Make sure that you have created a class, made it a thread (either by extending the thread class or, by implementing the Runnable interface) and implemented the run method." }, { "code": null, "e": 59554, "s": 59419, "text": "public class ClientMultiThreaded extends Thread {\n public void run() {\n //Run method implementation . . . . . . . . . .\n }\n}\n" }, { "code": null, "e": 59647, "s": 59554, "text": "Create thread objects by instantiating the Thread class (ClientMultiThreaded) created above." }, { "code": null, "e": 59753, "s": 59647, "text": "Pass a HttpClient object, respective HttpGet object and, an integer representing the ID to\nthese threads." }, { "code": null, "e": 60151, "s": 59753, "text": "ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);\nClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . .\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n" }, { "code": null, "e": 60233, "s": 60151, "text": "Start all the threads using start() method and join them using the join method()." }, { "code": null, "e": 60340, "s": 60233, "text": "thread1.start();\nthread2.start();\n. . . . . . . .\nthread1.join();\nthread2.join();\n. . . . . . . . . . . .\n" }, { "code": null, "e": 60429, "s": 60340, "text": "Within the run method, execute the request, retrieve the response and print the results." }, { "code": null, "e": 60686, "s": 60429, "text": "Following example demonstrates the execution of HTTP requests simultaneously from multiple threads. In this example, we are trying to execute various requests from various threads and trying to print the status, and the number of bytes read by each client." }, { "code": null, "e": 63687, "s": 60686, "text": "import org.apache.http.HttpEntity;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.impl.conn.PoolingHttpClientConnectionManager;\nimport org.apache.http.util.EntityUtils;\n\npublic class ClientMultiThreaded extends Thread {\n CloseableHttpClient httpClient;\n HttpGet httpget;\n int id;\n \n public ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpget,\n int id) {\n this.httpClient = httpClient;\n this.httpget = httpget;\n this.id = id;\n }\n @Override\n public void run() {\n try{\n //Executing the request\n CloseableHttpResponse httpresponse = httpClient.execute(httpget);\n\n //Displaying the status of the request.\n System.out.println(\"status of thread \"+id+\":\"+httpresponse.getStatusLine());\n\n //Retrieving the HttpEntity and displaying the no.of bytes read\n HttpEntity entity = httpresponse.getEntity();\n if (entity != null) {\n System.out.println(\"Bytes read by thread thread \"+id+\":\n \"+EntityUtils.toByteArray(entity).length);\n }\n }catch(Exception e) {\n System.out.println(e.getMessage());\n }\n }\n \n public static void main(String[] args) throws Exception {\n\n //Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class.\n PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();\n\n //Set the maximum number of connections in the pool\n connManager.setMaxTotal(100);\n\n //Create a ClientBuilder Object by setting the connection manager\n HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager);\n \n //Build the CloseableHttpClient object using the build() method.\n CloseableHttpClient httpclient = clientbuilder.build();\n\n //Creating the HttpGet requests\n HttpGet httpget1 = new HttpGet(\"http://www.tutorialspoint.com/\");\n HttpGet httpget2 = new HttpGet(\"http://www.google.com/\");\n HttpGet httpget3 = new HttpGet(\"https://www.qries.com/\");\n HttpGet httpget4 = new HttpGet(\"https://in.yahoo.com/\");\n \n //Creating the Thread objects\n ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);\n ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);\n ClientMultiThreaded thread3 = new ClientMultiThreaded(httpclient,httpget3, 3);\n ClientMultiThreaded thread4 = new ClientMultiThreaded(httpclient,httpget4, 4);\n\n //Starting all the threads\n thread1.start();\n thread2.start();\n thread3.start();\n thread4.start();\n\n //Joining all the threads\n thread1.join();\n thread2.join();\n thread3.join();\n thread4.join();\n }\n}" }, { "code": null, "e": 63752, "s": 63687, "text": "On executing, the above program generates the following output −" }, { "code": null, "e": 64046, "s": 63752, "text": "status of thread 1: HTTP/1.1 200 OK\nBytes read by thread thread 1: 36907\nstatus of thread 2: HTTP/1.1 200 OK\nBytes read by thread thread 2: 13725\nstatus of thread 3: HTTP/1.1 200 OK\nBytes read by thread thread 3: 17319\nstatus of thread 4: HTTP/1.1 200 OK\nBytes read by thread thread 4: 127018\n" }, { "code": null, "e": 64249, "s": 64046, "text": "Using Secure Socket Layer, you can establish a secured connection between the client and\nserver. It helps to safeguard sensitive information such as credit card numbers, usernames, passwords, pins, etc." }, { "code": null, "e": 64349, "s": 64249, "text": "You can make connections more secure by creating your own SSL context using the HttpClient library." }, { "code": null, "e": 64429, "s": 64349, "text": "Follow the steps given below to customize SSLContext using HttpClient library −" }, { "code": null, "e": 64560, "s": 64429, "text": "SSLContextBuilder is the builder for the SSLContext objects. Create its object using the custom() method of the SSLContexts class." }, { "code": null, "e": 64650, "s": 64560, "text": "//Creating SSLContextBuilder object\nSSLContextBuilder SSLBuilder = SSLContexts.custom();\n" }, { "code": null, "e": 64933, "s": 64650, "text": "In the path Java_home_directory/jre/lib/security/, you can find a file named cacerts. Save this as your key store file (with extension .jks). Load the keystore file and, its password (which is changeit by default) using the loadTrustMaterial() method of the SSLContextBuilder class." }, { "code": null, "e": 65077, "s": 64933, "text": "//Loading the Keystore file\nFile file = new File(\"mykeystore.jks\");\nSSLBuilder = SSLBuilder.loadTrustMaterial(file, \"changeit\".toCharArray());\n" }, { "code": null, "e": 65196, "s": 65077, "text": "An SSLContext object represents a secure socket protocol implementation. Build an SSLContext using the build() method." }, { "code": null, "e": 65267, "s": 65196, "text": "//Building the SSLContext\nSSLContext sslContext = SSLBuilder.build();\n" }, { "code": null, "e": 65473, "s": 65267, "text": "SSLConnectionSocketFactory is a layered socket factory for TSL and SSL connections. Using this, you can verify the Https server using a list of trusted certificates and authenticate the given Https server." }, { "code": null, "e": 65677, "s": 65473, "text": "You can create this in many ways. Depending on the way you create an SSLConnectionSocketFactory object, you can allow all hosts, allow only self-signed\ncertificates, allow only particular protocols, etc." }, { "code": null, "e": 65963, "s": 65677, "text": "To allow only particular protocols, create SSLConnectionSocketFactory object by passing an SSLContext object, string array representing the protocols need to be supported, string array representing the cipher suits need to be supported and a HostnameVerifier object to its constructor." }, { "code": null, "e": 66101, "s": 65963, "text": "new SSLConnectionSocketFactory(sslcontext, new String[]{\"TLSv1\"}, null, \n SSLConnectionSocketFactory.getDefaultHostnameVerifier());\n" }, { "code": null, "e": 66228, "s": 66101, "text": "To allow all hosts, create SSLConnectionSocketFactory object by passing a SSLContext object and a NoopHostnameVerifier object." }, { "code": null, "e": 66419, "s": 66228, "text": "//Creating SSLConnectionSocketFactory SSLConnectionSocketFactory object\nSSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());\n" }, { "code": null, "e": 66506, "s": 66419, "text": "Create an HttpClientBuilder object using the custom() method of the HttpClients class." }, { "code": null, "e": 66592, "s": 66506, "text": "//Creating HttpClientBuilder\nHttpClientBuilder clientbuilder = HttpClients.custom();\n" }, { "code": null, "e": 66699, "s": 66592, "text": "Set the SSLConnectionSocketFactory object to the HttpClientBuilder using the setSSLSocketFactory() method." }, { "code": null, "e": 66810, "s": 66699, "text": "//Setting the SSLConnectionSocketFactory\nclientbuilder = clientbuilder.setSSLSocketFactory(sslConSocFactory);\n" }, { "code": null, "e": 66878, "s": 66810, "text": "Build the CloseableHttpClient object by calling the build() method." }, { "code": null, "e": 66970, "s": 66878, "text": "//Building the CloseableHttpClient\nCloseableHttpClient httpclient = clientbuilder.build();\n" }, { "code": null, "e": 67085, "s": 66970, "text": "The HttpGet class represents the HTTP GET request which retrieves the information of\nthe given server using a URI." }, { "code": null, "e": 67188, "s": 67085, "text": "Create a HTTP GET request by instantiating the HttpGet class by passing a string representing the URI." }, { "code": null, "e": 67275, "s": 67188, "text": "//Creating the HttpGet request\nHttpGet httpget = new HttpGet(\"https://example.com/\");\n" }, { "code": null, "e": 67323, "s": 67275, "text": "Execute the request using the execute() method." }, { "code": null, "e": 67405, "s": 67323, "text": "//Executing the request\nHttpResponse httpresponse = httpclient.execute(httpget);\n" }, { "code": null, "e": 67475, "s": 67405, "text": "Following example demonstrates the customization of the SSLContrext −" }, { "code": null, "e": 69563, "s": 67475, "text": "import java.io.File;\nimport javax.net.ssl.SSLContext;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.conn.ssl.NoopHostnameVerifier;\nimport org.apache.http.conn.ssl.SSLConnectionSocketFactory;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.ssl.SSLContextBuilder;\nimport org.apache.http.ssl.SSLContexts;\nimport org.apache.http.util.EntityUtils;\n\npublic class ClientCustomSSL {\n \n public final static void main(String[] args) throws Exception {\n\n //Creating SSLContextBuilder object\n SSLContextBuilder SSLBuilder = SSLContexts.custom();\n \n //Loading the Keystore file\n File file = new File(\"mykeystore.jks\");\n SSLBuilder = SSLBuilder.loadTrustMaterial(file,\n \"changeit\".toCharArray());\n\n //Building the SSLContext usiong the build() method\n SSLContext sslcontext = SSLBuilder.build();\n \n //Creating SSLConnectionSocketFactory object\n SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());\n \n //Creating HttpClientBuilder\n HttpClientBuilder clientbuilder = HttpClients.custom();\n\n //Setting the SSLConnectionSocketFactory\n clientbuilder = clientbuilder.setSSLSocketFactory(sslConSocFactory);\n\n //Building the CloseableHttpClient\n CloseableHttpClient httpclient = clientbuilder.build();\n \n //Creating the HttpGet request\n HttpGet httpget = new HttpGet(\"https://example.com/\");\n \n //Executing the request\n HttpResponse httpresponse = httpclient.execute(httpget);\n\n //printing the status line\n System.out.println(httpresponse.getStatusLine());\n\n //Retrieving the HttpEntity and displaying the no.of bytes read\n HttpEntity entity = httpresponse.getEntity();\n if (entity != null) {\n System.out.println(EntityUtils.toByteArray(entity).length);\n } \n }\n}" }, { "code": null, "e": 69627, "s": 69563, "text": "On executing, the above program generates the following output." }, { "code": null, "e": 69649, "s": 69627, "text": "HTTP/1.1 200 OK\n1270\n" }, { "code": null, "e": 69854, "s": 69649, "text": "Using HttpClient, we can perform Multipart upload, i.e., we can upload larger objects in\nsmaller parts. In this chapter, we demonstrate the multipart upload in HTTP client by uploading a simple text file." }, { "code": null, "e": 69909, "s": 69854, "text": "In general, any multipart upload contains three parts." }, { "code": null, "e": 69934, "s": 69909, "text": "Initiation of the upload" }, { "code": null, "e": 69959, "s": 69934, "text": "Initiation of the upload" }, { "code": null, "e": 69986, "s": 69959, "text": "Uploading the object parts" }, { "code": null, "e": 70013, "s": 69986, "text": "Uploading the object parts" }, { "code": null, "e": 70045, "s": 70013, "text": "Completing the Multipart upload" }, { "code": null, "e": 70077, "s": 70045, "text": "Completing the Multipart upload" }, { "code": null, "e": 70156, "s": 70077, "text": "For the multipart upload using HttpClient, we need to follow the below steps −" }, { "code": null, "e": 70184, "s": 70156, "text": "Create a multipart builder." }, { "code": null, "e": 70212, "s": 70184, "text": "Create a multipart builder." }, { "code": null, "e": 70237, "s": 70212, "text": "Add desired parts to it." }, { "code": null, "e": 70262, "s": 70237, "text": "Add desired parts to it." }, { "code": null, "e": 70316, "s": 70262, "text": "Complete the build and obtain a multipart HttpEntity." }, { "code": null, "e": 70370, "s": 70316, "text": "Complete the build and obtain a multipart HttpEntity." }, { "code": null, "e": 70423, "s": 70370, "text": "Build request by setting the above muti-part entity." }, { "code": null, "e": 70476, "s": 70423, "text": "Build request by setting the above muti-part entity." }, { "code": null, "e": 70497, "s": 70476, "text": "Execute the request." }, { "code": null, "e": 70518, "s": 70497, "text": "Execute the request." }, { "code": null, "e": 70601, "s": 70518, "text": "Following are the steps to upload a multipart entity using the HttpClient library." }, { "code": null, "e": 70816, "s": 70601, "text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method, create an HttpClient object −" }, { "code": null, "e": 70917, "s": 70816, "text": "//Creating CloseableHttpClient object\nCloseableHttpClient httpclient = HttpClients.createDefault();\n" }, { "code": null, "e": 71093, "s": 70917, "text": "FileBody class represents the binary body part backed by a file. Instantiate this class by passing a File object and a ContentType object representing the type of the content." }, { "code": null, "e": 71255, "s": 71093, "text": "//Creating a File object\nFile file = new File(\"sample.txt\");\n\n//Creating the FileBody object\nFileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);\n" }, { "code": null, "e": 71404, "s": 71255, "text": "The MultipartEntityBuilder class is used to build the multi-part HttpEntity object. Create its object using the create() method (of the same class)." }, { "code": null, "e": 71515, "s": 71404, "text": "//Creating the MultipartEntityBuilder\nMultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();\n" }, { "code": null, "e": 71653, "s": 71515, "text": "A MultipartEntityBuilder has three modes: STRICT, RFC6532, and BROWSER_COMPATIBLE. Set it to the desired mode using the setMode() method." }, { "code": null, "e": 71734, "s": 71653, "text": "//Setting the mode\nentitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n" }, { "code": null, "e": 71927, "s": 71734, "text": "Using the methods addTextBody(), addPart() and, addBinaryBody(), you can add simple text, files, streams, and other objects to a MultipartBuilder. Add the desired contents using these methods." }, { "code": null, "e": 72097, "s": 71927, "text": "//Adding text\nentitybuilder.addTextBody(\"sample_text\", \"This is the text part of our file\");\n//Adding a file\nentitybuilder.addBinaryBody(\"image\", new File(\"logo.png\"));\n" }, { "code": null, "e": 72273, "s": 72097, "text": "You can build all these parts to a single entity using the build() method of the MultipartEntityBuilder class. Using this method, build all the parts into a single HttpEntity." }, { "code": null, "e": 72373, "s": 72273, "text": "//Building a single entity using the parts\nHttpEntity mutiPartHttpEntity = entityBuilder.build(); \n" }, { "code": null, "e": 72551, "s": 72373, "text": "The class RequestBuilder is used to build request by adding parameters to it. If the request is of type PUT or POST, it adds the parameters to the request as URL encoded entity." }, { "code": null, "e": 72698, "s": 72551, "text": "Create a RequestBuilder object (of type POST) using the post() method. And pass the Uri\nto which you wanted to send the request it as a parameter." }, { "code": null, "e": 72810, "s": 72698, "text": "//Building the post request object\nRequestBuilder reqbuilder = RequestBuilder.post(\"http://httpbin.org/post\");\n" }, { "code": null, "e": 72929, "s": 72810, "text": "Set the above created multipart entity to the RequestBuilder using the setEntity() method of the RequestBuilder class." }, { "code": null, "e": 73022, "s": 72929, "text": "//Setting the entity object to the RequestBuilder\nreqbuilder.setEntity(mutiPartHttpEntity);\n" }, { "code": null, "e": 73114, "s": 73022, "text": "Build a HttpUriRequest request object using the build() method of the RequestBuilder class." }, { "code": null, "e": 73192, "s": 73114, "text": "//Building the request\nHttpUriRequest multipartRequest = reqbuilder.build();\n" }, { "code": null, "e": 73322, "s": 73192, "text": "Using the execute() method, execute the request built in the previous step (bypassing the request as a parameter to this method)." }, { "code": null, "e": 73413, "s": 73322, "text": "//Executing the request\nHttpResponse httpresponse = httpclient.execute(multipartRequest);\n" }, { "code": null, "e": 73583, "s": 73413, "text": "Following example demonstrates how to send a multipart request using the HttpClient library. In this example, we are trying to send a multipart request backed by a file." }, { "code": null, "e": 75753, "s": 73583, "text": "import org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.client.methods.RequestBuilder;\nimport org.apache.http.entity.ContentType;\nimport org.apache.http.entity.mime.HttpMultipartMode;\nimport org.apache.http.entity.mime.MultipartEntityBuilder;\nimport org.apache.http.entity.mime.content.FileBody;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URISyntaxException;\n\npublic class MultipartUploadExample {\n \n public static void main(String args[]) throws Exception{\n\n //Creating CloseableHttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n \n //Creating a file object\n File file = new File(\"sample.txt\");\n\n //Creating the FileBody object\n FileBody filebody = new FileBody(file, ContentType.DEFAULT_BINARY);\n\n //Creating the MultipartEntityBuilder\n MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();\n\n //Setting the mode\n entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n\n //Adding text\n entitybuilder.addTextBody(\"sample_text\", \"This is the text part of our file\");\n\n //Adding a file\n entitybuilder.addBinaryBody(\"image\", new File(\"logo.png\"));\n\n //Building a single entity using the parts\n HttpEntity mutiPartHttpEntity = entitybuilder.build();\n\n //Building the RequestBuilder request object\n RequestBuilder reqbuilder = RequestBuilder.post(\"http://httpbin.org/post\");\n\n //Set the entity object to the RequestBuilder\n reqbuilder.setEntity(mutiPartHttpEntity);\n\n //Building the request\n HttpUriRequest multipartRequest = reqbuilder.build();\n\n //Executing the request\n HttpResponse httpresponse = httpclient.execute(multipartRequest);\n\n //Printing the status and the contents of the response\n System.out.println(EntityUtils.toString(httpresponse.getEntity()));\n System.out.println(httpresponse.getStatusLine());\n }\n} " }, { "code": null, "e": 75818, "s": 75753, "text": "On executing, the above program generates the following output −" }, { "code": null, "e": 76494, "s": 75818, "text": "{\n \"args\": {},\n \"data\": \"\",\n \"files\": {\n \"image\": \"data:application/octets66PohrH3IWNk1FzpohfdXPIfv9X3490FGcuXsHn9X0piCwomF/xdgADZ9GsfSyvLYAAAAAE\n lFTkSuQmCC\"\n },\n \"form\": {\n \"sample_text\": \"This is the text part of our file\"\n },\n \"headers\": {\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Connection\": \"close\",\n \"Content-Length\": \"11104\", \n \"Content-Type\": \"multipart/form-data;\n boundary=UFJbPHT7mTwpVq70LpZgCi5I2nvxd1g-I8Rt\",\n \"Host\": \"httpbin.org\",\n \"User-Agent\": \"Apache-HttpClient/4.5.6 (Java/1.8.0_91)\"\n },\n \"json\": null,\n \"origin\": \"117.216.245.180\",\n \"url\": \"http://httpbin.org/post\"\n}\nHTTP/1.1 200 OK\n" }, { "code": null, "e": 76529, "s": 76494, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 76548, "s": 76529, "text": " Arnab Chakraborty" }, { "code": null, "e": 76583, "s": 76548, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 76604, "s": 76583, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 76637, "s": 76604, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 76650, "s": 76637, "text": " Nilay Mehta" }, { "code": null, "e": 76685, "s": 76650, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 76703, "s": 76685, "text": " Bigdata Engineer" }, { "code": null, "e": 76736, "s": 76703, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 76754, "s": 76736, "text": " Bigdata Engineer" }, { "code": null, "e": 76787, "s": 76754, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 76805, "s": 76787, "text": " Bigdata Engineer" }, { "code": null, "e": 76812, "s": 76805, "text": " Print" }, { "code": null, "e": 76823, "s": 76812, "text": " Add Notes" } ]
Create a transparent border with CSS - GeeksforGeeks
30 Jan, 2020 In CSS, we can create a transparent border by using the border property in a nested div tag. The steps to create this are:Step 1: Create a nested div tag.Step 2: Specify the outer div tag’s border-style to be solid and the border-width property can be of any desired size.Step 3: The size of the inner div tag is made smaller than the outer div tag. Alternatively, we can specify all the individual properties by using the border shorthand property as shown in the example below. Example 1: Create a transparent border in CSS using the above approach. <!DOCTYPE html><html> <head> <style type="text/css"> h1 { color: green; } .outer { width: 300px; height: 300px; margin: 10%; border: 10px solid rgba(0, 0, 0, .4); border-radius: 5px; } .inner { width: 270px; height: 270px; margin: auto; margin-top: 3%; text-align: center; background: rgba(0, 0, 0, .4); border-radius: 5px; padding: 5px; } </style></head> <body> <div class="outer"> <div class="inner"> <h1>GeeksforGeeks</h1> </div> </div></body> </html> Output: Another alternative approach would be to use a single div tag and to use the border-style and background-clip property to create the transparent border. The steps to reproduce this are:Step 1: Create a div tag.Step 2: Specify the border-style property to be double to set two borders around the box.Step 3: Set the background-clip property to padding-box which clips the background color to the padding of the element. Example 2: Create a transparent border in CSS using the alternative approach discussed above. <!DOCTYPE html><html> <head> <style type="text/css"> h1 { color: green; } .trans_border { width: 270px; height: 270px; margin: auto; margin-top: 3%; text-align: center; border: 20px double rgba(0, 0, 0, .4); background: rgba(0, 0, 0, .4); background-clip: padding-box; border-radius: 5px; padding: 5px; } </style></head> <body> <div class="trans_border"> <h1>GeeksforGeeks</h1> </div></body> </html> Output: CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) 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": 27966, "s": 27938, "text": "\n30 Jan, 2020" }, { "code": null, "e": 28059, "s": 27966, "text": "In CSS, we can create a transparent border by using the border property in a nested div tag." }, { "code": null, "e": 28316, "s": 28059, "text": "The steps to create this are:Step 1: Create a nested div tag.Step 2: Specify the outer div tag’s border-style to be solid and the border-width property can be of any desired size.Step 3: The size of the inner div tag is made smaller than the outer div tag." }, { "code": null, "e": 28446, "s": 28316, "text": "Alternatively, we can specify all the individual properties by using the border shorthand property as shown in the example below." }, { "code": null, "e": 28518, "s": 28446, "text": "Example 1: Create a transparent border in CSS using the above approach." }, { "code": "<!DOCTYPE html><html> <head> <style type=\"text/css\"> h1 { color: green; } .outer { width: 300px; height: 300px; margin: 10%; border: 10px solid rgba(0, 0, 0, .4); border-radius: 5px; } .inner { width: 270px; height: 270px; margin: auto; margin-top: 3%; text-align: center; background: rgba(0, 0, 0, .4); border-radius: 5px; padding: 5px; } </style></head> <body> <div class=\"outer\"> <div class=\"inner\"> <h1>GeeksforGeeks</h1> </div> </div></body> </html>", "e": 29229, "s": 28518, "text": null }, { "code": null, "e": 29237, "s": 29229, "text": "Output:" }, { "code": null, "e": 29390, "s": 29237, "text": "Another alternative approach would be to use a single div tag and to use the border-style and background-clip property to create the transparent border." }, { "code": null, "e": 29656, "s": 29390, "text": "The steps to reproduce this are:Step 1: Create a div tag.Step 2: Specify the border-style property to be double to set two borders around the box.Step 3: Set the background-clip property to padding-box which clips the background color to the padding of the element." }, { "code": null, "e": 29750, "s": 29656, "text": "Example 2: Create a transparent border in CSS using the alternative approach discussed above." }, { "code": "<!DOCTYPE html><html> <head> <style type=\"text/css\"> h1 { color: green; } .trans_border { width: 270px; height: 270px; margin: auto; margin-top: 3%; text-align: center; border: 20px double rgba(0, 0, 0, .4); background: rgba(0, 0, 0, .4); background-clip: padding-box; border-radius: 5px; padding: 5px; } </style></head> <body> <div class=\"trans_border\"> <h1>GeeksforGeeks</h1> </div></body> </html>", "e": 30331, "s": 29750, "text": null }, { "code": null, "e": 30339, "s": 30331, "text": "Output:" }, { "code": null, "e": 30348, "s": 30339, "text": "CSS-Misc" }, { "code": null, "e": 30355, "s": 30348, "text": "Picked" }, { "code": null, "e": 30359, "s": 30355, "text": "CSS" }, { "code": null, "e": 30376, "s": 30359, "text": "Web Technologies" }, { "code": null, "e": 30474, "s": 30376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30483, "s": 30474, "text": "Comments" }, { "code": null, "e": 30496, "s": 30483, "text": "Old Comments" }, { "code": null, "e": 30558, "s": 30496, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30608, "s": 30558, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30666, "s": 30608, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 30714, "s": 30666, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30751, "s": 30714, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30793, "s": 30751, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30826, "s": 30793, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30888, "s": 30826, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30931, "s": 30888, "text": "How to fetch data from an API in ReactJS ?" } ]
Largest Number formed from an Array | Practice | GeeksforGeeks
Given a list of non negative integers, arrange them in such a manner that they form the largest number possible.The result is going to be very large, hence return the result in the form of a string. Example 1: Input: N = 5 Arr[] = {3, 30, 34, 5, 9} Output: 9534330 Explanation: Given numbers are {3, 30, 34, 5, 9}, the arrangement 9534330 gives the largest value. Example 2: Input: N = 4 Arr[] = {54, 546, 548, 60} Output: 6054854654 Explanation: Given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. Your Task: You don't need to read input or print anything. Your task is to complete the function printLargest() which takes the array of strings arr[] as parameter and returns a string denoting the answer. Expected Time Complexity: O(NlogN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 105 0 ≤ Arr[i] ≤ 1018 Sum of all the elements of the array is greater than 0. +1 satviktiwari13 hours ago C++: O(nlogn) static bool comp(string s1, string s2){ string x = s1+s2; string y = s2+s1; return x>y;}string printLargest(vector<string> &arr) { sort(arr.begin(), arr.end(), comp); string ans = ""; for(int i = 0; i < arr.size(); i++){ for(int j = 0; j < arr[i].size(); j++){ ans += arr[i][j]; } } return ans;} 0 ritikmishra2 weeks ago CPP Solution string printLargest(vector<string> &arr) { sort(arr.begin(),arr.end(),[](string X, string Y){ string XY = X.append(Y); string YX = Y.append(X); return XY.compare(YX) > 0 ? 1: 0; }); string ans=""; for (auto i:arr) ans += i; // cout << i << " "; return ans;} 0 danca2262 weeks ago is the runtime correct? O(n lg n) is the number of comparisons, but each compare is concatenating 2 strings and compare them which takes O(a+b) so it should be O(M*N lg N) where M is the max length of any two strings? 0 manjeetdhaterwal3 weeks ago java sol String printLargest(String[] arr) { Arrays.sort(arr, (s1, s2)-> {return (s2+s1).compareTo(s1+s2);}); String s=""; for(String x:arr) s+=x; return s; } 0 geek_deepx3 weeks ago class Solution{ public: /* for more reference go to - https://www.cplusplus.com/reference/algorithm/sort/ Beautiful explanation given for the uses of sort() function with our own condition */ bool static myCompare(string i, string j){ string ij = i.append(j); string ji = j.append(i); return ij.compare(ji) > 0 ? true : false; } string printLargest(vector<string> &arr) { int n = arr.size(); string ans; sort(arr.begin(), arr.end(), myCompare); for(int i = 0; i < n ; i++){ ans.append(arr[i]); } return ans; } }; 0 tushantverma3 weeks ago Why it's showing error for this code? class Solution { public String printLargest(String[] arr) { String k=""; String s=arr[0]; for (int i = 0; i < arr.length-1; i++) { String a= (s.concat(arr[i+1])); String b=(arr[i+1].concat(s)); if(a.compareTo(b)>=0) { k=(a); } else { k=(b); } s=k; } return k; } } 0 pavansunny5671 month ago Python Solution def printLargest(self,arr): # code here def comp(a,b): s1=a+b s2=b+a if s1<s2: return 1 return -1 # arr.sort(key=functools.cmp_to_key(comp)) ans="".join(arr) return ans 0 amishasahu3281 month ago class Solution{ public: // The main function that returns the arrangement with the largest value as // string. // The function accepts a vector of strings static int myCompare(string X, string Y) { string XY = X.append(Y); string YX = Y.append(X); return (XY > YX); } string printLargest(vector<string> &arr) { // code here sort(arr.begin(), arr.end(), myCompare); string ans; for(int i = 0; i < arr.size(); i++) ans.append(arr[i]); return ans; } }; +1 subashig191 month ago #include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h> int concat(int a,int b);int main(){ //Arr[] = {3, 30, 34, 5, 9} int arr[]={3, 30, 34, 5, 9}; int length; length=5; int i,j; for(i=0;i<length;i++) { for(j=i+1;j<length;j++) { int temp; int v,w; v=concat(arr[i],arr[j]); w=concat(arr[j],arr[i]); if (v>w) { ; } else { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } for(i=0;i<length;i++) { printf("%d",arr[i]); }} int concat(int a,int b){ char s1[20]; char s2[20]; // Convert both the integers to string sprintf(s1, "%d", a); sprintf(s2, "%d", b); // Concatenate both strings strcat(s1, s2); // Convert the concatenated string // to integer int c = atoi(s1); // return the formed integer return c;} 0 lindan1232 months ago static bool comp(string a,string b) { string s1 = a+b; string s2 = b+a; return s1>s2; } string printLargest(vector<string> &arr) { sort(arr.begin(),arr.end(),comp); int n = arr.size(); string str=""; for(int i=0;i<n;i++) { str+=arr[i]; } return str; } Time Taken : 0.8sec Cpp We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 437, "s": 238, "text": "Given a list of non negative integers, arrange them in such a manner that they form the largest number possible.The result is going to be very large, hence return the result in the form of a string." }, { "code": null, "e": 449, "s": 437, "text": "\nExample 1:" }, { "code": null, "e": 604, "s": 449, "text": "Input: \nN = 5\nArr[] = {3, 30, 34, 5, 9}\nOutput: 9534330\nExplanation: Given numbers are {3, 30, 34,\n5, 9}, the arrangement 9534330 gives the\nlargest value." }, { "code": null, "e": 615, "s": 604, "text": "Example 2:" }, { "code": null, "e": 779, "s": 615, "text": "Input: \nN = 4\nArr[] = {54, 546, 548, 60}\nOutput: 6054854654\nExplanation: Given numbers are {54, 546,\n548, 60}, the arrangement 6054854654 \ngives the largest value." }, { "code": null, "e": 1055, "s": 779, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function printLargest() which takes the array of strings arr[] as parameter and returns a string denoting the answer.\n\nExpected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1155, "s": 1055, "text": "\nConstraints:\n1 ≤ N ≤ 105\n0 ≤ Arr[i] ≤ 1018\nSum of all the elements of the array is greater than 0." }, { "code": null, "e": 1158, "s": 1155, "text": "+1" }, { "code": null, "e": 1183, "s": 1158, "text": "satviktiwari13 hours ago" }, { "code": null, "e": 1197, "s": 1183, "text": "C++: O(nlogn)" }, { "code": null, "e": 1544, "s": 1199, "text": "static bool comp(string s1, string s2){ string x = s1+s2; string y = s2+s1; return x>y;}string printLargest(vector<string> &arr) { sort(arr.begin(), arr.end(), comp); string ans = \"\"; for(int i = 0; i < arr.size(); i++){ for(int j = 0; j < arr[i].size(); j++){ ans += arr[i][j]; } } return ans;}" }, { "code": null, "e": 1546, "s": 1544, "text": "0" }, { "code": null, "e": 1569, "s": 1546, "text": "ritikmishra2 weeks ago" }, { "code": null, "e": 1582, "s": 1569, "text": "CPP Solution" }, { "code": null, "e": 1896, "s": 1584, "text": "string printLargest(vector<string> &arr) { sort(arr.begin(),arr.end(),[](string X, string Y){ string XY = X.append(Y); string YX = Y.append(X); return XY.compare(YX) > 0 ? 1: 0; }); string ans=\"\"; for (auto i:arr) ans += i; // cout << i << \" \"; return ans;}" }, { "code": null, "e": 1898, "s": 1896, "text": "0" }, { "code": null, "e": 1918, "s": 1898, "text": "danca2262 weeks ago" }, { "code": null, "e": 2136, "s": 1918, "text": "is the runtime correct? O(n lg n) is the number of comparisons, but each compare is concatenating 2 strings and compare them which takes O(a+b) so it should be O(M*N lg N) where M is the max length of any two strings?" }, { "code": null, "e": 2138, "s": 2136, "text": "0" }, { "code": null, "e": 2166, "s": 2138, "text": "manjeetdhaterwal3 weeks ago" }, { "code": null, "e": 2175, "s": 2166, "text": "java sol" }, { "code": null, "e": 2370, "s": 2175, "text": "String printLargest(String[] arr) {\n Arrays.sort(arr, (s1, s2)-> \n {return (s2+s1).compareTo(s1+s2);});\n String s=\"\";\n for(String x:arr) s+=x;\n return s;\n }" }, { "code": null, "e": 2372, "s": 2370, "text": "0" }, { "code": null, "e": 2394, "s": 2372, "text": "geek_deepx3 weeks ago" }, { "code": null, "e": 2953, "s": 2394, "text": "class Solution{\npublic:\n\n/*\nfor more reference go to - https://www.cplusplus.com/reference/algorithm/sort/\nBeautiful explanation given for the uses of sort() function with our own condition\n*/\nbool static myCompare(string i, string j){\n string ij = i.append(j);\n string ji = j.append(i);\n return ij.compare(ji) > 0 ? true : false;\n}\n\nstring printLargest(vector<string> &arr) {\n int n = arr.size();\n string ans;\n sort(arr.begin(), arr.end(), myCompare);\n for(int i = 0; i < n ; i++){\n ans.append(arr[i]);\n }\n return ans;\n}\n};" }, { "code": null, "e": 2955, "s": 2953, "text": "0" }, { "code": null, "e": 2979, "s": 2955, "text": "tushantverma3 weeks ago" }, { "code": null, "e": 3468, "s": 2979, "text": "Why it's showing error for this code?\nclass Solution\n{\n public String printLargest(String[] arr)\n {\n String k=\"\";\n String s=arr[0];\n for (int i = 0; i < arr.length-1; i++)\n {\n String a= (s.concat(arr[i+1]));\n String b=(arr[i+1].concat(s));\n if(a.compareTo(b)>=0)\n {\n k=(a);\n }\n else\n {\n k=(b);\n }\n s=k;\n }\n return k;\n }\n}\n" }, { "code": null, "e": 3470, "s": 3468, "text": "0" }, { "code": null, "e": 3495, "s": 3470, "text": "pavansunny5671 month ago" }, { "code": null, "e": 3511, "s": 3495, "text": "Python Solution" }, { "code": null, "e": 3770, "s": 3511, "text": "def printLargest(self,arr):\n\t # code here\n\t \n\t def comp(a,b):\n\t s1=a+b\n\t s2=b+a\n\t if s1<s2:\n\t return 1\n\t return -1\n# \n\t arr.sort(key=functools.cmp_to_key(comp))\n\t ans=\"\".join(arr)\n\t return ans\n" }, { "code": null, "e": 3772, "s": 3770, "text": "0" }, { "code": null, "e": 3797, "s": 3772, "text": "amishasahu3281 month ago" }, { "code": null, "e": 4314, "s": 3797, "text": "class Solution{\npublic:\n\t// The main function that returns the arrangement with the largest value as\n\t// string.\n\t// The function accepts a vector of strings\n\tstatic int myCompare(string X, string Y)\n\t{\n\t string XY = X.append(Y);\n\t string YX = Y.append(X);\n\t return (XY > YX);\n\t}\n\tstring printLargest(vector<string> &arr) {\n\t // code here\n\t sort(arr.begin(), arr.end(), myCompare);\n\t string ans;\n\t for(int i = 0; i < arr.size(); i++)\n\t ans.append(arr[i]);\n\t \n\t return ans;\n\t}\n};" }, { "code": null, "e": 4317, "s": 4314, "text": "+1" }, { "code": null, "e": 4339, "s": 4317, "text": "subashig191 month ago" }, { "code": null, "e": 4410, "s": 4339, "text": "#include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h>" }, { "code": null, "e": 5283, "s": 4410, "text": "int concat(int a,int b);int main(){ //Arr[] = {3, 30, 34, 5, 9} int arr[]={3, 30, 34, 5, 9}; int length; length=5; int i,j; for(i=0;i<length;i++) { for(j=i+1;j<length;j++) { int temp; int v,w; v=concat(arr[i],arr[j]); w=concat(arr[j],arr[i]); if (v>w) { ; } else { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } for(i=0;i<length;i++) { printf(\"%d\",arr[i]); }} int concat(int a,int b){ char s1[20]; char s2[20]; // Convert both the integers to string sprintf(s1, \"%d\", a); sprintf(s2, \"%d\", b); // Concatenate both strings strcat(s1, s2); // Convert the concatenated string // to integer int c = atoi(s1); // return the formed integer return c;}" }, { "code": null, "e": 5289, "s": 5287, "text": "0" }, { "code": null, "e": 5311, "s": 5289, "text": "lindan1232 months ago" }, { "code": null, "e": 5627, "s": 5311, "text": "\tstatic bool comp(string a,string b)\n\t{\n\t string s1 = a+b;\n\t string s2 = b+a;\n\t return s1>s2;\n\t}\n\tstring printLargest(vector<string> &arr) {\n\t sort(arr.begin(),arr.end(),comp);\n\t int n = arr.size();\n\t string str=\"\";\n\t for(int i=0;i<n;i++)\n\t {\n\t str+=arr[i];\n\t }\n\t return str;\n\t}" }, { "code": null, "e": 5647, "s": 5627, "text": "Time Taken : 0.8sec" }, { "code": null, "e": 5651, "s": 5647, "text": "Cpp" }, { "code": null, "e": 5797, "s": 5651, "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": 5833, "s": 5797, "text": " Login to access your submissions. " }, { "code": null, "e": 5843, "s": 5833, "text": "\nProblem\n" }, { "code": null, "e": 5853, "s": 5843, "text": "\nContest\n" }, { "code": null, "e": 5916, "s": 5853, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6064, "s": 5916, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6272, "s": 6064, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6378, "s": 6272, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Predicting HR Attrition using Support Vector Machines | by Arpan Mishra | Towards Data Science
Following my previous post, I will be covering how we can apply Support Vector Machines using python and Scikit-Learn on a real world dataset. This data was taken from a recent InClass hackathon hosted by IIT, Guwahati on Kaggle as part of their Summer Analytics 2020 capstone project, you can download it from here. In this post, you will see how easy it is to train and tune SVM and make them work for your problem statement. Using this I ranked 29th in the hackathon (top 4%) with very minimal pre-processing and feature engineering. Before we proceed, you must have an intuitive understanding of how SVM works. I would suggest you go through my previous post for an in-depth explanation of this algorithm. towardsdatascience.com Now assuming that you understand the theory behind support vector machines ... As the COVID-19 keeps unleashing its havoc, the world continues to get pushed into the crisis of the great economic recession, more and more companies start to cut down their underperforming employees. Companies firing hundreds and thousands of Employees is a typical headline today. Cutting down employees or reducing an employee salary is a tough decision to take. It needs to be taken with utmost care as imprecision in the identification of employees whose performance is attriting may lead to sabotaging of both employees’ career and the company’s reputation in the market. Aim: To predict Employee Attrition by the given data about his/her past history. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.compose importmake_column_transformerfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import GridSearchCV,RandomizedSearchCVfrom sklearn.svm import SVCfrom sklearn.decomposition import PCAfrom xgboost import XGBClassifierfrom sklearn.model_selection import cross_val_scorefrom sklearn.preprocessing import StandardScaler,RobustScalerfrom sklearn.preprocessing import OneHotEncoder,LabelEncoderfrom sklearn.pipeline import make_pipelinepd.set_option('display.max_columns', 500)pd.set_option('display.max_rows', 1000) To preserve the original training data I have made a copy of it. training = pd.read_csv('train.csv')train_data = training.copy()test_data = pd.read_csv('test.csv') train_data.info() We have 1628 observations and 29 features, out of which 22 are integers and 7 are objects. Some of the integer data type features might also be categorical. We have to predict Attrition which can either be 0 or 1 (1 if the employee left the company). train_data.head() Let's print out some statistics of our variables The weird thing to note here is that Behaviour has 0 standard deviation and mean=min=max = 1. This means that this columns has a value of 1 for all the observations, so we will drop it. We will also drop Id because it will have unique values for all the employees. train_id = train_data.Idtrain_data = train_data.drop(['Behaviour','Id'],axis = 1)test_id = test_data.Idtest_data = test_data.drop(['Behaviour','Id'],axis = 1) On exploring a little further I found that the feature PerformanceRating has only two values, 3 or 4 so I have mapped them to 0 and 1 respectively. train_data['PerformanceRating'] = train_data['PerformanceRating'].apply(lambda x: 0 if x == 3 else 1)test_data['PerformanceRating'] = test_data['PerformanceRating'].apply(lambda x: 0 if x == 3 else 1) Let's check the distribution of our target variable Attrition. train_data[‘Attrition’].value_counts().plot(kind = ‘bar’) We have more or less a balanced distribution. Checking for duplicates print('Number of duplicates: ',train_data.duplicated().sum()) train_data[train_data.duplicated()]['Attrition'].value_counts().plot(kind = 'bar') Alright, so the data has 628 duplicates and all the duplicates correspond to Attrition 1. So that means that data was oversampled to make it balanced. We will drop the duplicates now and check the distribution again. train_unq = train_data.drop_duplicates()print('New train set: ',train_unq.shape)X = train_unq.drop('Attrition',axis = 1)y = train_unq['Attrition']y.value_counts().plot(kind = 'bar')plt.show() Now our training data has 1000 data points and the target variable is imbalanced. There are many ways to tackle imbalanced data sets like upsampling or downsampling using SMOTE. We can also use a cross validation strategy such as stratified k-fold which keeps the distribution of our target variable (here Attrition) similar across the folds. The training and validation data is split using stratified sampling instead of random sampling. The stratas here are the two values of our target variable. If you don’t understand what this means then don’t worry about it just remember that it is an effective method to tackle imbalanced datasets while we train our model. You can learn more about it in the scikit-learn user guide for cross validation here. We will follow the following steps now: Drop performance rating (on exploration I found that 85% values were of a single class this might lead to overfitting) One Hot Encode all the ‘object’ data type features Use standard scaling on all the integer data type features. Use the pre-processed data and split it using Stratified K-Fold. Fit and validate with 3 candidate models: Random Forest, XGBoost and Support Vector Classifier These are a lot of steps. Well, scikit-learn allows us to do all of this in a few simple lines of codes using pipelines and column transformers. So, first, we make a pipeline for pre-processing categorical = [f for f in training.columns if training[f].dtype == object]numeric = [f for f in X.columns if f not in categorical+['Id',','Behaviour','PerformanceRating']]pre_pipe = make_column_transformer((OneHotEncoder(),categorical),(StandardScaler(),numeric)) The variable categorical stores all column names of object data type features and numeric stores all the integer data type columns. Now we define the pipeline for the models and print out the cross validation scores of the different models. Using cross_val_score we can pass “skf” into “cv” parameter and it will take care of splitting iterating and calculating the scores for us. I have used ‘roc_auc’ as the scoring metric as the data is imbalanced. For a better understanding of the parameters for cross_val_score check out its documentation. # random forest pipelinepipe_rf = make_pipeline(pre_pipe,RandomForestClassifier())#xgboost pipelinepipe_xgb = make_pipeline(pre_pipe,XGBClassifier()) # SVM pipelinepipe_svc = make_pipeline(pre_pipe,SVC(probability=True))print(‘RF:‘,np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_rf,scoring=’roc_auc’))) print(‘XGB:‘,np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_xgb,scoring=’roc_auc’))) print(‘SVC:’,np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_svc,scoring=’roc_auc’))) Clearly, support vector classifier performs better than our tree based models. It is possible that Random Forest and XGBoost may perform better after removing more features and tuning but in this post we will use SVM. After One hot encoding we had 46 features in total in the dataset, as the dimensionality increases there is more chance of overfitting and there might be irrelevant features as well. So I decided to go with PCA to reduce the dimensionality. So, first I took 46 components and included PCA in our pipeline. I have visualised the cumulative explained variance. n = 46pipe_svc = make_pipeline(pre_pipe,PCA(n_components=n),SVC(probability=True,C = 1,kernel='rbf'))plt.figure(figsize=(10,8))pipe_svc.fit(X,y)plt.plot(range(1,n+1),pipe_svc.named_steps['pca'].explained_variance_ratio_.cumsum())plt.xticks(range(1,n+1,2))plt.title('Explained Variance') We can see that about 34 components explain 100% variance. So we take 34 components and fit our model. n = 34pre_pipe = make_column_transformer((OneHotEncoder(),categorical),(StandardScaler(),numeric),remainder = 'passthrough')pipe_svc = make_pipeline(pre_pipe,PCA(n_components=n),SVC(probability=True,C = 1,kernel='rbf'))print('SVC: ',np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_svc,scoring='roc_auc'))) Our score has reduced by 0.01 but we have considerably reduced the dimensions and there is now higher chance that this model will perform better on unseen data. To squeeze out every bit of performance from the model, it is now time to tune our SVM model. we will use GridSearchCV for this if you`re not familiar with it take a look at the documentation. The parameters that can we tune are: C: This is the regularization parameter Kernel: Linear, Polynomial or RBF (Gaussian) Gamma: Equivalent to the variance term in the Gaussian kernel Class Weight: Balances the weights of the classes in target variable (weight is inversely proportional to class frequency) There are more parameters but these are the important ones that affect performance, take a look at the scikit-learn documentation before going further. Tuning is also a very easy process with pipelines, we just define out parameter grid and pass the entire pipeline into grid search. I have not tuned kernel here. Since ‘rbf’ is the most used kernel and works for most of the tasks, I will just use it to save on some compute time. You can go ahead and try tuning kernel as well. param_grid = { 'svc__C':[0.001,0.01,0.1,1,10,100,1000], 'svc__gamma': ['auto','scale'], 'svc__class_weight': ['balanced',None]}grid_search = GridSearchCV(pipe_svc,param_grid=param_grid,cv = skf, verbose=2, n_jobs = -1,scoring='roc_auc')grid_search.fit(X,y)print('Best score ',grid_search.best_score_)print('Best parameters ',grid_search.best_params_)best_svc = grid_search.best_estimator_ You may have noticed that I have prepended ‘svc__’ in front of all the parameters in the parameter grid, that is done just to specify which step of our pipeline are we tuning in the grid search as we are not just passing an estimator into GridSearchCV but an entire pipeline. I`m sure there might be better ways to do this, let me know in the comments if you know of better techniques. We can try tuning our model further to find the best C by just tweaking the range of C and fixing the values of other hyperparameters like so pipe_svc = make_pipeline(pre_pipe,PCA(n_components=n),SVC(probability=True,C = 1,kernel='rbf',class_weight=None,gamma='auto'))param_grid={ 'svc__C':[0.01,0.03,0.05,0.07,0.1,0.3,0.5,0.7,1] }grid_search = GridSearchCV(pipe_svc,param_grid=param_grid,cv = skf, verbose=2, n_jobs = -1,scoring = 'roc_auc')grid_search.fit(X,y)print('Best score ',grid_search.best_score_)print('Best parameters ',grid_search.best_params_)best_svc = grid_search.best_estimator_ The final mean validation score now is 0.8319. Time to make our submission on Kaggle. best_svc.predict_proba(test_data)[:,1]submission = pd.DataFrame(prediction,columns=['Attrition'])submission['Id'] = test['Id']submission = submission[['Id','Attrition']]submission.to_csv('submissionfile_SVC.csv',index = None) And voila ! As you can see that my rank dropped 4 places once the private leader board was revealed. This happened because my model overfit on the training data, I should have probably not gone too crazy tuning “C”. Better feature selection might also help in improving the score. What do you think? Feel free to go through my Kaggle notebook and execute the code. Thank you if you stuck around till the end. I hope you found this post useful and learnt something new from this. Please provide valuable feedback in the comments, I would love to know your ideas on improving the performance.
[ { "code": null, "e": 488, "s": 171, "text": "Following my previous post, I will be covering how we can apply Support Vector Machines using python and Scikit-Learn on a real world dataset. This data was taken from a recent InClass hackathon hosted by IIT, Guwahati on Kaggle as part of their Summer Analytics 2020 capstone project, you can download it from here." }, { "code": null, "e": 708, "s": 488, "text": "In this post, you will see how easy it is to train and tune SVM and make them work for your problem statement. Using this I ranked 29th in the hackathon (top 4%) with very minimal pre-processing and feature engineering." }, { "code": null, "e": 881, "s": 708, "text": "Before we proceed, you must have an intuitive understanding of how SVM works. I would suggest you go through my previous post for an in-depth explanation of this algorithm." }, { "code": null, "e": 904, "s": 881, "text": "towardsdatascience.com" }, { "code": null, "e": 983, "s": 904, "text": "Now assuming that you understand the theory behind support vector machines ..." }, { "code": null, "e": 1562, "s": 983, "text": "As the COVID-19 keeps unleashing its havoc, the world continues to get pushed into the crisis of the great economic recession, more and more companies start to cut down their underperforming employees. Companies firing hundreds and thousands of Employees is a typical headline today. Cutting down employees or reducing an employee salary is a tough decision to take. It needs to be taken with utmost care as imprecision in the identification of employees whose performance is attriting may lead to sabotaging of both employees’ career and the company’s reputation in the market." }, { "code": null, "e": 1643, "s": 1562, "text": "Aim: To predict Employee Attrition by the given data about his/her past history." }, { "code": null, "e": 2323, "s": 1643, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.compose importmake_column_transformerfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import GridSearchCV,RandomizedSearchCVfrom sklearn.svm import SVCfrom sklearn.decomposition import PCAfrom xgboost import XGBClassifierfrom sklearn.model_selection import cross_val_scorefrom sklearn.preprocessing import StandardScaler,RobustScalerfrom sklearn.preprocessing import OneHotEncoder,LabelEncoderfrom sklearn.pipeline import make_pipelinepd.set_option('display.max_columns', 500)pd.set_option('display.max_rows', 1000)" }, { "code": null, "e": 2388, "s": 2323, "text": "To preserve the original training data I have made a copy of it." }, { "code": null, "e": 2487, "s": 2388, "text": "training = pd.read_csv('train.csv')train_data = training.copy()test_data = pd.read_csv('test.csv')" }, { "code": null, "e": 2505, "s": 2487, "text": "train_data.info()" }, { "code": null, "e": 2756, "s": 2505, "text": "We have 1628 observations and 29 features, out of which 22 are integers and 7 are objects. Some of the integer data type features might also be categorical. We have to predict Attrition which can either be 0 or 1 (1 if the employee left the company)." }, { "code": null, "e": 2774, "s": 2756, "text": "train_data.head()" }, { "code": null, "e": 2823, "s": 2774, "text": "Let's print out some statistics of our variables" }, { "code": null, "e": 3088, "s": 2823, "text": "The weird thing to note here is that Behaviour has 0 standard deviation and mean=min=max = 1. This means that this columns has a value of 1 for all the observations, so we will drop it. We will also drop Id because it will have unique values for all the employees." }, { "code": null, "e": 3247, "s": 3088, "text": "train_id = train_data.Idtrain_data = train_data.drop(['Behaviour','Id'],axis = 1)test_id = test_data.Idtest_data = test_data.drop(['Behaviour','Id'],axis = 1)" }, { "code": null, "e": 3395, "s": 3247, "text": "On exploring a little further I found that the feature PerformanceRating has only two values, 3 or 4 so I have mapped them to 0 and 1 respectively." }, { "code": null, "e": 3596, "s": 3395, "text": "train_data['PerformanceRating'] = train_data['PerformanceRating'].apply(lambda x: 0 if x == 3 else 1)test_data['PerformanceRating'] = test_data['PerformanceRating'].apply(lambda x: 0 if x == 3 else 1)" }, { "code": null, "e": 3659, "s": 3596, "text": "Let's check the distribution of our target variable Attrition." }, { "code": null, "e": 3717, "s": 3659, "text": "train_data[‘Attrition’].value_counts().plot(kind = ‘bar’)" }, { "code": null, "e": 3763, "s": 3717, "text": "We have more or less a balanced distribution." }, { "code": null, "e": 3787, "s": 3763, "text": "Checking for duplicates" }, { "code": null, "e": 3849, "s": 3787, "text": "print('Number of duplicates: ',train_data.duplicated().sum())" }, { "code": null, "e": 3932, "s": 3849, "text": "train_data[train_data.duplicated()]['Attrition'].value_counts().plot(kind = 'bar')" }, { "code": null, "e": 4149, "s": 3932, "text": "Alright, so the data has 628 duplicates and all the duplicates correspond to Attrition 1. So that means that data was oversampled to make it balanced. We will drop the duplicates now and check the distribution again." }, { "code": null, "e": 4341, "s": 4149, "text": "train_unq = train_data.drop_duplicates()print('New train set: ',train_unq.shape)X = train_unq.drop('Attrition',axis = 1)y = train_unq['Attrition']y.value_counts().plot(kind = 'bar')plt.show()" }, { "code": null, "e": 4519, "s": 4341, "text": "Now our training data has 1000 data points and the target variable is imbalanced. There are many ways to tackle imbalanced data sets like upsampling or downsampling using SMOTE." }, { "code": null, "e": 5093, "s": 4519, "text": "We can also use a cross validation strategy such as stratified k-fold which keeps the distribution of our target variable (here Attrition) similar across the folds. The training and validation data is split using stratified sampling instead of random sampling. The stratas here are the two values of our target variable. If you don’t understand what this means then don’t worry about it just remember that it is an effective method to tackle imbalanced datasets while we train our model. You can learn more about it in the scikit-learn user guide for cross validation here." }, { "code": null, "e": 5133, "s": 5093, "text": "We will follow the following steps now:" }, { "code": null, "e": 5252, "s": 5133, "text": "Drop performance rating (on exploration I found that 85% values were of a single class this might lead to overfitting)" }, { "code": null, "e": 5303, "s": 5252, "text": "One Hot Encode all the ‘object’ data type features" }, { "code": null, "e": 5363, "s": 5303, "text": "Use standard scaling on all the integer data type features." }, { "code": null, "e": 5428, "s": 5363, "text": "Use the pre-processed data and split it using Stratified K-Fold." }, { "code": null, "e": 5523, "s": 5428, "text": "Fit and validate with 3 candidate models: Random Forest, XGBoost and Support Vector Classifier" }, { "code": null, "e": 5668, "s": 5523, "text": "These are a lot of steps. Well, scikit-learn allows us to do all of this in a few simple lines of codes using pipelines and column transformers." }, { "code": null, "e": 5717, "s": 5668, "text": "So, first, we make a pipeline for pre-processing" }, { "code": null, "e": 5981, "s": 5717, "text": "categorical = [f for f in training.columns if training[f].dtype == object]numeric = [f for f in X.columns if f not in categorical+['Id',','Behaviour','PerformanceRating']]pre_pipe = make_column_transformer((OneHotEncoder(),categorical),(StandardScaler(),numeric))" }, { "code": null, "e": 6113, "s": 5981, "text": "The variable categorical stores all column names of object data type features and numeric stores all the integer data type columns." }, { "code": null, "e": 6527, "s": 6113, "text": "Now we define the pipeline for the models and print out the cross validation scores of the different models. Using cross_val_score we can pass “skf” into “cv” parameter and it will take care of splitting iterating and calculating the scores for us. I have used ‘roc_auc’ as the scoring metric as the data is imbalanced. For a better understanding of the parameters for cross_val_score check out its documentation." }, { "code": null, "e": 7021, "s": 6527, "text": "# random forest pipelinepipe_rf = make_pipeline(pre_pipe,RandomForestClassifier())#xgboost pipelinepipe_xgb = make_pipeline(pre_pipe,XGBClassifier()) # SVM pipelinepipe_svc = make_pipeline(pre_pipe,SVC(probability=True))print(‘RF:‘,np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_rf,scoring=’roc_auc’))) print(‘XGB:‘,np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_xgb,scoring=’roc_auc’))) print(‘SVC:’,np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_svc,scoring=’roc_auc’)))" }, { "code": null, "e": 7239, "s": 7021, "text": "Clearly, support vector classifier performs better than our tree based models. It is possible that Random Forest and XGBoost may perform better after removing more features and tuning but in this post we will use SVM." }, { "code": null, "e": 7480, "s": 7239, "text": "After One hot encoding we had 46 features in total in the dataset, as the dimensionality increases there is more chance of overfitting and there might be irrelevant features as well. So I decided to go with PCA to reduce the dimensionality." }, { "code": null, "e": 7598, "s": 7480, "text": "So, first I took 46 components and included PCA in our pipeline. I have visualised the cumulative explained variance." }, { "code": null, "e": 7885, "s": 7598, "text": "n = 46pipe_svc = make_pipeline(pre_pipe,PCA(n_components=n),SVC(probability=True,C = 1,kernel='rbf'))plt.figure(figsize=(10,8))pipe_svc.fit(X,y)plt.plot(range(1,n+1),pipe_svc.named_steps['pca'].explained_variance_ratio_.cumsum())plt.xticks(range(1,n+1,2))plt.title('Explained Variance')" }, { "code": null, "e": 7988, "s": 7885, "text": "We can see that about 34 components explain 100% variance. So we take 34 components and fit our model." }, { "code": null, "e": 8300, "s": 7988, "text": "n = 34pre_pipe = make_column_transformer((OneHotEncoder(),categorical),(StandardScaler(),numeric),remainder = 'passthrough')pipe_svc = make_pipeline(pre_pipe,PCA(n_components=n),SVC(probability=True,C = 1,kernel='rbf'))print('SVC: ',np.mean(cross_val_score(X=X,y=y,cv=skf,estimator=pipe_svc,scoring='roc_auc')))" }, { "code": null, "e": 8461, "s": 8300, "text": "Our score has reduced by 0.01 but we have considerably reduced the dimensions and there is now higher chance that this model will perform better on unseen data." }, { "code": null, "e": 8654, "s": 8461, "text": "To squeeze out every bit of performance from the model, it is now time to tune our SVM model. we will use GridSearchCV for this if you`re not familiar with it take a look at the documentation." }, { "code": null, "e": 8691, "s": 8654, "text": "The parameters that can we tune are:" }, { "code": null, "e": 8731, "s": 8691, "text": "C: This is the regularization parameter" }, { "code": null, "e": 8776, "s": 8731, "text": "Kernel: Linear, Polynomial or RBF (Gaussian)" }, { "code": null, "e": 8838, "s": 8776, "text": "Gamma: Equivalent to the variance term in the Gaussian kernel" }, { "code": null, "e": 8961, "s": 8838, "text": "Class Weight: Balances the weights of the classes in target variable (weight is inversely proportional to class frequency)" }, { "code": null, "e": 9113, "s": 8961, "text": "There are more parameters but these are the important ones that affect performance, take a look at the scikit-learn documentation before going further." }, { "code": null, "e": 9441, "s": 9113, "text": "Tuning is also a very easy process with pipelines, we just define out parameter grid and pass the entire pipeline into grid search. I have not tuned kernel here. Since ‘rbf’ is the most used kernel and works for most of the tasks, I will just use it to save on some compute time. You can go ahead and try tuning kernel as well." }, { "code": null, "e": 9843, "s": 9441, "text": "param_grid = { 'svc__C':[0.001,0.01,0.1,1,10,100,1000], 'svc__gamma': ['auto','scale'], 'svc__class_weight': ['balanced',None]}grid_search = GridSearchCV(pipe_svc,param_grid=param_grid,cv = skf, verbose=2, n_jobs = -1,scoring='roc_auc')grid_search.fit(X,y)print('Best score ',grid_search.best_score_)print('Best parameters ',grid_search.best_params_)best_svc = grid_search.best_estimator_" }, { "code": null, "e": 10229, "s": 9843, "text": "You may have noticed that I have prepended ‘svc__’ in front of all the parameters in the parameter grid, that is done just to specify which step of our pipeline are we tuning in the grid search as we are not just passing an estimator into GridSearchCV but an entire pipeline. I`m sure there might be better ways to do this, let me know in the comments if you know of better techniques." }, { "code": null, "e": 10371, "s": 10229, "text": "We can try tuning our model further to find the best C by just tweaking the range of C and fixing the values of other hyperparameters like so" }, { "code": null, "e": 10828, "s": 10371, "text": "pipe_svc = make_pipeline(pre_pipe,PCA(n_components=n),SVC(probability=True,C = 1,kernel='rbf',class_weight=None,gamma='auto'))param_grid={ 'svc__C':[0.01,0.03,0.05,0.07,0.1,0.3,0.5,0.7,1] }grid_search = GridSearchCV(pipe_svc,param_grid=param_grid,cv = skf, verbose=2, n_jobs = -1,scoring = 'roc_auc')grid_search.fit(X,y)print('Best score ',grid_search.best_score_)print('Best parameters ',grid_search.best_params_)best_svc = grid_search.best_estimator_" }, { "code": null, "e": 10914, "s": 10828, "text": "The final mean validation score now is 0.8319. Time to make our submission on Kaggle." }, { "code": null, "e": 11140, "s": 10914, "text": "best_svc.predict_proba(test_data)[:,1]submission = pd.DataFrame(prediction,columns=['Attrition'])submission['Id'] = test['Id']submission = submission[['Id','Attrition']]submission.to_csv('submissionfile_SVC.csv',index = None)" }, { "code": null, "e": 11152, "s": 11140, "text": "And voila !" }, { "code": null, "e": 11505, "s": 11152, "text": "As you can see that my rank dropped 4 places once the private leader board was revealed. This happened because my model overfit on the training data, I should have probably not gone too crazy tuning “C”. Better feature selection might also help in improving the score. What do you think? Feel free to go through my Kaggle notebook and execute the code." } ]
How to detect iOS device UDID, Name, Version, Model by programmatically?
Device UDID stands for Unique device identifier. Every iOS Device has UDID which is a sequence of 40 letters and numbers that is guaranteed to be specific to your device. Device name is generally a name which will find in the device Setting→ General→ About. iOS Version is the version on which your current iPhone runs, latest iOS version in 12.2 iOS Model describes whether the iOS device which user is using is an iPhone/iPad. Now will see how to detect UDID, Name, Version and Model programatically. Open Xcode → New Project and add the below code in ViewController’s viewDidLoad method. override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let udid = UIDevice.current.identifierForVendor?.uuidString let name = UIDevice.current.name let version = UIDevice.current.systemVersion let modelName = UIDevice.current.model print(udid ?? "") // D774EAE3F447445F9D5FE2B3B699ADB1 print(name) // iPhone XR print(version) // 12.1 print(modelName) // iPhone }
[ { "code": null, "e": 1233, "s": 1062, "text": "Device UDID stands for Unique device identifier. Every iOS Device has UDID which is a sequence of 40 letters and numbers that is guaranteed to be specific to your device." }, { "code": null, "e": 1320, "s": 1233, "text": "Device name is generally a name which will find in the device Setting→ General→ About." }, { "code": null, "e": 1409, "s": 1320, "text": "iOS Version is the version on which your current iPhone runs, latest iOS version in 12.2" }, { "code": null, "e": 1491, "s": 1409, "text": "iOS Model describes whether the iOS device which user is using is an iPhone/iPad." }, { "code": null, "e": 1565, "s": 1491, "text": "Now will see how to detect UDID, Name, Version and Model programatically." }, { "code": null, "e": 1653, "s": 1565, "text": "Open Xcode → New Project and add the below code in ViewController’s viewDidLoad method." }, { "code": null, "e": 2136, "s": 1653, "text": "override func viewDidLoad() {\n super.viewDidLoad()\n // Do any additional setup after loading the view, typically from a nib.\n let udid = UIDevice.current.identifierForVendor?.uuidString\n let name = UIDevice.current.name\n let version = UIDevice.current.systemVersion\n let modelName = UIDevice.current.model\n print(udid ?? \"\") // D774EAE3F447445F9D5FE2B3B699ADB1\n print(name) // iPhone XR\n print(version) // 12.1\n print(modelName) // iPhone\n}" } ]
Difference Between One-Dimensional (1D) and Two-Dimensional (2D) Array
In this post, we will understand the difference between one dimensional array and two dimensional array. It helps store a single list of elements that are similar data type. It helps store a single list of elements that are similar data type. The total bytes is calculates as the product of the datatype of variable array and the size of the array. The total bytes is calculates as the product of the datatype of variable array and the size of the array. type variable_name[ size ]; type variable_name [ ]; variable_name = new type[size]; int [ ] a = new int [10]; It helps store 'list of lists' or 'array of arrays' or 'array of one dimensional arrays', i.e nested arrays. It helps store 'list of lists' or 'array of arrays' or 'array of one dimensional arrays', i.e nested arrays. The total bytes is equivalent to product of datatype of variable array and size of first index and size of the second index. The total bytes is equivalent to product of datatype of variable array and size of first index and size of the second index. type variable_name[size1][size2]; type variable_name = new int[size1][size2]; type variable_name = new int[size1][size2];
[ { "code": null, "e": 1167, "s": 1062, "text": "In this post, we will understand the difference between one dimensional array and two dimensional array." }, { "code": null, "e": 1236, "s": 1167, "text": "It helps store a single list of elements that are similar data type." }, { "code": null, "e": 1305, "s": 1236, "text": "It helps store a single list of elements that are similar data type." }, { "code": null, "e": 1411, "s": 1305, "text": "The total bytes is calculates as the product of the datatype of variable array and the size of the array." }, { "code": null, "e": 1517, "s": 1411, "text": "The total bytes is calculates as the product of the datatype of variable array and the size of the array." }, { "code": null, "e": 1545, "s": 1517, "text": "type variable_name[ size ];" }, { "code": null, "e": 1601, "s": 1545, "text": "type variable_name [ ];\nvariable_name = new type[size];" }, { "code": null, "e": 1627, "s": 1601, "text": "int [ ] a = new int [10];" }, { "code": null, "e": 1736, "s": 1627, "text": "It helps store 'list of lists' or 'array of arrays' or 'array of one dimensional arrays', i.e nested arrays." }, { "code": null, "e": 1845, "s": 1736, "text": "It helps store 'list of lists' or 'array of arrays' or 'array of one dimensional arrays', i.e nested arrays." }, { "code": null, "e": 1970, "s": 1845, "text": "The total bytes is equivalent to product of datatype of variable array and size of first index and size of the second index." }, { "code": null, "e": 2095, "s": 1970, "text": "The total bytes is equivalent to product of datatype of variable array and size of first index and size of the second index." }, { "code": null, "e": 2129, "s": 2095, "text": "type variable_name[size1][size2];" }, { "code": null, "e": 2173, "s": 2129, "text": "type variable_name = new int[size1][size2];" }, { "code": null, "e": 2217, "s": 2173, "text": "type variable_name = new int[size1][size2];" } ]
Bitwise AND of N binary strings in C++
In this problem, we are given an array bin[] of size n of binary strings. Our task is to create a program to find the Bitwise AND (&) of N binary strings. Here, we will take all numbers and find the bitwise AND of them i.e. bin[0] & bin[1] &... bin[n-2] & bin[n] Let’s take an example to understand the problem, Input − bin[] = {“1001”, “11001”, “010101”} Output − 000001 Explanation − Bitwise AND of all binary string − (1001) & (11001) & (010101) = 000001 To solve this problem, a direct and simple approach is to find the bitwise AND of two binary strings and then find the bitwise AND of the result with the next and go on till the last string of the array. Basic Algorithm will be − initially → result = bin[0] and i = 1 Step 1 − Repeat steps 2 and 3 until the array ends. Step 2 − result = result & bin[i] Step 3 − i++; Step 4 − print the result. Now, let’s solve the example with the help of this approach − bin[] = {“1001”, “11001”, “010101”} result = bin[0] = 1001, i = 1 Iteration 1 − result = 1001 & 11001 = 01001 i = 2 Iteration 2 − result = 01001 & 010101 = 000001 i = 3. END Program to illustrate the above solution, Live Demo #include <iostream> using namespace std; int changeLength(string &a, string &b){ int lengtha = a.length(); int lengthb = b.length(); int zeros = abs(lengtha-lengthb); if (lengtha<lengthb) { for (int i = 0 ; i<zeros; i++) a = '0' + a; return lengthb; } else { for (int i = 0 ; i<zeros; i++) b = '0' + b; } return lengtha; } string bitwiseAND(string binary1, string binary2){ int length = changeLength(binary1,binary2); string result = ""; for (int i = 0 ; i<length; i++){ result = result+(char)((binary1[i] - '0' & binary2[i]-'0')+'0'); } return result; } int main(){ string bin[] = {"1001", "11001", "010101"}; int n = sizeof(bin)/sizeof(bin[0]); string result; if (n<2){ cout<<bin[n-1]<<endl; } else{ result = bin[0]; for (int i = 1; i<n; i++) result = bitwiseAND(result, bin[i]); cout <<result<<endl; } } 000001 This approach is easy but not the most effective one as it needs to traverse the string. Let’s discuss a more effective solution, Here, we will find the size of the smallest and largest bits of the binary number. Then we will find the bitwise AND of each bit of the number and at the end we will add preceding 0’s (no. of zeros will be the largest - smallest). Let’s take an sample example to make the solution clear, bin[] = {"1001", "11001", "010101"} Largest = 010101 smallest = 1001 010101 & 1001 = 00001 Program to show the implementation of the above approach − Live Demo #include <bits/stdc++.h> using namespace std; string bitwiseANDarray(string* bin, int n){ string result; int minSize = INT_MAX; int maxSize = INT_MIN; for (int i = 0; i < n; i++) { reverse(bin[i].begin(), bin[i].end()); minSize = min(minSize, (int)bin[i].size()); maxSize = max(maxSize, (int)bin[i].size()); } for (int i = 0; i < minSize; i++) { bool setBit = true; for (int j = 0; j < n; j++) { if (bin[j][i] == '0') { setBit = false; break; } } result += (setBit ? '1' : '0'); } for (int i = 0; i<abs(maxSize-minSize); i++) result += '0'; reverse(result.begin(), result.end()); return result; } int main(){ string arr[] = {"1001", "11001", "010101"}; int n = sizeof(arr) / sizeof(arr[0]); cout<<bitwiseANDarray(arr, n); return 0; } 000001
[ { "code": null, "e": 1217, "s": 1062, "text": "In this problem, we are given an array bin[] of size n of binary strings. Our task is to create a program to find the Bitwise AND (&) of N binary strings." }, { "code": null, "e": 1325, "s": 1217, "text": "Here, we will take all numbers and find the bitwise AND of them i.e. bin[0] & bin[1] &... bin[n-2] & bin[n]" }, { "code": null, "e": 1374, "s": 1325, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1382, "s": 1374, "text": "Input −" }, { "code": null, "e": 1418, "s": 1382, "text": "bin[] = {“1001”, “11001”, “010101”}" }, { "code": null, "e": 1427, "s": 1418, "text": "Output −" }, { "code": null, "e": 1434, "s": 1427, "text": "000001" }, { "code": null, "e": 1483, "s": 1434, "text": "Explanation − Bitwise AND of all binary string −" }, { "code": null, "e": 1520, "s": 1483, "text": "(1001) & (11001) & (010101) = 000001" }, { "code": null, "e": 1724, "s": 1520, "text": "To solve this problem, a direct and simple approach is to find the bitwise AND of two binary strings and then find the bitwise AND of the result with the next and go on till the last string of the array." }, { "code": null, "e": 1750, "s": 1724, "text": "Basic Algorithm will be −" }, { "code": null, "e": 1788, "s": 1750, "text": "initially → result = bin[0] and i = 1" }, { "code": null, "e": 1840, "s": 1788, "text": "Step 1 − Repeat steps 2 and 3 until the array ends." }, { "code": null, "e": 1874, "s": 1840, "text": "Step 2 − result = result & bin[i]" }, { "code": null, "e": 1888, "s": 1874, "text": "Step 3 − i++;" }, { "code": null, "e": 1915, "s": 1888, "text": "Step 4 − print the result." }, { "code": null, "e": 1977, "s": 1915, "text": "Now, let’s solve the example with the help of this approach −" }, { "code": null, "e": 2043, "s": 1977, "text": "bin[] = {“1001”, “11001”, “010101”}\nresult = bin[0] = 1001, i = 1" }, { "code": null, "e": 2057, "s": 2043, "text": "Iteration 1 −" }, { "code": null, "e": 2093, "s": 2057, "text": "result = 1001 & 11001 = 01001\ni = 2" }, { "code": null, "e": 2107, "s": 2093, "text": "Iteration 2 −" }, { "code": null, "e": 2151, "s": 2107, "text": "result = 01001 & 010101 = 000001\ni = 3. END" }, { "code": null, "e": 2193, "s": 2151, "text": "Program to illustrate the above solution," }, { "code": null, "e": 2204, "s": 2193, "text": " Live Demo" }, { "code": null, "e": 3137, "s": 2204, "text": "#include <iostream>\nusing namespace std;\nint changeLength(string &a, string &b){\n int lengtha = a.length();\n int lengthb = b.length();\n int zeros = abs(lengtha-lengthb);\n if (lengtha<lengthb) {\n for (int i = 0 ; i<zeros; i++)\n a = '0' + a;\n return lengthb;\n }\n else {\n for (int i = 0 ; i<zeros; i++)\n b = '0' + b;\n }\n return lengtha;\n}\nstring bitwiseAND(string binary1, string binary2){\n int length = changeLength(binary1,binary2);\n string result = \"\";\n for (int i = 0 ; i<length; i++){\n result = result+(char)((binary1[i] - '0' & binary2[i]-'0')+'0');\n }\n return result;\n}\nint main(){\n string bin[] = {\"1001\", \"11001\", \"010101\"};\n int n = sizeof(bin)/sizeof(bin[0]);\n string result;\n if (n<2){\n cout<<bin[n-1]<<endl;\n }\n else{\n result = bin[0];\n for (int i = 1; i<n; i++)\n result = bitwiseAND(result, bin[i]);\n cout <<result<<endl;\n }\n}" }, { "code": null, "e": 3144, "s": 3137, "text": "000001" }, { "code": null, "e": 3233, "s": 3144, "text": "This approach is easy but not the most effective one as it needs to traverse the string." }, { "code": null, "e": 3274, "s": 3233, "text": "Let’s discuss a more effective solution," }, { "code": null, "e": 3505, "s": 3274, "text": "Here, we will find the size of the smallest and largest bits of the binary number. Then we will find the bitwise AND of each bit of the number and at the end we will add preceding 0’s (no. of zeros will be the largest - smallest)." }, { "code": null, "e": 3562, "s": 3505, "text": "Let’s take an sample example to make the solution clear," }, { "code": null, "e": 3653, "s": 3562, "text": "bin[] = {\"1001\", \"11001\", \"010101\"}\nLargest = 010101 smallest = 1001\n010101 & 1001 = 00001" }, { "code": null, "e": 3712, "s": 3653, "text": "Program to show the implementation of the above approach −" }, { "code": null, "e": 3723, "s": 3712, "text": " Live Demo" }, { "code": null, "e": 4586, "s": 3723, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstring bitwiseANDarray(string* bin, int n){\n string result;\n int minSize = INT_MAX;\n int maxSize = INT_MIN;\n for (int i = 0; i < n; i++) {\n reverse(bin[i].begin(), bin[i].end());\n minSize = min(minSize, (int)bin[i].size());\n maxSize = max(maxSize, (int)bin[i].size());\n }\n for (int i = 0; i < minSize; i++) {\n bool setBit = true;\n for (int j = 0; j < n; j++) {\n if (bin[j][i] == '0') {\n setBit = false;\n break;\n }\n }\n result += (setBit ? '1' : '0');\n }\n for (int i = 0; i<abs(maxSize-minSize); i++)\n result += '0';\n reverse(result.begin(), result.end());\n return result;\n}\nint main(){\n string arr[] = {\"1001\", \"11001\", \"010101\"};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout<<bitwiseANDarray(arr, n);\n return 0;\n}" }, { "code": null, "e": 4593, "s": 4586, "text": "000001" } ]
JasperReports - Filling Reports
The main purpose of any reporting tool is to produce high quality documents. Report filling process helps reporting tool to achieve this by manipulating sets of data. The main inputs required for report-filling process are − Report Template − This is actual JasperReport file. Report Template − This is actual JasperReport file. Report Parameters − These are basically named values that are passed at the report filling time to the engine. We will discuss them in Report Parameter chapter. Report Parameters − These are basically named values that are passed at the report filling time to the engine. We will discuss them in Report Parameter chapter. Data Source − We can fill a Jasper file from a range of datasources like an SQL query, an XML file, a csv file, an HQL (Hibernate Query Language) query, a collection of Java Beans, etc. This will be discussed in detail in Report Data Sources chapter. Data Source − We can fill a Jasper file from a range of datasources like an SQL query, an XML file, a csv file, an HQL (Hibernate Query Language) query, a collection of Java Beans, etc. This will be discussed in detail in Report Data Sources chapter. The output generated by this process is a .jrprint document which is ready to be viewed, printed, or exported to other formats. The facade class net.sf.jasperreports.engine.JasperFillManager is usually used for filling a report template with data. This class has various fillReportXXX() methods that fill report templates (templates could be located on disk, picked from input streams, or are supplied directly as in-memory). There are two categories of fillReportXXX() methods in this facade class − The first type, receive a java.sql.Connection object as the third parameter. Most of the times, reports are filled with data from a relational database. This is achieved by − Connect to the database through JDBC. Include an SQL query inside the report template. JasperReports engine uses the connection passed in and executes the SQL query. A report data source is thus produced for filling the report. The first type, receive a java.sql.Connection object as the third parameter. Most of the times, reports are filled with data from a relational database. This is achieved by − Connect to the database through JDBC. Connect to the database through JDBC. Include an SQL query inside the report template. Include an SQL query inside the report template. JasperReports engine uses the connection passed in and executes the SQL query. JasperReports engine uses the connection passed in and executes the SQL query. A report data source is thus produced for filling the report. A report data source is thus produced for filling the report. The second type, receive a net.sf.jasperreports.engine.JRDataSource object, when the data that need to be filled is available in other forms. The second type, receive a net.sf.jasperreports.engine.JRDataSource object, when the data that need to be filled is available in other forms. Let's write a report template. The contents of the JRXML file (C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml) are as below − <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name = "jasper_report_template" language = "groovy" pageWidth = "595" pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20" topMargin = "20" bottomMargin = "20"> <queryString> <![CDATA[]]> </queryString> <field name = "country" class = "java.lang.String"> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = "name" class = "java.lang.String"> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <columnHeader> <band height = "23"> <staticText> <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15" backcolor = "#70A9A9" /> <box> <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <staticText> <reportElement x = "414" y = "3" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = "0" y = "3" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = "16"> <staticText> <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14" backcolor = "#E5ECF9" /> <box> <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <textField> <reportElement x = "414" y = "0" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font size = "9" /> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = "0" y = "0" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle" /> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> </jasperReport> Next, let's pass a collection of Java data objects (Java beans), to the JasperReport Engine, to fill this compiled report. Write a POJO DataBean.java, which represents the data object (Java bean). This class defines two String objects i.e. 'name' and 'country'. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint. package com.tutorialspoint; public class DataBean { private String name; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } Write a class DataBeanList.java, which has business logic to generate a collection of java bean objects. This is further passed to the JasperReports engine, to generate the report. Here we are adding 4 DataBean objects in the List. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint. package com.tutorialspoint; import java.util.ArrayList; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); dataBeanList.add(produce("Manisha", "India")); dataBeanList.add(produce("Dennis Ritchie", "USA")); dataBeanList.add(produce("V.Anand", "India")); dataBeanList.add(produce("Shrinath", "California")); return dataBeanList; } /** * This method returns a DataBean object, * with name and country set in it. */ private DataBean produce(String name, String country) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); return dataBean; } } Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint. package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; public class JasperReportFill { @SuppressWarnings("unchecked") public static void main(String[] args) { String sourceFileName = "c://tools/jasperreports-5.0.1/test/jasper_report_template.jasper"; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); try { JasperFillManager.fillReportToFile( sourceFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } } } We will now compile and execute these files using our regular ANT build process. The build.xml file is as given below − The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml. <?xml version = "1.0" encoding = "UTF-8"?> <project name = "JasperReportTest" default = "executereport" basedir = "."> <import file = "baseBuild.xml"/> <target name = "executereport" depends = "compile,compilereportdesing,run"> <echo message = "Im here"/> </target> <target name = "compilereportdesing" description = "Compiles the JXML file and produces the .jasper file."> <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask"> <classpath refid = "classpath" /> </taskdef> <jrc destdir = "."> <src> <fileset dir = "."> <include name = "*.jrxml" /> </fileset> </src> <classpath refid = "classpath" /> </jrc> </target> </project> Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportFill (executereport is the default target) as follows − C:\tools\jasperreports-5.0.1\test>ant -Dmain-class = com.tutorialspoint.JasperReportFill Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml compile: [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:27: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds [javac] Compiling 1 source file to C:\tools\jasperreports-5.0.1\test\classes run: [echo] Runnin class : com.tutorialspoint.JasperReportFill [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. BUILD SUCCESSFUL Total time: 8 seconds As a result of above execution, a file jasper_report_template.jrprint is generated in the same directory as the .jasper file (In this case, it is generated at C:\tools\jasperreports-5.0.1\test). Print Add Notes Bookmark this page
[ { "code": null, "e": 2421, "s": 2254, "text": "The main purpose of any reporting tool is to produce high quality documents. Report filling process helps reporting tool to achieve this by manipulating sets of data." }, { "code": null, "e": 2479, "s": 2421, "text": "The main inputs required for report-filling process are −" }, { "code": null, "e": 2531, "s": 2479, "text": "Report Template − This is actual JasperReport file." }, { "code": null, "e": 2583, "s": 2531, "text": "Report Template − This is actual JasperReport file." }, { "code": null, "e": 2744, "s": 2583, "text": "Report Parameters − These are basically named values that are passed at the report filling time to the engine. We will discuss them in Report Parameter chapter." }, { "code": null, "e": 2905, "s": 2744, "text": "Report Parameters − These are basically named values that are passed at the report filling time to the engine. We will discuss them in Report Parameter chapter." }, { "code": null, "e": 3156, "s": 2905, "text": "Data Source − We can fill a Jasper file from a range of datasources like an SQL query, an XML file, a csv file, an HQL (Hibernate Query Language) query, a collection of Java Beans, etc. This will be discussed in detail in Report Data Sources chapter." }, { "code": null, "e": 3407, "s": 3156, "text": "Data Source − We can fill a Jasper file from a range of datasources like an SQL query, an XML file, a csv file, an HQL (Hibernate Query Language) query, a collection of Java Beans, etc. This will be discussed in detail in Report Data Sources chapter." }, { "code": null, "e": 3834, "s": 3407, "text": "The output generated by this process is a .jrprint document which is ready to be viewed, printed, or exported to other formats. The facade class net.sf.jasperreports.engine.JasperFillManager is usually used for filling a report template with data. This class has various fillReportXXX() methods that fill report templates (templates could be located on disk, picked from input streams, or are supplied directly as in-memory)." }, { "code": null, "e": 3909, "s": 3834, "text": "There are two categories of fillReportXXX() methods in this facade class −" }, { "code": null, "e": 4315, "s": 3909, "text": "The first type, receive a java.sql.Connection object as the third parameter. Most of the times, reports are filled with data from a relational database. This is achieved by −\n\nConnect to the database through JDBC.\nInclude an SQL query inside the report template.\nJasperReports engine uses the connection passed in and executes the SQL query.\nA report data source is thus produced for filling the report.\n\n" }, { "code": null, "e": 4490, "s": 4315, "text": "The first type, receive a java.sql.Connection object as the third parameter. Most of the times, reports are filled with data from a relational database. This is achieved by −" }, { "code": null, "e": 4528, "s": 4490, "text": "Connect to the database through JDBC." }, { "code": null, "e": 4566, "s": 4528, "text": "Connect to the database through JDBC." }, { "code": null, "e": 4615, "s": 4566, "text": "Include an SQL query inside the report template." }, { "code": null, "e": 4664, "s": 4615, "text": "Include an SQL query inside the report template." }, { "code": null, "e": 4743, "s": 4664, "text": "JasperReports engine uses the connection passed in and executes the SQL query." }, { "code": null, "e": 4822, "s": 4743, "text": "JasperReports engine uses the connection passed in and executes the SQL query." }, { "code": null, "e": 4884, "s": 4822, "text": "A report data source is thus produced for filling the report." }, { "code": null, "e": 4946, "s": 4884, "text": "A report data source is thus produced for filling the report." }, { "code": null, "e": 5088, "s": 4946, "text": "The second type, receive a net.sf.jasperreports.engine.JRDataSource object, when the data that need to be filled is available in other forms." }, { "code": null, "e": 5230, "s": 5088, "text": "The second type, receive a net.sf.jasperreports.engine.JRDataSource object, when the data that need to be filled is available in other forms." }, { "code": null, "e": 5372, "s": 5230, "text": "Let's write a report template. The contents of the JRXML file (C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml) are as below −" }, { "code": null, "e": 8738, "s": 5372, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE jasperReport PUBLIC \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" language = \"groovy\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"555\" leftMargin = \"20\" rightMargin = \"20\"\n topMargin = \"20\" bottomMargin = \"20\">\n\n <queryString>\n <![CDATA[]]>\n </queryString>\n \n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n </field>\n \n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n </field>\n\n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" \n width = \"535\" height = \"15\" backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n <text><![CDATA[]]> </text>\n </staticText>\n\t\t\t\n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n\t\t\t\t\n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n \n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" \n width = \"535\" height = \"14\" backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n <text><![CDATA[]]> </text>\n </staticText>\n \n <textField>\n <reportElement x = \"414\" y = \"0\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n\t\n</jasperReport>" }, { "code": null, "e": 8861, "s": 8738, "text": "Next, let's pass a collection of Java data objects (Java beans), to the JasperReport Engine, to fill this compiled report." }, { "code": null, "e": 9083, "s": 8861, "text": "Write a POJO DataBean.java, which represents the data object (Java bean). This class defines two String objects i.e. 'name' and 'country'. Save it to the directory C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint." }, { "code": null, "e": 9451, "s": 9083, "text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}" }, { "code": null, "e": 9766, "s": 9451, "text": "Write a class DataBeanList.java, which has business logic to generate a collection of java bean objects. This is further passed to the JasperReports engine, to generate the report. Here we are adding 4 DataBean objects in the List. Save it to the directory C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint." }, { "code": null, "e": 10530, "s": 9766, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}" }, { "code": null, "e": 10798, "s": 10530, "text": "Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint." }, { "code": null, "e": 11755, "s": 10798, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName = \n \"c://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource = new \n JRBeanCollectionDataSource(dataList);\n Map parameters = new HashMap();\n try {\n JasperFillManager.fillReportToFile( \n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 11875, "s": 11755, "text": "We will now compile and execute these files using our regular ANT build process. The build.xml file is as given below −" }, { "code": null, "e": 12009, "s": 11875, "text": "The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml." }, { "code": null, "e": 12822, "s": 12009, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"executereport\" basedir = \".\">\n <import file = \"baseBuild.xml\"/>\n\n <target name = \"executereport\" depends = \"compile,compilereportdesing,run\">\n <echo message = \"Im here\"/>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n \n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n\t\t\n </target>\n\t\n</project>" }, { "code": null, "e": 13046, "s": 12822, "text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class = com.tutorialspoint.JasperReportFill (executereport is the default target) as follows −" }, { "code": null, "e": 13762, "s": 13046, "text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class = com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\ncompile:\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:27:\n warning: 'includeantruntime' was not set, defaulting to\n build.sysclasspath=last; set to false for repeatable builds\n [javac] Compiling 1 source file to\n C:\\tools\\jasperreports-5.0.1\\test\\classes\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 8 seconds\n" }, { "code": null, "e": 13959, "s": 13762, "text": "As a result of above execution, a file jasper_report_template.jrprint is generated in the same directory as the .jasper file (In this case, it is generated at C:\\tools\\jasperreports-5.0.1\\test)." }, { "code": null, "e": 13966, "s": 13959, "text": " Print" }, { "code": null, "e": 13977, "s": 13966, "text": " Add Notes" } ]
Batch sampler for sequential data using PyTorch deep learning framework | by Harsh Maheshwari | Towards Data Science
Note — To learn how to write a data loader for a custom dataset either that be sequential or image, refer here. For a sequential dataset where the size of data points could be different, we used zero-padding to make all the data points of the same size. Thus the batch can be converted to tensor and passed to the graphic card (GPU) for parallel processing. But this method is not the most optimum. Consider two batches of 8 data points, with the size of each data point as follows: Batch 1— [2, 5, 5, 4, 6, 7, 8, 2], final_size_of _batch = 8*8 Batch 2— [2, 32, 5, 36, 6, 34, 8, 2], final_size_of _batch = 36*8 In Batch 1 all the data points need to be converted to size 8 using zero padding, while in Batch 2 all the data points need to be converted to size 36. In both cases, the minimum size is 2, but in Batch 1 we add just 6 zeros to the element of size 2 whereas in Batch 2 we need to add 34 zeros. Thus we can see that Batch 2 causes a lot of wastage of GPU memory on processing zeros that are of no use while Batch 1 is an efficient packing, wasting quite less GPU. This example shows the problem and also gives us our solution. If we can somehow make the batches manually then we can ensure that each packing is efficient. But how do we do that?? Remember the index variable in __getitem__ function which was provided internally, instead of that if we can manually provide the indexes for each batch, then our job is done. In order to do so, we can use the batch_sampler argument in the data loader as shown below. train_dataset = Dataset_seq(word2id, train_path)sampler = Sampler(tokens, data, bin_size) #data is list of sentences present in whole corpustrain_batch_sampler_loader = DataLoader( train_dataset, batch_sampler = sampler, collate_fn = collate_fn) Now the index for a batch will be provided using the sampler function which we will define below. Note — It is always preferred to have different sets of data points in a batch for different epochs i.e. if in the first epoch a batch passes (data 1, data 2, data 3, data 4 ), in other epochs we should make sure to not provide the same set (data 1, data 2, data 3, data 4) together. This is to ensure that our model does not learn the pattern/sequence in which the data points are provided. Let us now understand how we will write the algorithm for our sampler function: We will create a list text_len containing the length of each data point. Then we will create bins (or bucket data) such that each bin stores the index of data points with size less than or equal to the size corresponding to that bin. Here, the size corresponding to each bin is dependent on bin_size. For eg. If bin_size = 2 then the sizes of bins will be 3,5,7.... till the maximum size present in text_len. If say text_len = [2, 3, 4, 5, 6, 7, 8] then we will get the bins as {3: [0, 1], 5: [2, 3], 7: [4, 5], 8: [6]} i.e. values at index 0, 1 have size ≤ 3, values at index 2, 3 have size ≤ 5 and so on. The last bin has size 8 because that is the maximum size present in text_len. Now, that we have whole data segregated on the basis of size we will create our batches. For that, we will use a parameter n_tokens which indicates the maximum total size (including zero-padding) that can be loaded in the GPU. So if n_tokens=500 then we can make each batch such that after zero-padding the sum of the size of each data point in a batch is less than or equal to 500. Now to form the batches, we start from the largest bucket and keep picking indexes sequentially till the total size for that batch is just less than or equal to n_tokens. Once a batch is formed we append it to final_indicies which is a list of lists. This process continues till all the data points(present in all the bins) are picked up and allotted to a batch. To make sure that the same set of batches are not sent across different epoch, after each epoch, we randomly shuffle the list stored for each bin. So when we sequentially start picking from the bins we get different data each time. Refer to the code for this algorithm below I hope this blog helps you understand and explore new applications. Please do share your feedback and other methods that you follow to make this blog better. Become a Medium member to unlock and read many other stories on medium. Follow us on Medium for reading more such blog posts.
[ { "code": null, "e": 158, "s": 46, "text": "Note — To learn how to write a data loader for a custom dataset either that be sequential or image, refer here." }, { "code": null, "e": 404, "s": 158, "text": "For a sequential dataset where the size of data points could be different, we used zero-padding to make all the data points of the same size. Thus the batch can be converted to tensor and passed to the graphic card (GPU) for parallel processing." }, { "code": null, "e": 529, "s": 404, "text": "But this method is not the most optimum. Consider two batches of 8 data points, with the size of each data point as follows:" }, { "code": null, "e": 591, "s": 529, "text": "Batch 1— [2, 5, 5, 4, 6, 7, 8, 2], final_size_of _batch = 8*8" }, { "code": null, "e": 657, "s": 591, "text": "Batch 2— [2, 32, 5, 36, 6, 34, 8, 2], final_size_of _batch = 36*8" }, { "code": null, "e": 1278, "s": 657, "text": "In Batch 1 all the data points need to be converted to size 8 using zero padding, while in Batch 2 all the data points need to be converted to size 36. In both cases, the minimum size is 2, but in Batch 1 we add just 6 zeros to the element of size 2 whereas in Batch 2 we need to add 34 zeros. Thus we can see that Batch 2 causes a lot of wastage of GPU memory on processing zeros that are of no use while Batch 1 is an efficient packing, wasting quite less GPU. This example shows the problem and also gives us our solution. If we can somehow make the batches manually then we can ensure that each packing is efficient." }, { "code": null, "e": 1302, "s": 1278, "text": "But how do we do that??" }, { "code": null, "e": 1570, "s": 1302, "text": "Remember the index variable in __getitem__ function which was provided internally, instead of that if we can manually provide the indexes for each batch, then our job is done. In order to do so, we can use the batch_sampler argument in the data loader as shown below." }, { "code": null, "e": 1880, "s": 1570, "text": "train_dataset = Dataset_seq(word2id, train_path)sampler = Sampler(tokens, data, bin_size) #data is list of sentences present in whole corpustrain_batch_sampler_loader = DataLoader( train_dataset, batch_sampler = sampler, collate_fn = collate_fn)" }, { "code": null, "e": 1978, "s": 1880, "text": "Now the index for a batch will be provided using the sampler function which we will define below." }, { "code": null, "e": 2370, "s": 1978, "text": "Note — It is always preferred to have different sets of data points in a batch for different epochs i.e. if in the first epoch a batch passes (data 1, data 2, data 3, data 4 ), in other epochs we should make sure to not provide the same set (data 1, data 2, data 3, data 4) together. This is to ensure that our model does not learn the pattern/sequence in which the data points are provided." }, { "code": null, "e": 2450, "s": 2370, "text": "Let us now understand how we will write the algorithm for our sampler function:" }, { "code": null, "e": 2523, "s": 2450, "text": "We will create a list text_len containing the length of each data point." }, { "code": null, "e": 2859, "s": 2523, "text": "Then we will create bins (or bucket data) such that each bin stores the index of data points with size less than or equal to the size corresponding to that bin. Here, the size corresponding to each bin is dependent on bin_size. For eg. If bin_size = 2 then the sizes of bins will be 3,5,7.... till the maximum size present in text_len." }, { "code": null, "e": 3135, "s": 2859, "text": "If say text_len = [2, 3, 4, 5, 6, 7, 8] then we will get the bins as {3: [0, 1], 5: [2, 3], 7: [4, 5], 8: [6]} i.e. values at index 0, 1 have size ≤ 3, values at index 2, 3 have size ≤ 5 and so on. The last bin has size 8 because that is the maximum size present in text_len." }, { "code": null, "e": 3518, "s": 3135, "text": "Now, that we have whole data segregated on the basis of size we will create our batches. For that, we will use a parameter n_tokens which indicates the maximum total size (including zero-padding) that can be loaded in the GPU. So if n_tokens=500 then we can make each batch such that after zero-padding the sum of the size of each data point in a batch is less than or equal to 500." }, { "code": null, "e": 3881, "s": 3518, "text": "Now to form the batches, we start from the largest bucket and keep picking indexes sequentially till the total size for that batch is just less than or equal to n_tokens. Once a batch is formed we append it to final_indicies which is a list of lists. This process continues till all the data points(present in all the bins) are picked up and allotted to a batch." }, { "code": null, "e": 4113, "s": 3881, "text": "To make sure that the same set of batches are not sent across different epoch, after each epoch, we randomly shuffle the list stored for each bin. So when we sequentially start picking from the bins we get different data each time." }, { "code": null, "e": 4156, "s": 4113, "text": "Refer to the code for this algorithm below" }, { "code": null, "e": 4314, "s": 4156, "text": "I hope this blog helps you understand and explore new applications. Please do share your feedback and other methods that you follow to make this blog better." } ]
Geocoding: OpenStreetMap + R + Tableau | by jose Luis Rodriguez | Towards Data Science
In the past, Google Maps did not require an API token, which made it helpful for short use cases. Now, one must create a cloud account. To be honest, it is surprising that Google allowed the token free API to go on for as long as it did. In looking for an alternative for short use cases requiring the geo location of a street address, I found that OpenStreetMap is a simple and useful replacement. This feature is primarily targeted toward users who already have some experience working with R. These users will find the integration beneficial for several reasons: Full access to any R package or function that has been installed in R Use of Tableau capabilities to further analyze and understand data Provides a platform to integrate open source data and software with proprietary software Users must have access to R/RStudio and Tableau. The two softwares can either be present on the same computer or can be present remotely (cloud). There is a way to execute R or Python commands from Tableau in order to allow us to leverage the capabilities of these programming languages (functions, models and packages). You can do this via calculated fields that dynamically communicate with an R or Python instance, and the results are returned back to Tableau as a predetermined data type (INT, REAL, BOOL, STR). This integration is helpful when there is a need for dynamically computed fields to support analysts’ needs without having to run code separately and send a new dataset back. For this reason, we will not be using this capability, but you can check a related blog below. In many cases, we have access to data with location information (e.g. Address, City, County, Zip Code, Country). If we want to visualize this data with more detail, we need to use geolocation. The geolocation coordinates (longitude, latitude) need to be calculated based on the location data. Nominatim is a free search engine for OpenStreetMap data. Using Nominatim, we can easily calculate geolocation coordinates from a given address. OpenStreetMap consists of data built by a community of mappers who contribute and maintain data about roads, trails, cafés, railway stations, and much more, all over the world. https://www.openstreetmap.org/about To load packages in R/RStudio, we are going to use tidyverse, which is a collection of R packages designed for data science as well as other packages to help with data cleaning and processing. The code blocks below allow you to: Check if the required package is installedInstall uninstalled packagesLoad the package after installation Check if the required package is installed Install uninstalled packages Load the package after installation Package Tidyverse www.tidyverse.org # CHECK IF PACKAGE IS INSTALLEDif(!require("tidyverse")){ # IF PACKAGE NOT FOUND, INSTALL IT install.packages("tidyverse", dependencies = TRUE) # LOAD PACKAGE AFTER INSTALLETION library("tidyverse")} Package rvest github.com # CHECK IF PACKAGE IS INSTALLEDif(!require("rvest")){# IF PACKAGE NOT FOUND, INSTALL IT install.packages("rvest", dependencies = TRUE)# LOAD PACKAGE AFTER INSTALLETION library("rvest")} Package stringi github.com # CHECK IF PACKAGE IS INSTALLEDif(!require("stringi")){# IF PACKAGE NOT FOUND, INSTALL IT install.packages("stringi", dependencies = TRUE)# LOAD PACKAGE AFTER INSTALLETION library("stringi")} Package jsonlite github.com # CHECK IF PACKAGE IS INSTALLEDif(!require("jsonlite")){# IF PACKAGE NOT FOUND, INSTALL IT install.packages("jsonlite", dependencies = TRUE)# LOAD PACKAGE AFTER INSTALLETION library("jsonlite")} The geocode function below allows us to make requests to Nominatim (a search engine for OpenStreetMap data). Nominatim: https://nominatim.openstreetmap.org/ Resources: https://nominatim.org/release-docs/develop/api/Search The function takes and inputs the following parameters which can be modified depending on your needs: [Name], [Address], [City] , [State] , [Zipcode] geocode <- function(name, address, city, state, zipcode){ # NOMINATIM SEARCH API URL src_url <- "https://nominatim.openstreetmap.org/search?q=" # CREATE A FULL ADDRESS addr <- paste(address, city, state, zipcode, sep = "%2C") # CREATE A SEARCH URL BASED ON NOMINATIM API TO RETURN GEOJSON requests <- paste0(src_url, query, "&format=geojson") # ITERATE OVER THE URLS AND MAKE REQUEST TO THE SEARCH API for (i in 1:length(requests)) { # QUERY THE API TRANSFORM RESPONSE FROM JSON TO R LIST response <- read_html(requests[i]) %>% html_node("p") %>% html_text() %>% fromJSON() # FROM THE RESPONSE EXTRACT LATITUDE AND LONGITUDE COORDINATES lon <- response$features$geometry$coordinates[[1]][1] lat <- response$features$geometry$coordinates[[1]][2] # CREATE A COORDINATES DATAFRAME if(i == 1) { loc <- tibble(name = name[i], address = str_replace_all(addr[i], "%2C", ","), latitude = lat, longitude = lon) }else{ df <- tibble(name = name[i], address = str_replace_all(addr[i], "%2C", ","), latitude = lat, longitude = lon) loc <- bind_rows(loc, df) } } return(loc)} This information is derived from inspections of restaurants and other food establishments in Chicago from January 1, 2010 to the present. Inspections are performed by staff from the Chicago Department of Public Health’s Food Protection Program using a standardized procedure. data.cityofchicago.org The food inspection data has geolocation coordinates, and we can use them to check the accuracy of our results. In this sample dataset, we will only use the location columns to find the coordinates of restaurants. In the code chunk below, we are reading the data and making some changes to make sure that the address works with the Nominatim API. Reading the data # READ THE DATAdata <- read_csv("food_inspection_sample.csv")# REMOVE SPACE FROM COLUMNScolnames(data) <- str_replace_all(colnames(data)," ", "_") Cleaning The Data # REMOVE SPACE FROM RESULTSdata$Results <- data$Results %>% str_replace_all(" w/ ", " with ") %>% str_replace_all(" ", "_")# EXTRACT RISK LEVEL data$Risk <- tolower(data$Risk) %>% str_extract("\\(.*\\)") %>% str_extract("[a-z]+")head(data) In this section, we will prepare the address variable to match the Nominatim API style. # EXTRACT THE ADDRESS VARIABLE address <- data$Address Modifying the address variable to match the API # CLEAN SPECIAL CASES (e.g. 1 N MAY BLDG)query <- str_replace_all(string = address, pattern = "BLDG", replacement = " ")# CLEAN SPECIAL CASES (e.g. 3333-3339 N CLARK)query <- stri_replace(str = query, replacement = " ", regex = "(-[0-9]+\\s)")# REPLACE SPACES (\\s) OR COMMAS (,) WITH PLUS SIGN (+)query <- str_replace_all(string = query, pattern = "\\s|,", replacement = "+") After the address variable is ready for the API, we can use the geocode function created at the beginning to find the geo coordinates of the restaurants. df <- geocode(name = data$DBA_Name, address = query, city = data$City, state = data$State, zipcode = data$Zipcode) Finally, we can merge the two datasets to create a main one and work in Tableau. To achieve this, we use a left_join by the variable name on the returned DataFrame and DBA_Name variable from the original dataset. geo_df <- data %>% left_join(df, by = c("DBA_Name" = "name")) Now that there is a main dataset with geo coordinates, we can import it to Tableau for further analysis. To start working on Tableau, connect to the file viaText file (CSV). This is the file that was previously created in R. Tableau data interpreter helps to identify the data types of your columns, but it is always important to double check to ensure that the data type is correct. In this case, we are going to make sure that the variables (latitude and longitude) data type (geographic role) is correct. A good practice when working in Tableau is to Extract the dataset that you are working on by selecting the option on the top right corner of the screen. This will prevent you from overwriting/damaging the original data. When finished making changes to the data types, go to the highlighted worksheet section on the bottom left side of the screen. A prompt to save the dataset (extract) will appear. Follow the prompt to save it in the default location. On the worksheet, you will see the dataset columns in two sections depending of the data type (Dimensions and Measures). In the measures section, you will find the Longitude and Latitude variables. To map the coordinates, follow the steps below: Double-click on the Longitude variable and Tableau will place the variable in the correct axis (columns).Double-click on the Latitude variable, and it will be placed in the correct axis (rows).After placing the variables in the correct axis, change the data type from Measure to Dimension for each variable. Double-click on the Longitude variable and Tableau will place the variable in the correct axis (columns). Double-click on the Latitude variable, and it will be placed in the correct axis (rows). After placing the variables in the correct axis, change the data type from Measure to Dimension for each variable. With the addresses located in the map, we can now add more features, such as county boundaries, zip codes, location details, and color. Double-click on the DBA Name variable to automatically assign it as a Detail Mark to see the name of each location.Double-click on the Risk variable. Since there are three categories, the Color Mark is automatically assigned.When hovering the mouse over the points, we should be able to see the name of the restaurant, risk, and geo coordinates. Double-click on the DBA Name variable to automatically assign it as a Detail Mark to see the name of each location. Double-click on the Risk variable. Since there are three categories, the Color Mark is automatically assigned. When hovering the mouse over the points, we should be able to see the name of the restaurant, risk, and geo coordinates. Tableau allows us to add additional layers to the default map. In this case, it would be helpful to know zip code labels and boundaries. On the main toolbar, select Map → Map Layers.A Map Layer view should come out on the left corner of the worksheet. Scroll down and enable the Zip Code Boundaries and Zip Code Labels options. On the main toolbar, select Map → Map Layers. A Map Layer view should come out on the left corner of the worksheet. Scroll down and enable the Zip Code Boundaries and Zip Code Labels options. Finally, you can zoom in to take a closer look at a specific area. Keep in mind, this blog post only scratches the surface of what is possible when we integrate OpenStreetMap, R, and Tableau. OpenStreetMap API does not require a token, which others (Google, Mapquest) require. By leveraging OpenStreetMap as a resource, simple use cases can be deeply enriched. With that being said, be mindful of the amount of requests you make at any given time.
[ { "code": null, "e": 410, "s": 172, "text": "In the past, Google Maps did not require an API token, which made it helpful for short use cases. Now, one must create a cloud account. To be honest, it is surprising that Google allowed the token free API to go on for as long as it did." }, { "code": null, "e": 571, "s": 410, "text": "In looking for an alternative for short use cases requiring the geo location of a street address, I found that OpenStreetMap is a simple and useful replacement." }, { "code": null, "e": 738, "s": 571, "text": "This feature is primarily targeted toward users who already have some experience working with R. These users will find the integration beneficial for several reasons:" }, { "code": null, "e": 808, "s": 738, "text": "Full access to any R package or function that has been installed in R" }, { "code": null, "e": 875, "s": 808, "text": "Use of Tableau capabilities to further analyze and understand data" }, { "code": null, "e": 964, "s": 875, "text": "Provides a platform to integrate open source data and software with proprietary software" }, { "code": null, "e": 1110, "s": 964, "text": "Users must have access to R/RStudio and Tableau. The two softwares can either be present on the same computer or can be present remotely (cloud)." }, { "code": null, "e": 1480, "s": 1110, "text": "There is a way to execute R or Python commands from Tableau in order to allow us to leverage the capabilities of these programming languages (functions, models and packages). You can do this via calculated fields that dynamically communicate with an R or Python instance, and the results are returned back to Tableau as a predetermined data type (INT, REAL, BOOL, STR)." }, { "code": null, "e": 1750, "s": 1480, "text": "This integration is helpful when there is a need for dynamically computed fields to support analysts’ needs without having to run code separately and send a new dataset back. For this reason, we will not be using this capability, but you can check a related blog below." }, { "code": null, "e": 1943, "s": 1750, "text": "In many cases, we have access to data with location information (e.g. Address, City, County, Zip Code, Country). If we want to visualize this data with more detail, we need to use geolocation." }, { "code": null, "e": 2043, "s": 1943, "text": "The geolocation coordinates (longitude, latitude) need to be calculated based on the location data." }, { "code": null, "e": 2188, "s": 2043, "text": "Nominatim is a free search engine for OpenStreetMap data. Using Nominatim, we can easily calculate geolocation coordinates from a given address." }, { "code": null, "e": 2366, "s": 2188, "text": "OpenStreetMap consists of data built by a community of mappers who contribute and maintain data about roads, trails, cafés, railway stations, and much more, all over the world." }, { "code": null, "e": 2402, "s": 2366, "text": "https://www.openstreetmap.org/about" }, { "code": null, "e": 2631, "s": 2402, "text": "To load packages in R/RStudio, we are going to use tidyverse, which is a collection of R packages designed for data science as well as other packages to help with data cleaning and processing. The code blocks below allow you to:" }, { "code": null, "e": 2737, "s": 2631, "text": "Check if the required package is installedInstall uninstalled packagesLoad the package after installation" }, { "code": null, "e": 2780, "s": 2737, "text": "Check if the required package is installed" }, { "code": null, "e": 2809, "s": 2780, "text": "Install uninstalled packages" }, { "code": null, "e": 2845, "s": 2809, "text": "Load the package after installation" }, { "code": null, "e": 2863, "s": 2845, "text": "Package Tidyverse" }, { "code": null, "e": 2881, "s": 2863, "text": "www.tidyverse.org" }, { "code": null, "e": 3085, "s": 2881, "text": "# CHECK IF PACKAGE IS INSTALLEDif(!require(\"tidyverse\")){ # IF PACKAGE NOT FOUND, INSTALL IT install.packages(\"tidyverse\", dependencies = TRUE) # LOAD PACKAGE AFTER INSTALLETION library(\"tidyverse\")}" }, { "code": null, "e": 3099, "s": 3085, "text": "Package rvest" }, { "code": null, "e": 3110, "s": 3099, "text": "github.com" }, { "code": null, "e": 3298, "s": 3110, "text": "# CHECK IF PACKAGE IS INSTALLEDif(!require(\"rvest\")){# IF PACKAGE NOT FOUND, INSTALL IT install.packages(\"rvest\", dependencies = TRUE)# LOAD PACKAGE AFTER INSTALLETION library(\"rvest\")}" }, { "code": null, "e": 3314, "s": 3298, "text": "Package stringi" }, { "code": null, "e": 3325, "s": 3314, "text": "github.com" }, { "code": null, "e": 3519, "s": 3325, "text": "# CHECK IF PACKAGE IS INSTALLEDif(!require(\"stringi\")){# IF PACKAGE NOT FOUND, INSTALL IT install.packages(\"stringi\", dependencies = TRUE)# LOAD PACKAGE AFTER INSTALLETION library(\"stringi\")}" }, { "code": null, "e": 3536, "s": 3519, "text": "Package jsonlite" }, { "code": null, "e": 3547, "s": 3536, "text": "github.com" }, { "code": null, "e": 3744, "s": 3547, "text": "# CHECK IF PACKAGE IS INSTALLEDif(!require(\"jsonlite\")){# IF PACKAGE NOT FOUND, INSTALL IT install.packages(\"jsonlite\", dependencies = TRUE)# LOAD PACKAGE AFTER INSTALLETION library(\"jsonlite\")}" }, { "code": null, "e": 3853, "s": 3744, "text": "The geocode function below allows us to make requests to Nominatim (a search engine for OpenStreetMap data)." }, { "code": null, "e": 3901, "s": 3853, "text": "Nominatim: https://nominatim.openstreetmap.org/" }, { "code": null, "e": 3966, "s": 3901, "text": "Resources: https://nominatim.org/release-docs/develop/api/Search" }, { "code": null, "e": 4116, "s": 3966, "text": "The function takes and inputs the following parameters which can be modified depending on your needs: [Name], [Address], [City] , [State] , [Zipcode]" }, { "code": null, "e": 5339, "s": 4116, "text": "geocode <- function(name, address, city, state, zipcode){ # NOMINATIM SEARCH API URL src_url <- \"https://nominatim.openstreetmap.org/search?q=\" # CREATE A FULL ADDRESS addr <- paste(address, city, state, zipcode, sep = \"%2C\") # CREATE A SEARCH URL BASED ON NOMINATIM API TO RETURN GEOJSON requests <- paste0(src_url, query, \"&format=geojson\") # ITERATE OVER THE URLS AND MAKE REQUEST TO THE SEARCH API for (i in 1:length(requests)) { # QUERY THE API TRANSFORM RESPONSE FROM JSON TO R LIST response <- read_html(requests[i]) %>% html_node(\"p\") %>% html_text() %>% fromJSON() # FROM THE RESPONSE EXTRACT LATITUDE AND LONGITUDE COORDINATES lon <- response$features$geometry$coordinates[[1]][1] lat <- response$features$geometry$coordinates[[1]][2] # CREATE A COORDINATES DATAFRAME if(i == 1) { loc <- tibble(name = name[i], address = str_replace_all(addr[i], \"%2C\", \",\"), latitude = lat, longitude = lon) }else{ df <- tibble(name = name[i], address = str_replace_all(addr[i], \"%2C\", \",\"), latitude = lat, longitude = lon) loc <- bind_rows(loc, df) } } return(loc)}" }, { "code": null, "e": 5615, "s": 5339, "text": "This information is derived from inspections of restaurants and other food establishments in Chicago from January 1, 2010 to the present. Inspections are performed by staff from the Chicago Department of Public Health’s Food Protection Program using a standardized procedure." }, { "code": null, "e": 5638, "s": 5615, "text": "data.cityofchicago.org" }, { "code": null, "e": 5852, "s": 5638, "text": "The food inspection data has geolocation coordinates, and we can use them to check the accuracy of our results. In this sample dataset, we will only use the location columns to find the coordinates of restaurants." }, { "code": null, "e": 5985, "s": 5852, "text": "In the code chunk below, we are reading the data and making some changes to make sure that the address works with the Nominatim API." }, { "code": null, "e": 6002, "s": 5985, "text": "Reading the data" }, { "code": null, "e": 6149, "s": 6002, "text": "# READ THE DATAdata <- read_csv(\"food_inspection_sample.csv\")# REMOVE SPACE FROM COLUMNScolnames(data) <- str_replace_all(colnames(data),\" \", \"_\")" }, { "code": null, "e": 6167, "s": 6149, "text": "Cleaning The Data" }, { "code": null, "e": 6415, "s": 6167, "text": "# REMOVE SPACE FROM RESULTSdata$Results <- data$Results %>% str_replace_all(\" w/ \", \" with \") %>% str_replace_all(\" \", \"_\")# EXTRACT RISK LEVEL data$Risk <- tolower(data$Risk) %>% str_extract(\"\\\\(.*\\\\)\") %>% str_extract(\"[a-z]+\")head(data)" }, { "code": null, "e": 6503, "s": 6415, "text": "In this section, we will prepare the address variable to match the Nominatim API style." }, { "code": null, "e": 6558, "s": 6503, "text": "# EXTRACT THE ADDRESS VARIABLE address <- data$Address" }, { "code": null, "e": 6606, "s": 6558, "text": "Modifying the address variable to match the API" }, { "code": null, "e": 7127, "s": 6606, "text": "# CLEAN SPECIAL CASES (e.g. 1 N MAY BLDG)query <- str_replace_all(string = address, pattern = \"BLDG\", replacement = \" \")# CLEAN SPECIAL CASES (e.g. 3333-3339 N CLARK)query <- stri_replace(str = query, replacement = \" \", regex = \"(-[0-9]+\\\\s)\")# REPLACE SPACES (\\\\s) OR COMMAS (,) WITH PLUS SIGN (+)query <- str_replace_all(string = query, pattern = \"\\\\s|,\", replacement = \"+\")" }, { "code": null, "e": 7281, "s": 7127, "text": "After the address variable is ready for the API, we can use the geocode function created at the beginning to find the geo coordinates of the restaurants." }, { "code": null, "e": 7449, "s": 7281, "text": "df <- geocode(name = data$DBA_Name, address = query, city = data$City, state = data$State, zipcode = data$Zipcode)" }, { "code": null, "e": 7662, "s": 7449, "text": "Finally, we can merge the two datasets to create a main one and work in Tableau. To achieve this, we use a left_join by the variable name on the returned DataFrame and DBA_Name variable from the original dataset." }, { "code": null, "e": 7724, "s": 7662, "text": "geo_df <- data %>% left_join(df, by = c(\"DBA_Name\" = \"name\"))" }, { "code": null, "e": 7829, "s": 7724, "text": "Now that there is a main dataset with geo coordinates, we can import it to Tableau for further analysis." }, { "code": null, "e": 7949, "s": 7829, "text": "To start working on Tableau, connect to the file viaText file (CSV). This is the file that was previously created in R." }, { "code": null, "e": 8232, "s": 7949, "text": "Tableau data interpreter helps to identify the data types of your columns, but it is always important to double check to ensure that the data type is correct. In this case, we are going to make sure that the variables (latitude and longitude) data type (geographic role) is correct." }, { "code": null, "e": 8452, "s": 8232, "text": "A good practice when working in Tableau is to Extract the dataset that you are working on by selecting the option on the top right corner of the screen. This will prevent you from overwriting/damaging the original data." }, { "code": null, "e": 8685, "s": 8452, "text": "When finished making changes to the data types, go to the highlighted worksheet section on the bottom left side of the screen. A prompt to save the dataset (extract) will appear. Follow the prompt to save it in the default location." }, { "code": null, "e": 8931, "s": 8685, "text": "On the worksheet, you will see the dataset columns in two sections depending of the data type (Dimensions and Measures). In the measures section, you will find the Longitude and Latitude variables. To map the coordinates, follow the steps below:" }, { "code": null, "e": 9239, "s": 8931, "text": "Double-click on the Longitude variable and Tableau will place the variable in the correct axis (columns).Double-click on the Latitude variable, and it will be placed in the correct axis (rows).After placing the variables in the correct axis, change the data type from Measure to Dimension for each variable." }, { "code": null, "e": 9345, "s": 9239, "text": "Double-click on the Longitude variable and Tableau will place the variable in the correct axis (columns)." }, { "code": null, "e": 9434, "s": 9345, "text": "Double-click on the Latitude variable, and it will be placed in the correct axis (rows)." }, { "code": null, "e": 9549, "s": 9434, "text": "After placing the variables in the correct axis, change the data type from Measure to Dimension for each variable." }, { "code": null, "e": 9685, "s": 9549, "text": "With the addresses located in the map, we can now add more features, such as county boundaries, zip codes, location details, and color." }, { "code": null, "e": 10031, "s": 9685, "text": "Double-click on the DBA Name variable to automatically assign it as a Detail Mark to see the name of each location.Double-click on the Risk variable. Since there are three categories, the Color Mark is automatically assigned.When hovering the mouse over the points, we should be able to see the name of the restaurant, risk, and geo coordinates." }, { "code": null, "e": 10147, "s": 10031, "text": "Double-click on the DBA Name variable to automatically assign it as a Detail Mark to see the name of each location." }, { "code": null, "e": 10258, "s": 10147, "text": "Double-click on the Risk variable. Since there are three categories, the Color Mark is automatically assigned." }, { "code": null, "e": 10379, "s": 10258, "text": "When hovering the mouse over the points, we should be able to see the name of the restaurant, risk, and geo coordinates." }, { "code": null, "e": 10516, "s": 10379, "text": "Tableau allows us to add additional layers to the default map. In this case, it would be helpful to know zip code labels and boundaries." }, { "code": null, "e": 10707, "s": 10516, "text": "On the main toolbar, select Map → Map Layers.A Map Layer view should come out on the left corner of the worksheet. Scroll down and enable the Zip Code Boundaries and Zip Code Labels options." }, { "code": null, "e": 10753, "s": 10707, "text": "On the main toolbar, select Map → Map Layers." }, { "code": null, "e": 10899, "s": 10753, "text": "A Map Layer view should come out on the left corner of the worksheet. Scroll down and enable the Zip Code Boundaries and Zip Code Labels options." }, { "code": null, "e": 10966, "s": 10899, "text": "Finally, you can zoom in to take a closer look at a specific area." }, { "code": null, "e": 11176, "s": 10966, "text": "Keep in mind, this blog post only scratches the surface of what is possible when we integrate OpenStreetMap, R, and Tableau. OpenStreetMap API does not require a token, which others (Google, Mapquest) require." } ]
How to force redirect to a particular route in angular? - GeeksforGeeks
15 Sep, 2020 Introduction: We can use the property binding concept and we can pass query parameters to routerLink. Using Property binding we can bind queryParams property and can provide the required details in object. Property Binding: It is a concept where we use square bracket notation to bind data to Document Object Model(DOM) properties of Hypertext markup language(HTML) element. import {Component, OnInit} from '@angular/core' @Component({ selector:'app-property',template:`<p [textContent]="title"></p> `}) export class AppComponent implements OnInit{ constructor(){}ngOnInit() {} title='Property Binding example in GeeksforGeeks'; } Output: We can implement the route re-direction in two ways:1) The first method is by doing from .html file.2) The second method is from the .ts file. Syntax for .html file: <a [routerLink]="[/path]" > State Details </a> Approach:First, configure the routes in app.module.tsImplement routerLink property binding with the required path in HTML file.After mentioning the above instructions, then we can click on the configured HTML element and can redirect it.Once you are done with clicking it it will automatically redirect you to another component.Implementation by code:app.module.ts:import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { RouterModule, Routes } from "@angular/router"; import { AppComponent } from "./app.component";import { StateComponent } from "./state/state.component"; const routes: Routes = [{ path: "punjab", component: StateComponent }]; @NgModule({ imports: [BrowserModule, RouterModule.forRoot(routes)], declarations: [AppComponent, StateComponent], bootstrap: [AppComponent],})export class AppModule {}app.component.html:<a [routerLink]="['/punjab']"> State Details </a><router-outlet></router-outlet>After clicking on the anchor tag, then we can see that the url will be changed in the following way and we will be directed to the configured component in the app.module.ts file.Output:state.component.html: Approach: First, configure the routes in app.module.ts Implement routerLink property binding with the required path in HTML file. After mentioning the above instructions, then we can click on the configured HTML element and can redirect it. Once you are done with clicking it it will automatically redirect you to another component. Implementation by code:app.module.ts: import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { RouterModule, Routes } from "@angular/router"; import { AppComponent } from "./app.component";import { StateComponent } from "./state/state.component"; const routes: Routes = [{ path: "punjab", component: StateComponent }]; @NgModule({ imports: [BrowserModule, RouterModule.forRoot(routes)], declarations: [AppComponent, StateComponent], bootstrap: [AppComponent],})export class AppModule {} app.component.html: <a [routerLink]="['/punjab']"> State Details </a><router-outlet></router-outlet> After clicking on the anchor tag, then we can see that the url will be changed in the following way and we will be directed to the configured component in the app.module.ts file. Output:state.component.html: Second method from .ts file:Approach:First, configure the routes in app.module.tsImplement routing by importing ‘Router’ from ‘@angular/router’.Then initialize the router in the constructor.After doing the above process, then implement routing in a function so that the function can be triggered from .html file.Once everything is done then we can force redirect the route to another component.Implementation By code:app.module.ts:import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component';import { StateComponent } from './state/state.component'; const routes: Routes = [ { path: 'punjab', component: StateComponent },]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes) ], declarations: [ AppComponent, StateComponent ], bootstrap: [ AppComponent ]})export class AppModule { }app.component.ts:import { Component, OnInit } from '@angular/core';import {Router} from '@angular/router'; @Component({ selector: 'app-main', templateUrl: './main.component.html', styleUrls: ['./main.component.css']})export class HomeComponent implements OnInit { constructor(private router:Router) { } ngOnInit(){} onSelect(){ this.router.navigate(['/punjab']); }}app.component.html:<a (click)="onSelect()"> State Details </a><router-outlet></router-outlet>After following the above code and one if you click on the anchor tag then the url will be changed and you will be redirected to the respective configured component.Output: Second method from .ts file: First, configure the routes in app.module.ts Implement routing by importing ‘Router’ from ‘@angular/router’. Then initialize the router in the constructor. After doing the above process, then implement routing in a function so that the function can be triggered from .html file. Once everything is done then we can force redirect the route to another component. Implementation By code:app.module.ts: import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component';import { StateComponent } from './state/state.component'; const routes: Routes = [ { path: 'punjab', component: StateComponent },]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes) ], declarations: [ AppComponent, StateComponent ], bootstrap: [ AppComponent ]})export class AppModule { } app.component.ts: import { Component, OnInit } from '@angular/core';import {Router} from '@angular/router'; @Component({ selector: 'app-main', templateUrl: './main.component.html', styleUrls: ['./main.component.css']})export class HomeComponent implements OnInit { constructor(private router:Router) { } ngOnInit(){} onSelect(){ this.router.navigate(['/punjab']); }} app.component.html: <a (click)="onSelect()"> State Details </a><router-outlet></router-outlet> After following the above code and one if you click on the anchor tag then the url will be changed and you will be redirected to the respective configured component. Output: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? 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? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25109, "s": 25081, "text": "\n15 Sep, 2020" }, { "code": null, "e": 25123, "s": 25109, "text": "Introduction:" }, { "code": null, "e": 25315, "s": 25123, "text": "We can use the property binding concept and we can pass query parameters to routerLink. Using Property binding we can bind queryParams property and can provide the required details in object." }, { "code": null, "e": 25484, "s": 25315, "text": "Property Binding: It is a concept where we use square bracket notation to bind data to Document Object Model(DOM) properties of Hypertext markup language(HTML) element." }, { "code": "import {Component, OnInit} from '@angular/core' @Component({ selector:'app-property',template:`<p [textContent]=\"title\"></p> `}) export class AppComponent implements OnInit{ constructor(){}ngOnInit() {} title='Property Binding example in GeeksforGeeks'; }", "e": 25752, "s": 25484, "text": null }, { "code": null, "e": 25760, "s": 25752, "text": "Output:" }, { "code": null, "e": 25903, "s": 25760, "text": "We can implement the route re-direction in two ways:1) The first method is by doing from .html file.2) The second method is from the .ts file." }, { "code": null, "e": 25927, "s": 25903, "text": "Syntax for .html file: " }, { "code": "<a [routerLink]=\"[/path]\" > State Details </a>", "e": 25976, "s": 25927, "text": null }, { "code": null, "e": 27163, "s": 25976, "text": "Approach:First, configure the routes in app.module.tsImplement routerLink property binding with the required path in HTML file.After mentioning the above instructions, then we can click on the configured HTML element and can redirect it.Once you are done with clicking it it will automatically redirect you to another component.Implementation by code:app.module.ts:import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { RouterModule, Routes } from \"@angular/router\"; import { AppComponent } from \"./app.component\";import { StateComponent } from \"./state/state.component\"; const routes: Routes = [{ path: \"punjab\", component: StateComponent }]; @NgModule({ imports: [BrowserModule, RouterModule.forRoot(routes)], declarations: [AppComponent, StateComponent], bootstrap: [AppComponent],})export class AppModule {}app.component.html:<a [routerLink]=\"['/punjab']\"> State Details </a><router-outlet></router-outlet>After clicking on the anchor tag, then we can see that the url will be changed in the following way and we will be directed to the configured component in the app.module.ts file.Output:state.component.html: " }, { "code": null, "e": 27173, "s": 27163, "text": "Approach:" }, { "code": null, "e": 27218, "s": 27173, "text": "First, configure the routes in app.module.ts" }, { "code": null, "e": 27293, "s": 27218, "text": "Implement routerLink property binding with the required path in HTML file." }, { "code": null, "e": 27404, "s": 27293, "text": "After mentioning the above instructions, then we can click on the configured HTML element and can redirect it." }, { "code": null, "e": 27496, "s": 27404, "text": "Once you are done with clicking it it will automatically redirect you to another component." }, { "code": null, "e": 27534, "s": 27496, "text": "Implementation by code:app.module.ts:" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { RouterModule, Routes } from \"@angular/router\"; import { AppComponent } from \"./app.component\";import { StateComponent } from \"./state/state.component\"; const routes: Routes = [{ path: \"punjab\", component: StateComponent }]; @NgModule({ imports: [BrowserModule, RouterModule.forRoot(routes)], declarations: [AppComponent, StateComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 28048, "s": 27534, "text": null }, { "code": null, "e": 28068, "s": 28048, "text": "app.component.html:" }, { "code": "<a [routerLink]=\"['/punjab']\"> State Details </a><router-outlet></router-outlet>", "e": 28151, "s": 28068, "text": null }, { "code": null, "e": 28330, "s": 28151, "text": "After clicking on the anchor tag, then we can see that the url will be changed in the following way and we will be directed to the configured component in the app.module.ts file." }, { "code": null, "e": 28360, "s": 28330, "text": "Output:state.component.html: " }, { "code": null, "e": 29966, "s": 28360, "text": "Second method from .ts file:Approach:First, configure the routes in app.module.tsImplement routing by importing ‘Router’ from ‘@angular/router’.Then initialize the router in the constructor.After doing the above process, then implement routing in a function so that the function can be triggered from .html file.Once everything is done then we can force redirect the route to another component.Implementation By code:app.module.ts:import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component';import { StateComponent } from './state/state.component'; const routes: Routes = [ { path: 'punjab', component: StateComponent },]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes) ], declarations: [ AppComponent, StateComponent ], bootstrap: [ AppComponent ]})export class AppModule { }app.component.ts:import { Component, OnInit } from '@angular/core';import {Router} from '@angular/router'; @Component({ selector: 'app-main', templateUrl: './main.component.html', styleUrls: ['./main.component.css']})export class HomeComponent implements OnInit { constructor(private router:Router) { } ngOnInit(){} onSelect(){ this.router.navigate(['/punjab']); }}app.component.html:<a (click)=\"onSelect()\"> State Details </a><router-outlet></router-outlet>After following the above code and one if you click on the anchor tag then the url will be changed and you will be redirected to the respective configured component.Output:" }, { "code": null, "e": 29995, "s": 29966, "text": "Second method from .ts file:" }, { "code": null, "e": 30040, "s": 29995, "text": "First, configure the routes in app.module.ts" }, { "code": null, "e": 30104, "s": 30040, "text": "Implement routing by importing ‘Router’ from ‘@angular/router’." }, { "code": null, "e": 30151, "s": 30104, "text": "Then initialize the router in the constructor." }, { "code": null, "e": 30274, "s": 30151, "text": "After doing the above process, then implement routing in a function so that the function can be triggered from .html file." }, { "code": null, "e": 30357, "s": 30274, "text": "Once everything is done then we can force redirect the route to another component." }, { "code": null, "e": 30395, "s": 30357, "text": "Implementation By code:app.module.ts:" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component';import { StateComponent } from './state/state.component'; const routes: Routes = [ { path: 'punjab', component: StateComponent },]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes) ], declarations: [ AppComponent, StateComponent ], bootstrap: [ AppComponent ]})export class AppModule { }", "e": 30921, "s": 30395, "text": null }, { "code": null, "e": 30939, "s": 30921, "text": "app.component.ts:" }, { "code": "import { Component, OnInit } from '@angular/core';import {Router} from '@angular/router'; @Component({ selector: 'app-main', templateUrl: './main.component.html', styleUrls: ['./main.component.css']})export class HomeComponent implements OnInit { constructor(private router:Router) { } ngOnInit(){} onSelect(){ this.router.navigate(['/punjab']); }}", "e": 31305, "s": 30939, "text": null }, { "code": null, "e": 31325, "s": 31305, "text": "app.component.html:" }, { "code": "<a (click)=\"onSelect()\"> State Details </a><router-outlet></router-outlet>", "e": 31402, "s": 31325, "text": null }, { "code": null, "e": 31568, "s": 31402, "text": "After following the above code and one if you click on the anchor tag then the url will be changed and you will be redirected to the respective configured component." }, { "code": null, "e": 31576, "s": 31568, "text": "Output:" }, { "code": null, "e": 31591, "s": 31576, "text": "AngularJS-Misc" }, { "code": null, "e": 31598, "s": 31591, "text": "Picked" }, { "code": null, "e": 31608, "s": 31598, "text": "AngularJS" }, { "code": null, "e": 31625, "s": 31608, "text": "Web Technologies" }, { "code": null, "e": 31723, "s": 31625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31767, "s": 31723, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 31802, "s": 31767, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31826, "s": 31802, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31879, "s": 31826, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31928, "s": 31879, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 31970, "s": 31928, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32003, "s": 31970, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32046, "s": 32003, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32096, "s": 32046, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How Can I Measure Data Quality?. Introducing YData Quality: An... | by Fabiana Clemente | Towards Data Science
“Everyone wants to do the model work, not the data work” — Google Research According to Alation’s State of Data Culture Report, 87% of employees attribute poor data quality to why most organizations fail to adopt AI meaningfully. Based on a 2020 study by McKinsey, high-quality data is crucial for digital transformations to propel an organization, past competitors. Based on a 2020 YData study, the biggest problem faced by data scientists was the unavailability of high-quality data. The underlying problem in the rapidly evolving AI industry is apparent, and the scarcest resource in AI now is high-quality data at scale. Despite realizing this, the industry has been focussing on improving models, libraries, and frameworks for years. Data scientists often see modeling as exciting work and data cleaning as tedious tasks. The neglected data issues compound to cause adverse downstream effects through the entire machine learning solution development. Thankfully, we have seen a paradigm shift in the recent past, pioneered by Andrew Ng, moving from a model-centric approach to a data-centric approach. We’re witnessing data-centric competitions, awareness in the community. We’re marching in the right direction. However, the problem persists; there’s still a lack of industry-ready tools to understand the underlying data quality issues and improve them. As you can already tell, we’re obsessed with solving this pressing data problem for the AI industry. First, we open-sourced our synthetic data engine and built a community around it. Synthetic data can help create high-quality data, but what happens to the existing real-world messy data? What if we could analyze the data for standard quality issues and flag them by priority upfront, saving precious time for the data scientists? That’s the question we’d like to answer today. Today, we are excited to announce YData Quality, an open-source python library for assessing Data Quality throughout the multiple stages of a data pipeline development. The package is handy, especially in the initial stages of development when you’re still grasping the value of the available data. We can only capture a holistic view of the data through a look at data from multiple dimensions. YData Quality evaluates it modularly — specific modules for each dimension, finally wrapped into a single data quality engine. The quality engine performs several tests on the input data, and warnings are raised depending on the data quality. A warning will contain not only the details of the detected issue but also a priority level based on the expected impact. Here’s a quick overview of the core modules in YData Quality: Bias and Fairness: Guarantees that data is not biased and its application is fair concerning sensitive attributes for which there are legal and ethical obligations not to differentiate the treatment (e.g., gender, race). Data Expectations: Unit tests for data that assert a particular property. Leverage Great Expectations validations, integrate their outcomes in our framework and check the quality of the validations. Data Relations: Check the association between features, test for causality effects, estimate the feature importance, and detect features with high collinearity. Drift Analysis: Often, with time, different patterns may evolve from the data. Using this module, you can check the stability of your features (i.e., covariates) and target (i.e., label) as you look at different chunks of data. Duplicates: Data may come from different sources and is not always unique. This module checks for repeated entries in data that are redundant and can (or should) be dropped. Labellings: With specialized engines for categorical and numerical targets, this module provides a test suite that detects both common (e.g., imbalanced labels) and complex analysis (e.g., label outliers). Missings: Missing values can cause multiple problems in data applications. With this module, you can better understand the severity of their impact and how they occur. Erroneous Data: Data may contain values without inherent meaning. With this module, you can inspect your data (tabular and time-series) for typical misguided values on data points. This is the part we all love. Fire up your terminal and type the following: pip install ydata-quality You have all the data quality engines installed in a single command. To walk you through various library usages, we have included multiple tutorials presented as jupyter notebooks. Let us give you a flavor of how our data quality engine works: And here’s how a sample report looks like: From the above output, we notice that duplicated column is a high-priority issue and needs further inspection. To this, we use the get_warnings() method. Simply type in the following: dq.get_warnings(test="Duplicate Columns") We can see the detailed output specific to the issue we want to resolve: [QualityWarning(category='Duplicates', test='Duplicate Columns', description='Found 1 columns with exactly the same feature values as other columns.', priority=<Priority.P1: 1>, data={'workclass': ['workclass2']})] Based on the evaluation, we can see that the columns workclass and workclass2 are entirely duplicated, which can have serious consequences downstream. We must drop the duplicated column and move on to the next identified issue based on its priority. We saw how the package could help data scientists fix data quality issues by flagging them upfront with the details. Further, we recommend starting with this tutorial notebook that evaluates a messy dataset for data quality issues and fixes them. Got any questions? Join our dedicated Community Slack space and ask away everything. We’re a friendly bunch of people looking to learn from each other and grow in the process. Accelerating AI with improved data is at the core of what we do, and this open-source project is yet another step towards our meaningful journey. We invite you to be part of it — together, the possibilities are endless. Fabiana Clemente is CDO at YData. Accelerating AI with improved data. YData provides the first data development platform for Data Science teams.
[ { "code": null, "e": 247, "s": 172, "text": "“Everyone wants to do the model work, not the data work” — Google Research" }, { "code": null, "e": 539, "s": 247, "text": "According to Alation’s State of Data Culture Report, 87% of employees attribute poor data quality to why most organizations fail to adopt AI meaningfully. Based on a 2020 study by McKinsey, high-quality data is crucial for digital transformations to propel an organization, past competitors." }, { "code": null, "e": 797, "s": 539, "text": "Based on a 2020 YData study, the biggest problem faced by data scientists was the unavailability of high-quality data. The underlying problem in the rapidly evolving AI industry is apparent, and the scarcest resource in AI now is high-quality data at scale." }, { "code": null, "e": 1128, "s": 797, "text": "Despite realizing this, the industry has been focussing on improving models, libraries, and frameworks for years. Data scientists often see modeling as exciting work and data cleaning as tedious tasks. The neglected data issues compound to cause adverse downstream effects through the entire machine learning solution development." }, { "code": null, "e": 1390, "s": 1128, "text": "Thankfully, we have seen a paradigm shift in the recent past, pioneered by Andrew Ng, moving from a model-centric approach to a data-centric approach. We’re witnessing data-centric competitions, awareness in the community. We’re marching in the right direction." }, { "code": null, "e": 1533, "s": 1390, "text": "However, the problem persists; there’s still a lack of industry-ready tools to understand the underlying data quality issues and improve them." }, { "code": null, "e": 1822, "s": 1533, "text": "As you can already tell, we’re obsessed with solving this pressing data problem for the AI industry. First, we open-sourced our synthetic data engine and built a community around it. Synthetic data can help create high-quality data, but what happens to the existing real-world messy data?" }, { "code": null, "e": 2012, "s": 1822, "text": "What if we could analyze the data for standard quality issues and flag them by priority upfront, saving precious time for the data scientists? That’s the question we’d like to answer today." }, { "code": null, "e": 2181, "s": 2012, "text": "Today, we are excited to announce YData Quality, an open-source python library for assessing Data Quality throughout the multiple stages of a data pipeline development." }, { "code": null, "e": 2535, "s": 2181, "text": "The package is handy, especially in the initial stages of development when you’re still grasping the value of the available data. We can only capture a holistic view of the data through a look at data from multiple dimensions. YData Quality evaluates it modularly — specific modules for each dimension, finally wrapped into a single data quality engine." }, { "code": null, "e": 2773, "s": 2535, "text": "The quality engine performs several tests on the input data, and warnings are raised depending on the data quality. A warning will contain not only the details of the detected issue but also a priority level based on the expected impact." }, { "code": null, "e": 2835, "s": 2773, "text": "Here’s a quick overview of the core modules in YData Quality:" }, { "code": null, "e": 3056, "s": 2835, "text": "Bias and Fairness: Guarantees that data is not biased and its application is fair concerning sensitive attributes for which there are legal and ethical obligations not to differentiate the treatment (e.g., gender, race)." }, { "code": null, "e": 3255, "s": 3056, "text": "Data Expectations: Unit tests for data that assert a particular property. Leverage Great Expectations validations, integrate their outcomes in our framework and check the quality of the validations." }, { "code": null, "e": 3416, "s": 3255, "text": "Data Relations: Check the association between features, test for causality effects, estimate the feature importance, and detect features with high collinearity." }, { "code": null, "e": 3644, "s": 3416, "text": "Drift Analysis: Often, with time, different patterns may evolve from the data. Using this module, you can check the stability of your features (i.e., covariates) and target (i.e., label) as you look at different chunks of data." }, { "code": null, "e": 3818, "s": 3644, "text": "Duplicates: Data may come from different sources and is not always unique. This module checks for repeated entries in data that are redundant and can (or should) be dropped." }, { "code": null, "e": 4024, "s": 3818, "text": "Labellings: With specialized engines for categorical and numerical targets, this module provides a test suite that detects both common (e.g., imbalanced labels) and complex analysis (e.g., label outliers)." }, { "code": null, "e": 4192, "s": 4024, "text": "Missings: Missing values can cause multiple problems in data applications. With this module, you can better understand the severity of their impact and how they occur." }, { "code": null, "e": 4373, "s": 4192, "text": "Erroneous Data: Data may contain values without inherent meaning. With this module, you can inspect your data (tabular and time-series) for typical misguided values on data points." }, { "code": null, "e": 4449, "s": 4373, "text": "This is the part we all love. Fire up your terminal and type the following:" }, { "code": null, "e": 4475, "s": 4449, "text": "pip install ydata-quality" }, { "code": null, "e": 4656, "s": 4475, "text": "You have all the data quality engines installed in a single command. To walk you through various library usages, we have included multiple tutorials presented as jupyter notebooks." }, { "code": null, "e": 4719, "s": 4656, "text": "Let us give you a flavor of how our data quality engine works:" }, { "code": null, "e": 4762, "s": 4719, "text": "And here’s how a sample report looks like:" }, { "code": null, "e": 4916, "s": 4762, "text": "From the above output, we notice that duplicated column is a high-priority issue and needs further inspection. To this, we use the get_warnings() method." }, { "code": null, "e": 4946, "s": 4916, "text": "Simply type in the following:" }, { "code": null, "e": 4988, "s": 4946, "text": "dq.get_warnings(test=\"Duplicate Columns\")" }, { "code": null, "e": 5061, "s": 4988, "text": "We can see the detailed output specific to the issue we want to resolve:" }, { "code": null, "e": 5276, "s": 5061, "text": "[QualityWarning(category='Duplicates', test='Duplicate Columns', description='Found 1 columns with exactly the same feature values as other columns.', priority=<Priority.P1: 1>, data={'workclass': ['workclass2']})]" }, { "code": null, "e": 5526, "s": 5276, "text": "Based on the evaluation, we can see that the columns workclass and workclass2 are entirely duplicated, which can have serious consequences downstream. We must drop the duplicated column and move on to the next identified issue based on its priority." }, { "code": null, "e": 5773, "s": 5526, "text": "We saw how the package could help data scientists fix data quality issues by flagging them upfront with the details. Further, we recommend starting with this tutorial notebook that evaluates a messy dataset for data quality issues and fixes them." }, { "code": null, "e": 5949, "s": 5773, "text": "Got any questions? Join our dedicated Community Slack space and ask away everything. We’re a friendly bunch of people looking to learn from each other and grow in the process." }, { "code": null, "e": 6169, "s": 5949, "text": "Accelerating AI with improved data is at the core of what we do, and this open-source project is yet another step towards our meaningful journey. We invite you to be part of it — together, the possibilities are endless." }, { "code": null, "e": 6203, "s": 6169, "text": "Fabiana Clemente is CDO at YData." }, { "code": null, "e": 6239, "s": 6203, "text": "Accelerating AI with improved data." } ]
Reason of runtime error in C/C++ - GeeksforGeeks
08 Feb, 2021 In this article, we will discuss the reason for the run-time error and its solution. Runtime Error: A runtime error in a program is an error that occurs while the program is running after being successfully compiled. Below are some methods to identify the reason behind Runtime error: Method 1: When the index of the array is assigned with a negative index it leads to invalid memory access during runtime error. Below is the C++ Program to illustrate the invalid memory access during run-time: C++ // C++ program to illustrate invalid // memory access during run-time #include <iostream> using namespace std; // Global declaration int arr[5]; // Driver Code int main() { int answer = arr[-10]; cout << answer; return 0; } 1736487104 Method 2: Sometimes Array or vector runs out of bound of their limits resulting in a runtime error. Below is the C++ program illustrating array runs out of bound: C++ // C++ program to illustrate // array runs out of bound #include <iostream> using namespace std; // Driver Code int main() { long n; n = 100000000000; // 'n' is out of bound for // the array limit long a[n]; cout << a[1] << " "; return 0; } Output: Explanation: This is an error for index out of bound. It can be resolved by using the size of the array/vector as within the limit. Method 3: Some silly mistakes encountered while coding in hurry, sometimes leads to runtime error. Below is the C++ program illustrating runtime error by un-assigned variables: C++ // C++ program to illustrate runtime // error by un-assigned variables #include <iostream> using namespace std; // Driver Code int main() { long long N; // N is assigned garbage value long arr[N]; cin >> N; for (int i = 0; i < N; i++) { cin >> arr[i]; } for (int i = 0; i < N; i++) { cout << arr[i] << " "; } return 0; } Output: Explanation: The above program shows “Bad memory access (SIGBUS)” because: Here, variable N is assigned a garbage value resulting in a runtime error. Sometimes, since it depends on the compiler how it assigned the garbage value. This can be resolved by declaring arr[N] after scanning the value for variable n and checking if it is the upper or lower limit of the array/vector index. CPP-Basics C++ C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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": 24196, "s": 24165, "text": " \n08 Feb, 2021\n" }, { "code": null, "e": 24281, "s": 24196, "text": "In this article, we will discuss the reason for the run-time error and its solution." }, { "code": null, "e": 24481, "s": 24281, "text": "Runtime Error: A runtime error in a program is an error that occurs while the program is running after being successfully compiled. Below are some methods to identify the reason behind Runtime error:" }, { "code": null, "e": 24691, "s": 24481, "text": "Method 1: When the index of the array is assigned with a negative index it leads to invalid memory access during runtime error. Below is the C++ Program to illustrate the invalid memory access during run-time:" }, { "code": null, "e": 24695, "s": 24691, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to illustrate invalid \n// memory access during run-time \n#include <iostream> \nusing namespace std; \n \n// Global declaration \nint arr[5]; \n \n// Driver Code \nint main() \n{ \n int answer = arr[-10]; \n cout << answer; \n \n return 0; \n} \n\n\n\n\n\n", "e": 24976, "s": 24705, "text": null }, { "code": null, "e": 24988, "s": 24976, "text": "1736487104\n" }, { "code": null, "e": 25151, "s": 24988, "text": "Method 2: Sometimes Array or vector runs out of bound of their limits resulting in a runtime error. Below is the C++ program illustrating array runs out of bound:" }, { "code": null, "e": 25155, "s": 25151, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to illustrate \n// array runs out of bound \n#include <iostream> \nusing namespace std; \n \n// Driver Code \nint main() \n{ \n long n; \n n = 100000000000; \n \n // 'n' is out of bound for \n // the array limit \n long a[n]; \n \n cout << a[1] << \" \"; \n return 0; \n} \n\n\n\n\n\n", "e": 25471, "s": 25165, "text": null }, { "code": null, "e": 25480, "s": 25471, "text": "Output:\n" }, { "code": null, "e": 25493, "s": 25480, "text": "Explanation:" }, { "code": null, "e": 25534, "s": 25493, "text": "This is an error for index out of bound." }, { "code": null, "e": 25612, "s": 25534, "text": "It can be resolved by using the size of the array/vector as within the limit." }, { "code": null, "e": 25789, "s": 25612, "text": "Method 3: Some silly mistakes encountered while coding in hurry, sometimes leads to runtime error. Below is the C++ program illustrating runtime error by un-assigned variables:" }, { "code": null, "e": 25793, "s": 25789, "text": "C++" }, { "code": "\n\n\n\n\n\n\n// C++ program to illustrate runtime \n// error by un-assigned variables \n#include <iostream> \nusing namespace std; \n \n// Driver Code \nint main() \n{ \n long long N; \n \n // N is assigned garbage value \n long arr[N]; \n \n cin >> N; \n \n for (int i = 0; i < N; i++) { \n cin >> arr[i]; \n } \n \n for (int i = 0; i < N; i++) { \n cout << arr[i] << \" \"; \n } \n \n return 0; \n} \n\n\n\n\n\n", "e": 26226, "s": 25803, "text": null }, { "code": null, "e": 26235, "s": 26226, "text": "Output:\n" }, { "code": null, "e": 26248, "s": 26235, "text": "Explanation:" }, { "code": null, "e": 26311, "s": 26248, "text": " The above program shows “Bad memory access (SIGBUS)” because:" }, { "code": null, "e": 26386, "s": 26311, "text": "Here, variable N is assigned a garbage value resulting in a runtime error." }, { "code": null, "e": 26465, "s": 26386, "text": "Sometimes, since it depends on the compiler how it assigned the garbage value." }, { "code": null, "e": 26620, "s": 26465, "text": "This can be resolved by declaring arr[N] after scanning the value for variable n and checking if it is the upper or lower limit of the array/vector index." }, { "code": null, "e": 26633, "s": 26620, "text": "\nCPP-Basics\n" }, { "code": null, "e": 26639, "s": 26633, "text": "\nC++\n" }, { "code": null, "e": 26654, "s": 26639, "text": "\nC++ Programs\n" }, { "code": null, "e": 26859, "s": 26654, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 26887, "s": 26859, "text": "Operator Overloading in C++" }, { "code": null, "e": 26907, "s": 26887, "text": "Polymorphism in C++" }, { "code": null, "e": 26940, "s": 26907, "text": "Friend class and function in C++" }, { "code": null, "e": 26964, "s": 26940, "text": "Sorting a vector in C++" }, { "code": null, "e": 26985, "s": 26964, "text": "Iterators in C++ STL" }, { "code": null, "e": 27020, "s": 26985, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27046, "s": 27020, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27105, "s": 27046, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27149, "s": 27105, "text": "Program to print ASCII Value of a character" } ]
Check if a String is whitespace, empty ("") or null in Java
Let’s say the following is our string. String myStr = ""; Now, we will check whether the above string is whitespace, empty ("") or null. if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) { System.out.println("String is not null or not empty or not whitespace"); } else { System.out.println("String is null or empty or whitespace"); } The following is an example that checks for an empty string. Live Demo public class Demo { public static void main(String[] args) { String myStr = ""; if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) { System.out.println("String is not null or not empty or not whitespace"); } else { System.out.println("String is null or empty or whitespace"); } } } String is null or empty or whitespace Let us see another example that checks for whitespace input. Live Demo public class Demo { public static void main(String[] args) { String myStr = " "; if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) { System.out.println("String is not null or not empty or not whitespace"); } else { System.out.println("String is null or empty or whitespace"); } } } String is null or empty or whitespace
[ { "code": null, "e": 1101, "s": 1062, "text": "Let’s say the following is our string." }, { "code": null, "e": 1120, "s": 1101, "text": "String myStr = \"\";" }, { "code": null, "e": 1199, "s": 1120, "text": "Now, we will check whether the above string is whitespace, empty (\"\") or null." }, { "code": null, "e": 1417, "s": 1199, "text": "if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {\n System.out.println(\"String is not null or not empty or not whitespace\");\n} else {\n System.out.println(\"String is null or empty or whitespace\");\n}" }, { "code": null, "e": 1478, "s": 1417, "text": "The following is an example that checks for an empty string." }, { "code": null, "e": 1489, "s": 1478, "text": " Live Demo" }, { "code": null, "e": 1833, "s": 1489, "text": "public class Demo {\n public static void main(String[] args) {\n String myStr = \"\";\n if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {\n System.out.println(\"String is not null or not empty or not whitespace\");\n } else {\n System.out.println(\"String is null or empty or whitespace\");\n }\n }\n}" }, { "code": null, "e": 1871, "s": 1833, "text": "String is null or empty or whitespace" }, { "code": null, "e": 1932, "s": 1871, "text": "Let us see another example that checks for whitespace input." }, { "code": null, "e": 1943, "s": 1932, "text": " Live Demo" }, { "code": null, "e": 2288, "s": 1943, "text": "public class Demo {\n public static void main(String[] args) {\n String myStr = \" \";\n if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {\n System.out.println(\"String is not null or not empty or not whitespace\");\n } else {\n System.out.println(\"String is null or empty or whitespace\");\n }\n }\n}" }, { "code": null, "e": 2326, "s": 2288, "text": "String is null or empty or whitespace" } ]
Nth node from end of linked list | Practice | GeeksforGeeks
Given a linked list consisting of L nodes and given a number N. The task is to find the Nth node from the end of the linked list. Example 1: Input: N = 2 LinkedList: 1->2->3->4->5->6->7->8->9 Output: 8 Explanation: In the first example, there are 9 nodes in linked list and we need to find 2nd node from end. 2nd node from end os 8. Example 2: Input: N = 5 LinkedList: 10->5->100->5 Output: -1 Explanation: In the second example, there are 4 nodes in the linked list and we need to find 5th from the end. Since 'n' is more than the number of nodes in the linked list, the output is -1. Your Task: The task is to complete the function getNthFromLast() which takes two arguments: reference to head and N and you need to return Nth from the end or -1 in case node doesn't exist.. Note: Try to solve in single traversal. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 <= L <= 106 1 <= N <= 106 0 2019sushilkumarkori9 hours ago int getNthFromLast(Node *head, int n) { // Your code here int l=0; Node* temp = head; while(temp!=NULL){ l++; temp=temp->next; } if(n>l){ return -1; } temp=head; int i=0; while(temp!=NULL){ i++; if(i == (l-n)+1){ return temp->data; } temp=temp->next; } return -1; } 0 jimmynandwana5 days ago int getNthFromLast(Node head, int n) { // Your code here Node low = head; Node high = head; for(int i = 1 ; i<n;i++){ if(high.next != null){ high = high.next; } else{ return -1; } } while(high != null && high.next != null){ low = low.next; high = high.next; } return low.data; } +1 bipulharsh1235 days ago Time : O(N) Space: O(1) int getNthFromLast(Node *head, int n){ // Your code here Node *ptr=NULL; Node *startBatch=head; int count=0; while(head){ count = (count+1)%n; if(count%n==0){ ptr = startBatch; startBatch = head->next; } head = head->next; } if(!ptr) return -1; while(count--){ ptr = ptr->next; } return ptr->data;} 0 sailendrad1 week ago int getNthFromLast(Node head, int n) { // Your code here Node fast = head; Node slow = head; while(n > 1){ fast = fast.next; if(fast == null)return -1; n--; } while(fast.next !=null){ fast= fast.next; slow= slow.next; } return slow.data; } 0 sudeepgarg6711 week ago int getNthFromLast(Node *head, int n){ Node *temp = head; int count = 0; while(temp!=NULL){ count++; temp = temp->next; } if(n>count){ return -1; } int start = 0; Node *temp2 = head; while(start!=count-n){ temp2 = temp2->next; start++; } return temp2->data;} 0 nischithtn1 week ago int getNthFromLast(Node head, int n) { // Your code here LinkedList<Integer> l = new LinkedList<Integer>(); while(head!=null){ l.add(head.data); head=head.next; } int p=l.size(); int k =p-n; int z=-1; if(n<=p){ z=l.get(k); }else{ z=-1; } return z; } 0 akaashhardha1 week ago int getNthFromLast(struct Node *head, int n){ int count = 0; struct Node *temp = head; while(temp != NULL){ count++; temp = temp->next; } struct Node *temp2 = head; if(n <= count){ for(int i = 1; i <= count - n ; i++) temp2 = temp2->next; return temp2->data; } else return -1;} +2 nimox1 week ago int getNthFromLast(Node head, int n) { // Your code here Node temp = head; Node ans = head; int count = 0; while(temp!=null) { if(count>=n) ans=ans.next; temp = temp.next; count++; } if(n>count) return -1; return ans.data; } +1 shahabuddinbravo401 week ago int getNthFromLast(Node *head, int n){ Node *ptr=head; int count=0; while(ptr!=NULL) { ptr=ptr->next; count++; } if(count-n >= 0){ Node *ptr1=head; int index=1; while(ptr1!=NULL){ if(index==(count-n)+1){ return ptr1->data; } index++; ptr1=ptr1->next; } } else{ return -1; }} 0 vaibhav9812031 week ago JAVA int getNthFromLast(Node head, int n) { // Your code here int count = 1; Node n1 = head; while(n1.next!=null){ n1 = n1.next; count++; } int newIndex = count-n; if(count == n) return head.data; if(n > count) return -1; n1 = head; count = 1; while(n1.next!=null){ if(count == newIndex) break; n1 = n1.next; count++; } Node result = n1.next; return result.data; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 368, "s": 238, "text": "Given a linked list consisting of L nodes and given a number N. The task is to find the Nth node from the end of the linked list." }, { "code": null, "e": 379, "s": 368, "text": "Example 1:" }, { "code": null, "e": 574, "s": 379, "text": "Input:\nN = 2\nLinkedList: 1->2->3->4->5->6->7->8->9\nOutput: 8\nExplanation: In the first example, there\nare 9 nodes in linked list and we need\nto find 2nd node from end. 2nd node\nfrom end os 8. \n" }, { "code": null, "e": 585, "s": 574, "text": "Example 2:" }, { "code": null, "e": 827, "s": 585, "text": "Input:\nN = 5\nLinkedList: 10->5->100->5\nOutput: -1\nExplanation: In the second example, there\nare 4 nodes in the linked list and we\nneed to find 5th from the end. Since 'n'\nis more than the number of nodes in the\nlinked list, the output is -1." }, { "code": null, "e": 1018, "s": 827, "text": "Your Task:\nThe task is to complete the function getNthFromLast() which takes two arguments: reference to head and N and you need to return Nth from the end or -1 in case node doesn't exist.." }, { "code": null, "e": 1058, "s": 1018, "text": "Note:\nTry to solve in single traversal." }, { "code": null, "e": 1122, "s": 1058, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1163, "s": 1122, "text": "Constraints:\n1 <= L <= 106\n1 <= N <= 106" }, { "code": null, "e": 1165, "s": 1163, "text": "0" }, { "code": null, "e": 1196, "s": 1165, "text": "2019sushilkumarkori9 hours ago" }, { "code": null, "e": 1638, "s": 1196, "text": "int getNthFromLast(Node *head, int n)\n{\n // Your code here\n int l=0;\n Node* temp = head;\n while(temp!=NULL){\n l++;\n temp=temp->next;\n }\n if(n>l){\n return -1;\n }\n temp=head;\n int i=0;\n while(temp!=NULL){\n i++;\n if(i == (l-n)+1){\n return temp->data;\n }\n temp=temp->next;\n }\n return -1;\n}" }, { "code": null, "e": 1640, "s": 1638, "text": "0" }, { "code": null, "e": 1664, "s": 1640, "text": "jimmynandwana5 days ago" }, { "code": null, "e": 2028, "s": 1664, "text": "int getNthFromLast(Node head, int n) { // Your code here Node low = head; Node high = head; for(int i = 1 ; i<n;i++){ if(high.next != null){ high = high.next; } else{ return -1; } } while(high != null && high.next != null){ low = low.next; high = high.next; } return low.data; }" }, { "code": null, "e": 2031, "s": 2028, "text": "+1" }, { "code": null, "e": 2055, "s": 2031, "text": "bipulharsh1235 days ago" }, { "code": null, "e": 2067, "s": 2055, "text": "Time : O(N)" }, { "code": null, "e": 2079, "s": 2067, "text": "Space: O(1)" }, { "code": null, "e": 2511, "s": 2081, "text": "int getNthFromLast(Node *head, int n){ // Your code here Node *ptr=NULL; Node *startBatch=head; int count=0; while(head){ count = (count+1)%n; if(count%n==0){ ptr = startBatch; startBatch = head->next; } head = head->next; } if(!ptr) return -1; while(count--){ ptr = ptr->next; } return ptr->data;}" }, { "code": null, "e": 2513, "s": 2511, "text": "0" }, { "code": null, "e": 2534, "s": 2513, "text": "sailendrad1 week ago" }, { "code": null, "e": 2863, "s": 2534, "text": " int getNthFromLast(Node head, int n) { // Your code here Node fast = head; Node slow = head; while(n > 1){ fast = fast.next; if(fast == null)return -1; n--; } while(fast.next !=null){ fast= fast.next; slow= slow.next; } return slow.data; }" }, { "code": null, "e": 2865, "s": 2863, "text": "0" }, { "code": null, "e": 2889, "s": 2865, "text": "sudeepgarg6711 week ago" }, { "code": null, "e": 3248, "s": 2889, "text": "int getNthFromLast(Node *head, int n){ Node *temp = head; int count = 0; while(temp!=NULL){ count++; temp = temp->next; } if(n>count){ return -1; } int start = 0; Node *temp2 = head; while(start!=count-n){ temp2 = temp2->next; start++; } return temp2->data;}" }, { "code": null, "e": 3250, "s": 3248, "text": "0" }, { "code": null, "e": 3271, "s": 3250, "text": "nischithtn1 week ago" }, { "code": null, "e": 3607, "s": 3275, "text": "int getNthFromLast(Node head, int n) { // Your code here LinkedList<Integer> l = new LinkedList<Integer>(); while(head!=null){ l.add(head.data); head=head.next; } int p=l.size(); int k =p-n; int z=-1; if(n<=p){ z=l.get(k); }else{ z=-1; } return z; }" }, { "code": null, "e": 3609, "s": 3607, "text": "0" }, { "code": null, "e": 3632, "s": 3609, "text": "akaashhardha1 week ago" }, { "code": null, "e": 3976, "s": 3632, "text": "int getNthFromLast(struct Node *head, int n){ int count = 0; struct Node *temp = head; while(temp != NULL){ count++; temp = temp->next; } struct Node *temp2 = head; if(n <= count){ for(int i = 1; i <= count - n ; i++) temp2 = temp2->next; return temp2->data; } else return -1;}" }, { "code": null, "e": 3981, "s": 3978, "text": "+2" }, { "code": null, "e": 3997, "s": 3981, "text": "nimox1 week ago" }, { "code": null, "e": 4330, "s": 3997, "text": "int getNthFromLast(Node head, int n)\n {\n \t// Your code here\t\n \tNode temp = head;\n \tNode ans = head;\n \tint count = 0;\n \t\n \twhile(temp!=null)\n \t{\n \t if(count>=n) ans=ans.next;\n \t \n \t temp = temp.next;\n \t count++;\n \t}\n \t\n \tif(n>count) return -1;\n \treturn ans.data;\n }" }, { "code": null, "e": 4333, "s": 4330, "text": "+1" }, { "code": null, "e": 4362, "s": 4333, "text": "shahabuddinbravo401 week ago" }, { "code": null, "e": 4820, "s": 4362, "text": "int getNthFromLast(Node *head, int n){ Node *ptr=head; int count=0; while(ptr!=NULL) { ptr=ptr->next; count++; } if(count-n >= 0){ Node *ptr1=head; int index=1; while(ptr1!=NULL){ if(index==(count-n)+1){ return ptr1->data; } index++; ptr1=ptr1->next; } } else{ return -1; }}" }, { "code": null, "e": 4824, "s": 4822, "text": "0" }, { "code": null, "e": 4848, "s": 4824, "text": "vaibhav9812031 week ago" }, { "code": null, "e": 4854, "s": 4848, "text": "JAVA " }, { "code": null, "e": 5269, "s": 4856, "text": " int getNthFromLast(Node head, int n) { // Your code here int count = 1; Node n1 = head; while(n1.next!=null){ n1 = n1.next; count++; } int newIndex = count-n; if(count == n) return head.data; if(n > count) return -1; n1 = head; count = 1; while(n1.next!=null){ if(count == newIndex) break; n1 = n1.next; count++;" }, { "code": null, "e": 5328, "s": 5269, "text": " } Node result = n1.next; return result.data; }" }, { "code": null, "e": 5474, "s": 5328, "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": 5510, "s": 5474, "text": " Login to access your submissions. " }, { "code": null, "e": 5520, "s": 5510, "text": "\nProblem\n" }, { "code": null, "e": 5530, "s": 5520, "text": "\nContest\n" }, { "code": null, "e": 5593, "s": 5530, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5741, "s": 5593, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5949, "s": 5741, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6055, "s": 5949, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Java Interface | Practice | GeeksforGeeks
Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body). Given an inteface in1 which includes a method display which takes an integer as input . interface in1 { void display(int p); } Task is to write a class testClass which implements interface in1 and has a method named display which takes an integer as input and total number of prime numbers between 2 and integer k (including it). Main function in written for you in the editor. Input: The first line will contain an integer T (number of test cases). Each test case consists of an integer n. Output: Print total number of prime numbers between 2 and the given number ( including them ). Constraints: 1 < = T < = 1000 2<= n <= 104 Example: Input: 2 13 19 Output: 6 8 0 nikhilkalkalbin 9 hours i think my code is right way to solve this problem here is a APPROCH TO solve this not execetly ============================== import java.util.*;class HelloWorld { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); int count=0; for(int i=2;i<a;i++){ if(checkprime(i)){ count++; } }System.out.print(count); } public static boolean checkprime(int a){ int t=a/2; for(int i=2;i<t;i++){ if(a%i==0){ return false; } }return true; }} 0 sknurhassan041 week ago class testClass implements in1{ boolean isPrime(int num) { for(int i = 2; i<=Math.sqrt(num); i++) { if(num%i==0) { return false; } } return true; } public void display(int k) { // Add your code here. int count =0; for(int n =2; n<=k;n++) { if(isPrime(n)) { count++; } } System.out.println(count); }} +1 mdsaif04052 months ago boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } public void display(int n) { int prime=0; for (int i = 2; i <= n; i++) { if( isPrime(i) ){ prime++; } } System.out.println(prime); } +2 badgujarsachin834 months ago class testClass implements in1 { boolean isprime(int n){ if(n==1||n==0){ return false; } for(int i=2;i<=Math.sqrt(n);i++){ if(n%i==0){ return false; } } return true; } public void display(int k) { // Add your code here. int count=0; for(int i=2;i<=k;i++){ if(isprime(i)){ count++; } } System.out.println(count); } } 0 ramyakovi99 This comment was deleted. -1 Samyak Jain10 months ago Samyak Jain class testClass implements in1{ int sum=0; int x,i,j; public void display(int k) { for(x=2;x<=k;x++){ //for numbers between 2 and 13 for(i=2;i<x;i++){ for="" dividing="" to="" check="" the="" number="" is="" prime="" if(x%i="=0){" break;="" }="" }="" if(i="=x){" sum++;="" }="" }="" system.out.println(sum);="" add="" your="" code="" here.="" }="" }=""> -1 Shashank Agarwal2 years ago Shashank Agarwal class testClass implements in1{ public void display(int k) { // Add your code here. int flag=1; int count=0; for(int i=3;i<=k;i=i+2) { for(int j=2;j<=i/2;j++) { if(i%j==0) { flag=0; break; } else{ flag=1; } } if(flag==1) { count++; } } count=count+1; System.out.println(count); }}best solution -1 Krishna Pavan2 years ago Krishna Pavan Took just 1.10 seconds. public void display(int k) { // Add your code here. int total = 1; int count = 0; for(int i = 2; i <= k; i++) { for(int j = 2; j < i; j++) { if(i % j == 0) { count = 0; break; } else { count = 1; } } if(count == 1) { total++; } } System.out.println(total); } -1 Shreyash Atmaram Yewale2 years ago Shreyash Atmaram Yewale Best Solution for the problem.// Add your code here. boolean isPrime=true; int cnt=0; int i=2; while(i<=k) { for(int j=2;j<=i/2;j++) { if(i%j==0) { isPrime=false; cnt++; break; } } i++; } int arr[]=new int[k-1]; int p=0; for(int c=2;c<=k;c++) { arr[p]=c; p++; } int ans=arr.length-cnt++; System.out.println(ans); } -1 Saransh2 years ago Saransh class testClass implements in1{ boolean isPrime(int n) { for(int i = 2; i <= Math.sqrt(n); i++) { if(n%i == 0) return false; } return true; } public void display(int k) { int count = 0; for(int i = 2; i <= k; i++) { if(isPrime(i)) count++; } System.out.println(count); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 383, "s": 226, "text": "Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body). " }, { "code": null, "e": 471, "s": 383, "text": "Given an inteface in1 which includes a method display which takes an integer as input ." }, { "code": null, "e": 514, "s": 471, "text": "interface in1\n{\n void display(int p);\n}" }, { "code": null, "e": 765, "s": 514, "text": "Task is to write a class testClass which implements interface in1 and has a method named display which takes an integer as input and total number of prime numbers between 2 and integer k (including it). Main function in written for you in the editor." }, { "code": null, "e": 879, "s": 765, "text": "Input: \nThe first line will contain an integer T (number of test cases). Each test case consists of an integer n." }, { "code": null, "e": 975, "s": 879, "text": "Output: \nPrint total number of prime numbers between 2 and the given number ( including them )." }, { "code": null, "e": 1019, "s": 975, "text": "Constraints: \n1 < = T < = 1000\n2<= n <= 104" }, { "code": null, "e": 1043, "s": 1019, "text": "Example:\nInput:\n2\n13\n19" }, { "code": null, "e": 1055, "s": 1043, "text": "Output:\n6\n8" }, { "code": null, "e": 1057, "s": 1055, "text": "0" }, { "code": null, "e": 1081, "s": 1057, "text": "nikhilkalkalbin 9 hours" }, { "code": null, "e": 1182, "s": 1081, "text": "i think my code is right way to solve this problem here is a APPROCH TO solve this not execetly" }, { "code": null, "e": 1215, "s": 1184, "text": "==============================" }, { "code": null, "e": 1685, "s": 1215, "text": "import java.util.*;class HelloWorld { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); int count=0; for(int i=2;i<a;i++){ if(checkprime(i)){ count++; } }System.out.print(count); } public static boolean checkprime(int a){ int t=a/2; for(int i=2;i<t;i++){ if(a%i==0){ return false; } }return true; }}" }, { "code": null, "e": 1687, "s": 1685, "text": "0" }, { "code": null, "e": 1711, "s": 1687, "text": "sknurhassan041 week ago" }, { "code": null, "e": 2267, "s": 1711, "text": "class testClass implements in1{ boolean isPrime(int num) { for(int i = 2; i<=Math.sqrt(num); i++) { if(num%i==0) { return false; } } return true; } public void display(int k) { // Add your code here. int count =0; for(int n =2; n<=k;n++) { if(isPrime(n)) { count++; } } System.out.println(count); }}" }, { "code": null, "e": 2270, "s": 2267, "text": "+1" }, { "code": null, "e": 2293, "s": 2270, "text": "mdsaif04052 months ago" }, { "code": null, "e": 2771, "s": 2293, "text": " boolean isPrime(int num) {\n if (num <= 1) {\n return false;\n }\n for (int i = 2; i <= Math.sqrt(num); i++) {\n if (num % i == 0) {\n return false;\n }\n }\n return true;\n }\n public void display(int n)\n { \n int prime=0;\n for (int i = 2; i <= n; i++) {\n if( isPrime(i) ){\n prime++;\n }\n }\n System.out.println(prime); \n }" }, { "code": null, "e": 2774, "s": 2771, "text": "+2" }, { "code": null, "e": 2803, "s": 2774, "text": "badgujarsachin834 months ago" }, { "code": null, "e": 3314, "s": 2803, "text": "class testClass implements in1\n{\n boolean isprime(int n){\n if(n==1||n==0){\n return false;\n }\n for(int i=2;i<=Math.sqrt(n);i++){\n if(n%i==0){\n return false;\n }\n }\n return true;\n }\n public void display(int k)\n { \n // Add your code here.\n int count=0;\n for(int i=2;i<=k;i++){\n if(isprime(i)){\n count++;\n }\n }\n System.out.println(count);\n }\n}" }, { "code": null, "e": 3316, "s": 3314, "text": "0" }, { "code": null, "e": 3328, "s": 3316, "text": "ramyakovi99" }, { "code": null, "e": 3354, "s": 3328, "text": "This comment was deleted." }, { "code": null, "e": 3357, "s": 3354, "text": "-1" }, { "code": null, "e": 3382, "s": 3357, "text": "Samyak Jain10 months ago" }, { "code": null, "e": 3394, "s": 3382, "text": "Samyak Jain" }, { "code": null, "e": 3426, "s": 3394, "text": "class testClass implements in1{" }, { "code": null, "e": 3455, "s": 3426, "text": " int sum=0; int x,i,j;" }, { "code": null, "e": 3791, "s": 3455, "text": " public void display(int k) { for(x=2;x<=k;x++){ //for numbers between 2 and 13 for(i=2;i<x;i++){ for=\"\" dividing=\"\" to=\"\" check=\"\" the=\"\" number=\"\" is=\"\" prime=\"\" if(x%i=\"=0){\" break;=\"\" }=\"\" }=\"\" if(i=\"=x){\" sum++;=\"\" }=\"\" }=\"\" system.out.println(sum);=\"\" add=\"\" your=\"\" code=\"\" here.=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 3794, "s": 3791, "text": "-1" }, { "code": null, "e": 3822, "s": 3794, "text": "Shashank Agarwal2 years ago" }, { "code": null, "e": 3839, "s": 3822, "text": "Shashank Agarwal" }, { "code": null, "e": 4413, "s": 3839, "text": "class testClass implements in1{ public void display(int k) { // Add your code here. int flag=1; int count=0; for(int i=3;i<=k;i=i+2) { for(int j=2;j<=i/2;j++) { if(i%j==0) { flag=0; break; } else{ flag=1; } } if(flag==1) { count++; } } count=count+1; System.out.println(count); }}best solution" }, { "code": null, "e": 4416, "s": 4413, "text": "-1" }, { "code": null, "e": 4441, "s": 4416, "text": "Krishna Pavan2 years ago" }, { "code": null, "e": 4455, "s": 4441, "text": "Krishna Pavan" }, { "code": null, "e": 4479, "s": 4455, "text": "Took just 1.10 seconds." }, { "code": null, "e": 5030, "s": 4479, "text": "public void display(int k) { // Add your code here. int total = 1; int count = 0; for(int i = 2; i <= k; i++) { for(int j = 2; j < i; j++) { if(i % j == 0) { count = 0; break; } else { count = 1; } } if(count == 1) { total++; } } System.out.println(total); }" }, { "code": null, "e": 5033, "s": 5030, "text": "-1" }, { "code": null, "e": 5068, "s": 5033, "text": "Shreyash Atmaram Yewale2 years ago" }, { "code": null, "e": 5092, "s": 5068, "text": "Shreyash Atmaram Yewale" }, { "code": null, "e": 5459, "s": 5092, "text": "Best Solution for the problem.// Add your code here. boolean isPrime=true; int cnt=0; int i=2; while(i<=k) { for(int j=2;j<=i/2;j++) { if(i%j==0) { isPrime=false; cnt++; break; } } i++;" }, { "code": null, "e": 5600, "s": 5459, "text": " } int arr[]=new int[k-1]; int p=0; for(int c=2;c<=k;c++) { arr[p]=c; p++; }" }, { "code": null, "e": 5671, "s": 5600, "text": " int ans=arr.length-cnt++; System.out.println(ans); }" }, { "code": null, "e": 5674, "s": 5671, "text": "-1" }, { "code": null, "e": 5693, "s": 5674, "text": "Saransh2 years ago" }, { "code": null, "e": 5701, "s": 5693, "text": "Saransh" }, { "code": null, "e": 6094, "s": 5701, "text": "class testClass implements in1{ boolean isPrime(int n) { for(int i = 2; i <= Math.sqrt(n); i++) { if(n%i == 0) return false; } return true; } public void display(int k) { int count = 0; for(int i = 2; i <= k; i++) { if(isPrime(i)) count++; } System.out.println(count); }" }, { "code": null, "e": 6240, "s": 6094, "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": 6276, "s": 6240, "text": " Login to access your submissions. " }, { "code": null, "e": 6286, "s": 6276, "text": "\nProblem\n" }, { "code": null, "e": 6296, "s": 6286, "text": "\nContest\n" }, { "code": null, "e": 6359, "s": 6296, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6507, "s": 6359, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6715, "s": 6507, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6821, "s": 6715, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Biopython - Motif Objects
A sequence motif is a nucleotide or amino-acid sequence pattern. Sequence motifs are formed by three-dimensional arrangement of amino acids which may not be adjacent. Biopython provides a separate module, Bio.motifs to access the functionalities of sequence motif as specified below − from Bio import motifs Let us create a simple DNA motif sequence using the below command − >>> from Bio import motifs >>> from Bio.Seq import Seq >>> DNA_motif = [ Seq("AGCT"), ... Seq("TCGA"), ... Seq("AACT"), ... ] >>> seq = motifs.create(DNA_motif) >>> print(seq) AGCT TCGA AACT To count the sequence values, use the below command − >>> print(seq.counts) 0 1 2 3 A: 2.00 1.00 0.00 1.00 C: 0.00 1.00 2.00 0.00 G: 0.00 1.00 1.00 0.00 T: 1.00 0.00 0.00 2.00 Use the following code to count ‘A’ in the sequence − >>> seq.counts["A", :] (2, 1, 0, 1) If you want to access the columns of counts, use the below command − >>> seq.counts[:, 3] {'A': 1, 'C': 0, 'T': 2, 'G': 0} We shall now discuss how to create a Sequence Logo. Consider the below sequence − AGCTTACG ATCGTACC TTCCGAAT GGTACGTA AAGCTTGG You can create your own logo using the following link − http://weblogo.berkeley.edu/ Add the above sequence and create a new logo and save the image named seq.png in your biopython folder. seq.png After creating the image, now run the following command − >>> seq.weblogo("seq.png") This DNA sequence motif is represented as a sequence logo for the LexA-binding motif. JASPAR is one of the most popular databases. It provides facilities of any of the motif formats for reading, writing and scanning sequences. It stores meta-information for each motif. The module Bio.motifs contains a specialized class jaspar.Motif to represent meta-information attributes. It has the following notable attributes types − matrix_id − Unique JASPAR motif ID name − The name of the motif tf_family − The family of motif, e.g. ’Helix-Loop-Helix’ data_type − the type of data used in motif. Let us create a JASPAR sites format named in sample.sites in biopython folder. It is defined below − sample.sites >MA0001 ARNT 1 AACGTGatgtccta >MA0001 ARNT 2 CAGGTGggatgtac >MA0001 ARNT 3 TACGTAgctcatgc >MA0001 ARNT 4 AACGTGacagcgct >MA0001 ARNT 5 CACGTGcacgtcgt >MA0001 ARNT 6 cggcctCGCGTGc In the above file, we have created motif instances. Now, let us create a motif object from the above instances − >>> from Bio import motifs >>> with open("sample.sites") as handle: ... data = motifs.read(handle,"sites") ... >>> print(data) TF name None Matrix ID None Matrix: 0 1 2 3 4 5 A: 2.00 5.00 0.00 0.00 0.00 1.00 C: 3.00 0.00 5.00 0.00 0.00 0.00 G: 0.00 1.00 1.00 6.00 0.00 5.00 T: 1.00 0.00 0.00 0.00 6.00 0.00 Here, data reads all the motif instances from sample.sites file. To print all the instances from data, use the below command − >>> for instance in data.instances: ... print(instance) ... AACGTG CAGGTG TACGTA AACGTG CACGTG CGCGTG Use the below command to count all the values − >>> print(data.counts) 0 1 2 3 4 5 A: 2.00 5.00 0.00 0.00 0.00 1.00 C: 3.00 0.00 5.00 0.00 0.00 0.00 G: 0.00 1.00 1.00 6.00 0.00 5.00 T: 1.00 0.00 0.00 0.00 6.00 0.00 >>> Print Add Notes Bookmark this page
[ { "code": null, "e": 2391, "s": 2106, "text": "A sequence motif is a nucleotide or amino-acid sequence pattern. Sequence motifs are formed by three-dimensional arrangement of amino acids which may not be adjacent. Biopython provides a separate module, Bio.motifs to access the functionalities of sequence motif as specified below −" }, { "code": null, "e": 2415, "s": 2391, "text": "from Bio import motifs\n" }, { "code": null, "e": 2483, "s": 2415, "text": "Let us create a simple DNA motif sequence using the below command −" }, { "code": null, "e": 2721, "s": 2483, "text": ">>> from Bio import motifs \n>>> from Bio.Seq import Seq \n>>> DNA_motif = [ Seq(\"AGCT\"), \n... Seq(\"TCGA\"), \n... Seq(\"AACT\"), \n... ] \n>>> seq = motifs.create(DNA_motif) \n>>> print(seq) AGCT TCGA AACT" }, { "code": null, "e": 2775, "s": 2721, "text": "To count the sequence values, use the below command −" }, { "code": null, "e": 2972, "s": 2775, "text": ">>> print(seq.counts) \n 0 1 2 3 \nA: 2.00 1.00 0.00 1.00 \nC: 0.00 1.00 2.00 0.00 \nG: 0.00 1.00 1.00 0.00 \nT: 1.00 0.00 0.00 2.00" }, { "code": null, "e": 3026, "s": 2972, "text": "Use the following code to count ‘A’ in the sequence −" }, { "code": null, "e": 3063, "s": 3026, "text": ">>> seq.counts[\"A\", :] \n(2, 1, 0, 1)" }, { "code": null, "e": 3132, "s": 3063, "text": "If you want to access the columns of counts, use the below command −" }, { "code": null, "e": 3187, "s": 3132, "text": ">>> seq.counts[:, 3] \n{'A': 1, 'C': 0, 'T': 2, 'G': 0}" }, { "code": null, "e": 3239, "s": 3187, "text": "We shall now discuss how to create a Sequence Logo." }, { "code": null, "e": 3269, "s": 3239, "text": "Consider the below sequence −" }, { "code": null, "e": 3319, "s": 3269, "text": "AGCTTACG \nATCGTACC \nTTCCGAAT \nGGTACGTA \nAAGCTTGG\n" }, { "code": null, "e": 3404, "s": 3319, "text": "You can create your own logo using the following link − http://weblogo.berkeley.edu/" }, { "code": null, "e": 3508, "s": 3404, "text": "Add the above sequence and create a new logo and save the image named seq.png in your biopython folder." }, { "code": null, "e": 3517, "s": 3508, "text": "seq.png\n" }, { "code": null, "e": 3575, "s": 3517, "text": "After creating the image, now run the following command −" }, { "code": null, "e": 3603, "s": 3575, "text": ">>> seq.weblogo(\"seq.png\")\n" }, { "code": null, "e": 3689, "s": 3603, "text": "This DNA sequence motif is represented as a sequence logo for the LexA-binding motif." }, { "code": null, "e": 3979, "s": 3689, "text": "JASPAR is one of the most popular databases. It provides facilities of any of the motif formats for reading, writing and scanning sequences. It stores meta-information for each motif. The module Bio.motifs contains a specialized class jaspar.Motif to represent meta-information attributes." }, { "code": null, "e": 4027, "s": 3979, "text": "It has the following notable attributes types −" }, { "code": null, "e": 4062, "s": 4027, "text": "matrix_id − Unique JASPAR motif ID" }, { "code": null, "e": 4091, "s": 4062, "text": "name − The name of the motif" }, { "code": null, "e": 4148, "s": 4091, "text": "tf_family − The family of motif, e.g. ’Helix-Loop-Helix’" }, { "code": null, "e": 4192, "s": 4148, "text": "data_type − the type of data used in motif." }, { "code": null, "e": 4293, "s": 4192, "text": "Let us create a JASPAR sites format named in sample.sites in biopython folder. It is defined below −" }, { "code": null, "e": 4496, "s": 4293, "text": "sample.sites\n>MA0001 ARNT 1 \nAACGTGatgtccta \n>MA0001 ARNT 2 \nCAGGTGggatgtac \n>MA0001 ARNT 3 \nTACGTAgctcatgc \n>MA0001 ARNT 4 \nAACGTGacagcgct \n>MA0001 ARNT 5 \nCACGTGcacgtcgt \n>MA0001 ARNT 6 \ncggcctCGCGTGc" }, { "code": null, "e": 4609, "s": 4496, "text": "In the above file, we have created motif instances. Now, let us create a motif object from the above instances −" }, { "code": null, "e": 5053, "s": 4609, "text": ">>> from Bio import motifs \n>>> with open(\"sample.sites\") as handle: \n... data = motifs.read(handle,\"sites\") \n... \n>>> print(data) \nTF name None \nMatrix ID None \nMatrix:\n 0 1 2 3 4 5 \nA: 2.00 5.00 0.00 0.00 0.00 1.00 \nC: 3.00 0.00 5.00 0.00 0.00 0.00 \nG: 0.00 1.00 1.00 6.00 0.00 5.00 \nT: 1.00 0.00 0.00 0.00 6.00 0.00" }, { "code": null, "e": 5118, "s": 5053, "text": "Here, data reads all the motif instances from sample.sites file." }, { "code": null, "e": 5180, "s": 5118, "text": "To print all the instances from data, use the below command −" }, { "code": null, "e": 5293, "s": 5180, "text": ">>> for instance in data.instances: \n... print(instance) \n... \nAACGTG \nCAGGTG \nTACGTA \nAACGTG \nCACGTG \nCGCGTG" }, { "code": null, "e": 5341, "s": 5293, "text": "Use the below command to count all the values −" }, { "code": null, "e": 5642, "s": 5341, "text": ">>> print(data.counts)\n 0 1 2 3 4 5 \nA: 2.00 5.00 0.00 0.00 0.00 1.00 \nC: 3.00 0.00 5.00 0.00 0.00 0.00 \nG: 0.00 1.00 1.00 6.00 0.00 5.00 \nT: 1.00 0.00 0.00 0.00 6.00 0.00\n>>>" }, { "code": null, "e": 5649, "s": 5642, "text": " Print" }, { "code": null, "e": 5660, "s": 5649, "text": " Add Notes" } ]
Compare array of objects - JavaScript
We have two arrays of objects like these − const blocks = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, ] const containers = [ { block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 3 } }, ] We are required to write a function that checks each object of blocks array with the block key of each object of containers array and see if there exists any id in blocks array that is not present in the containers array. If so, we return false, otherwise we return true. Let’s write the code − const blocks = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, ] const containers = [ { block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 3 } }, ] const checkProperty = (first, second) => { const findInContainers = id => { for(let i = 0; i < second.length; i++){ if(second[i].block.id === id){ return true; }; }; return false; }; for(let i = 0; i < first.length; i++){ if(!findInContainers(first[i].id)){ return false; }; }; return true; }; console.log(checkProperty(blocks, containers)); Following is the output in the console − false
[ { "code": null, "e": 1105, "s": 1062, "text": "We have two arrays of objects like these −" }, { "code": null, "e": 1278, "s": 1105, "text": "const blocks = [\n { id: 1 },\n { id: 2 },\n { id: 3 },\n { id: 4 },\n]\nconst containers = [\n { block: { id: 1 } },\n { block: { id: 2 } },\n { block: { id: 3 } },\n]" }, { "code": null, "e": 1550, "s": 1278, "text": "We are required to write a function that checks each object of blocks array with the block key of each object of containers array and see if there exists any id in blocks array that is not present in the containers array. If so, we return false, otherwise we return true." }, { "code": null, "e": 1573, "s": 1550, "text": "Let’s write the code −" }, { "code": null, "e": 2172, "s": 1573, "text": "const blocks = [\n { id: 1 },\n { id: 2 },\n { id: 3 },\n { id: 4 },\n]\nconst containers = [\n { block: { id: 1 } },\n { block: { id: 2 } },\n { block: { id: 3 } },\n]\nconst checkProperty = (first, second) => {\n const findInContainers = id => {\n for(let i = 0; i < second.length; i++){\n if(second[i].block.id === id){\n return true;\n };\n };\n return false;\n };\n for(let i = 0; i < first.length; i++){\n if(!findInContainers(first[i].id)){\n return false;\n };\n };\n return true;\n};\nconsole.log(checkProperty(blocks, containers));" }, { "code": null, "e": 2213, "s": 2172, "text": "Following is the output in the console −" }, { "code": null, "e": 2219, "s": 2213, "text": "false" } ]
C++ Program to Implement Bucket Sort
In the Bucket Sorting technique, the data items are distributed of a set of buckets. Each bucket can hold similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that all elements are gathered into the main list to get the sorted form. Time Complexity: O(n + k) for best case and average case and O(n2 ) for worst case. Time Complexity: O(n + k) for best case and average case and O(n2 ) for worst case. Space Complexity: O(nk) for worst case Space Complexity: O(nk) for worst case Input − A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Output − Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79 Input: An array of data, and the total number in the array Output: The sorted Array Begin for i := 0 to size-1 do insert array[i] into the bucket index (size * array[i]) done for i := 0 to size-1 do sort bucket[i] done for i := 0 to size -1 do gather items of bucket[i] and put in array done End #include<iostream> #include<vector> #include<algorithm> using namespace std; void display(float *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void bucketSort(float *array, int size) { vector<float> bucket[size]; for(int i = 0; i<size; i++) { //put elements into different buckets bucket[int(size*array[i])].push_back(array[i]); } for(int i = 0; i<size; i++) { sort(bucket[i].begin(), bucket[i].end()); //sort individual vectors } int index = 0; for(int i = 0; i<size; i++) { while(!bucket[i].empty()) { array[index++] = *(bucket[i].begin()); bucket[i].erase(bucket[i].begin()); } } } int main() { int n; cout << "Enter the number of elements: "; cin >> n; float arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl; for(int i = 0; i<n; i++) { cin >> arr[i]; } cout << "Array before Sorting: "; display(arr, n); bucketSort(arr, n); cout << "Array after Sorting: "; display(arr, n); } Enter the number of elements: 10 Enter elements: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69 Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79
[ { "code": null, "e": 1345, "s": 1062, "text": "In the Bucket Sorting technique, the data items are distributed of a set of buckets. Each bucket can hold similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that all elements are gathered into the main list to get the sorted form." }, { "code": null, "e": 1429, "s": 1345, "text": "Time Complexity: O(n + k) for best case and average case and O(n2 ) for worst case." }, { "code": null, "e": 1513, "s": 1429, "text": "Time Complexity: O(n + k) for best case and average case and O(n2 ) for worst case." }, { "code": null, "e": 1552, "s": 1513, "text": "Space Complexity: O(nk) for worst case" }, { "code": null, "e": 1591, "s": 1552, "text": "Space Complexity: O(nk) for worst case" }, { "code": null, "e": 1754, "s": 1591, "text": "Input − A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\nOutput − Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79" }, { "code": null, "e": 1813, "s": 1754, "text": "Input: An array of data, and the total number in the array" }, { "code": null, "e": 1838, "s": 1813, "text": "Output: The sorted Array" }, { "code": null, "e": 2086, "s": 1838, "text": "Begin\n for i := 0 to size-1 do\n insert array[i] into the bucket index (size * array[i])\n done\n for i := 0 to size-1 do\n sort bucket[i]\n done\n for i := 0 to size -1 do\n gather items of bucket[i] and put in array\n done\nEnd" }, { "code": null, "e": 3189, "s": 2086, "text": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nvoid display(float *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\nvoid bucketSort(float *array, int size) {\n vector<float> bucket[size];\n for(int i = 0; i<size; i++) { //put elements into different buckets\n bucket[int(size*array[i])].push_back(array[i]);\n }\n for(int i = 0; i<size; i++) {\n sort(bucket[i].begin(), bucket[i].end()); //sort individual vectors\n }\n int index = 0;\n for(int i = 0; i<size; i++) {\n while(!bucket[i].empty()) {\n array[index++] = *(bucket[i].begin());\n bucket[i].erase(bucket[i].begin());\n }\n }\n}\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n float arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n cout << \"Array before Sorting: \";\n display(arr, n);\n bucketSort(arr, n);\n cout << \"Array after Sorting: \";\n display(arr, n);\n}" }, { "code": null, "e": 3431, "s": 3189, "text": "Enter the number of elements: 10\nEnter elements:\n0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\nArray before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01\n0.69\nArray after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69\n0.79" } ]
6 Julia Frameworks to Create Desktop GUI’s and Web Apps | by Logan Kilpatrick | Towards Data Science
Julia is used for a lot of deeply technical applications like Machine Learning and Data Science. But as a general-purpose programming language, Julia can also be used for things like building websites and interactive visualizations. In this article, we will go over 5 Julia packages that can be used to create desktop GUI’s or web applications. Genie.jl is a pure Julia web framework based on Django. From the Genie website: Genie Framework includes all you need to quickly build production ready web applications with Julia Lang. Develop Julia backends, create beautiful web UIs, integrate with databases and set up high-performance web services and APIs. Like Django, Genie is not just a stand alone-package, it is an entire ecosystem! Let’s look at a basic hello world example with Genie: # Genie Hello World!using Genieroute("/helloworld") do "Hello and welcome to Genie!"end# Powerful high-performance HTML view templatesusing Genie.Renderer.Htmlroute("/html") do h1("Welcome to Genie!") |> htmlend# JSON rendering built inusing Genie.Renderer.Jsonroute("/json") do (:greeting => "Welcome to Genie!") |> jsonend# Start the app!up(8888) As you can see, Genie follows a similar design pattern to Django and comes with features like a web server, templating engine, cookies, encryption, authentication, a routing engine, backend views written in Julia, and much more! If you want to build modern web applications and are familiar with Django, Genie is the right place to start! You can find out more here: https://genieframework.com For a comprehensive video tutorial on Genie, check out: Gtk.jl is a Julia package built on top of the very popular GTK windowing toolkit. You can find the getting started manual here: https://juliagraphics.github.io/Gtk.jl/latest/manual/gettingStarted/ Let’s look at a simple example: using Gtkwin = GtkWindow("My First Gtk.jl Program", 400, 200)b = GtkButton("Click Me")push!(win,b)showall(win) First, we set the name of the window and the dimensions. Then, we create a button object with a specific text label and push it into the app. Last, we display the app by calling showall. Gtk.jl has been used to build some very cool applications. I highly suggest checking out this video: Makie is one of the most loved visualization packages in the Julia ecosystem. There is an incredible depth to what you can build. Makie allows you to build interactive visualizations that run on the GPU and can also be run in your browser. The Makie docs also recently went through a large update so the content there is up to date and very helpful: https://makie.juliaplots.org/stable/ I would also suggest checking out https://lazarusa.github.io/BeautifulMakie/ which is a gallery of lots of really nice animations built using Makie. Blink.jl is the Julia wrapper around Electron. It can serve HTML content in a local window, and allows for communication between Julia and the web page. In this way, therefore, Blink can be used as a GUI toolkit for building HTML-based applications for the desktop. I could not think of a better way to re-state this, so the above is a quote from the Blink docs. What makes Blink different from other packages is that you can build HTML-based GUI’s using it. julia> using Blinkjulia> w = Window() # Open a new windowBlink.AtomShell.Window(...)julia> body!(w, "Hello World") # Set the body contentjulia> loadurl(w, "http://julialang.org") # Load a web page We start off by creating the Electron window, then appending in some text to the body tag of the window, and finally, loading a URL in the window. If you run this code locally, you will see that the window changes dynamically as we execute these commands. While I don’t think Blink is widely used, I have had a lot of fun playing around with it on various projects. Dash is a Julia interface to the Dash ecosystem for creating analytic web applications in Julia without requiring JavaScript. This means you can build impressive dashboards like https://covid-county-dash.herokuapp.com and deploy them with ease! You might also want to check out the Dash site https://dash.plotly.com/julia for details on getting started. There is also comprehensive documentation available on Dash.jl: https://github.com/plotly/Dash.jl Right now, the best way to create a desktop app that can be shared and run on computers without Julia installed is to use PackageCompiler. PackageCompiler allows you to take an entire Julia project and compile it to an exe file. This process bundles all of the dependencies together into a single file to make it distributable. I will note that there are currently limitations concerning what you need to do to create an exe. There might be some code re-writing that is required to make it compatible. For a step by step walkthrough on using PackageCompiler, check out: And you can read more about Package Compiler in the docs: https://julialang.github.io/PackageCompiler.jl/stable/apps.html The 5 packages highlighted above are just a small sample of the packages available today in the Julia ecosystem. Below, I will add a semi-exhaustive list of all the visualization packages I can find in case the first 5 did not suit your use-case: Plots.jl, powerful convenience for visualization in JuliaInteract.jl, Interactive widgets to play with your Julia codeStipple.jl, The reactive UI library for interactive data applications with pure Julia.QML.jl, Build Qt5 QML interfaces for Julia programs.ClmGui.jl, Julia wrapper for cimgui Plots.jl, powerful convenience for visualization in Julia Interact.jl, Interactive widgets to play with your Julia code Stipple.jl, The reactive UI library for interactive data applications with pure Julia. QML.jl, Build Qt5 QML interfaces for Julia programs. ClmGui.jl, Julia wrapper for cimgui Am I missing one? Feel free to comment on this article and I will append the package to this list!
[ { "code": null, "e": 510, "s": 165, "text": "Julia is used for a lot of deeply technical applications like Machine Learning and Data Science. But as a general-purpose programming language, Julia can also be used for things like building websites and interactive visualizations. In this article, we will go over 5 Julia packages that can be used to create desktop GUI’s or web applications." }, { "code": null, "e": 590, "s": 510, "text": "Genie.jl is a pure Julia web framework based on Django. From the Genie website:" }, { "code": null, "e": 822, "s": 590, "text": "Genie Framework includes all you need to quickly build production ready web applications with Julia Lang. Develop Julia backends, create beautiful web UIs, integrate with databases and set up high-performance web services and APIs." }, { "code": null, "e": 957, "s": 822, "text": "Like Django, Genie is not just a stand alone-package, it is an entire ecosystem! Let’s look at a basic hello world example with Genie:" }, { "code": null, "e": 1315, "s": 957, "text": "# Genie Hello World!using Genieroute(\"/helloworld\") do \"Hello and welcome to Genie!\"end# Powerful high-performance HTML view templatesusing Genie.Renderer.Htmlroute(\"/html\") do h1(\"Welcome to Genie!\") |> htmlend# JSON rendering built inusing Genie.Renderer.Jsonroute(\"/json\") do (:greeting => \"Welcome to Genie!\") |> jsonend# Start the app!up(8888)" }, { "code": null, "e": 1544, "s": 1315, "text": "As you can see, Genie follows a similar design pattern to Django and comes with features like a web server, templating engine, cookies, encryption, authentication, a routing engine, backend views written in Julia, and much more!" }, { "code": null, "e": 1709, "s": 1544, "text": "If you want to build modern web applications and are familiar with Django, Genie is the right place to start! You can find out more here: https://genieframework.com" }, { "code": null, "e": 1765, "s": 1709, "text": "For a comprehensive video tutorial on Genie, check out:" }, { "code": null, "e": 1962, "s": 1765, "text": "Gtk.jl is a Julia package built on top of the very popular GTK windowing toolkit. You can find the getting started manual here: https://juliagraphics.github.io/Gtk.jl/latest/manual/gettingStarted/" }, { "code": null, "e": 1994, "s": 1962, "text": "Let’s look at a simple example:" }, { "code": null, "e": 2105, "s": 1994, "text": "using Gtkwin = GtkWindow(\"My First Gtk.jl Program\", 400, 200)b = GtkButton(\"Click Me\")push!(win,b)showall(win)" }, { "code": null, "e": 2292, "s": 2105, "text": "First, we set the name of the window and the dimensions. Then, we create a button object with a specific text label and push it into the app. Last, we display the app by calling showall." }, { "code": null, "e": 2393, "s": 2292, "text": "Gtk.jl has been used to build some very cool applications. I highly suggest checking out this video:" }, { "code": null, "e": 2523, "s": 2393, "text": "Makie is one of the most loved visualization packages in the Julia ecosystem. There is an incredible depth to what you can build." }, { "code": null, "e": 2780, "s": 2523, "text": "Makie allows you to build interactive visualizations that run on the GPU and can also be run in your browser. The Makie docs also recently went through a large update so the content there is up to date and very helpful: https://makie.juliaplots.org/stable/" }, { "code": null, "e": 2929, "s": 2780, "text": "I would also suggest checking out https://lazarusa.github.io/BeautifulMakie/ which is a gallery of lots of really nice animations built using Makie." }, { "code": null, "e": 3195, "s": 2929, "text": "Blink.jl is the Julia wrapper around Electron. It can serve HTML content in a local window, and allows for communication between Julia and the web page. In this way, therefore, Blink can be used as a GUI toolkit for building HTML-based applications for the desktop." }, { "code": null, "e": 3388, "s": 3195, "text": "I could not think of a better way to re-state this, so the above is a quote from the Blink docs. What makes Blink different from other packages is that you can build HTML-based GUI’s using it." }, { "code": null, "e": 3585, "s": 3388, "text": "julia> using Blinkjulia> w = Window() # Open a new windowBlink.AtomShell.Window(...)julia> body!(w, \"Hello World\") # Set the body contentjulia> loadurl(w, \"http://julialang.org\") # Load a web page" }, { "code": null, "e": 3841, "s": 3585, "text": "We start off by creating the Electron window, then appending in some text to the body tag of the window, and finally, loading a URL in the window. If you run this code locally, you will see that the window changes dynamically as we execute these commands." }, { "code": null, "e": 3951, "s": 3841, "text": "While I don’t think Blink is widely used, I have had a lot of fun playing around with it on various projects." }, { "code": null, "e": 4196, "s": 3951, "text": "Dash is a Julia interface to the Dash ecosystem for creating analytic web applications in Julia without requiring JavaScript. This means you can build impressive dashboards like https://covid-county-dash.herokuapp.com and deploy them with ease!" }, { "code": null, "e": 4403, "s": 4196, "text": "You might also want to check out the Dash site https://dash.plotly.com/julia for details on getting started. There is also comprehensive documentation available on Dash.jl: https://github.com/plotly/Dash.jl" }, { "code": null, "e": 4731, "s": 4403, "text": "Right now, the best way to create a desktop app that can be shared and run on computers without Julia installed is to use PackageCompiler. PackageCompiler allows you to take an entire Julia project and compile it to an exe file. This process bundles all of the dependencies together into a single file to make it distributable." }, { "code": null, "e": 4973, "s": 4731, "text": "I will note that there are currently limitations concerning what you need to do to create an exe. There might be some code re-writing that is required to make it compatible. For a step by step walkthrough on using PackageCompiler, check out:" }, { "code": null, "e": 5095, "s": 4973, "text": "And you can read more about Package Compiler in the docs: https://julialang.github.io/PackageCompiler.jl/stable/apps.html" }, { "code": null, "e": 5342, "s": 5095, "text": "The 5 packages highlighted above are just a small sample of the packages available today in the Julia ecosystem. Below, I will add a semi-exhaustive list of all the visualization packages I can find in case the first 5 did not suit your use-case:" }, { "code": null, "e": 5634, "s": 5342, "text": "Plots.jl, powerful convenience for visualization in JuliaInteract.jl, Interactive widgets to play with your Julia codeStipple.jl, The reactive UI library for interactive data applications with pure Julia.QML.jl, Build Qt5 QML interfaces for Julia programs.ClmGui.jl, Julia wrapper for cimgui" }, { "code": null, "e": 5692, "s": 5634, "text": "Plots.jl, powerful convenience for visualization in Julia" }, { "code": null, "e": 5754, "s": 5692, "text": "Interact.jl, Interactive widgets to play with your Julia code" }, { "code": null, "e": 5841, "s": 5754, "text": "Stipple.jl, The reactive UI library for interactive data applications with pure Julia." }, { "code": null, "e": 5894, "s": 5841, "text": "QML.jl, Build Qt5 QML interfaces for Julia programs." }, { "code": null, "e": 5930, "s": 5894, "text": "ClmGui.jl, Julia wrapper for cimgui" } ]
Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N) - GeeksforGeeks
04 Aug, 2021 Given N, count all ‘a’ and ‘b’ that satisfy the condition a^3 + b^3 = N. Examples: Input : N = 9 Output : 2 1^3 + 2^3 = 9 2^3 + 1^3 = 9 Input : N = 28 Output : 2 1^3 + 3^3 = 28 3^3 + 1^3 = 28 Note:- (a, b) and (b, a) are to be considered as two different pairs. Asked in : Adobe Implementation: Traverse numbers from 1 to cube root of N. a) Subtract cube of current number from N and check if their difference is a perfect cube or not. i) If perfect cube then increment count. 2- Return count. Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript // C++ program to count pairs whose sum// cubes is N#include<bits/stdc++.h>using namespace std; // Function to count the pairs satisfying// a ^ 3 + b ^ 3 = Nint countPairs(int N){ int count = 0; // Check for each number 1 to cbrt(N) for (int i = 1; i <= cbrt(N); i++) { // Store cube of a number int cb = i*i*i; // Subtract the cube from given N int diff = N - cb; // Check if the difference is also // a perfect cube int cbrtDiff = cbrt(diff); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count;} // Driver programint main(){ // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (int i = 1; i<= 10; i++) cout << "For n = " << i << ", " << countPairs(i) <<" pair exists\n"; return 0;} // Java program to count pairs whose sum// cubes is N class Test{ // method to count the pairs satisfying // a ^ 3 + b ^ 3 = N static int countPairs(int N) { int count = 0; // Check for each number 1 to cbrt(N) for (int i = 1; i <= Math.cbrt(N); i++) { // Store cube of a number int cb = i*i*i; // Subtract the cube from given N int diff = N - cb; // Check if the difference is also // a perfect cube int cbrtDiff = (int) Math.cbrt(diff); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count; } // Driver method public static void main(String args[]) { // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (int i = 1; i<= 10; i++) System.out.println("For n = " + i + ", " + + countPairs(i) + " pair exists"); }} # Python 3 program to count pairs# whose sum cubes is Nimport math # Function to count the pairs# satisfying a ^ 3 + b ^ 3 = Ndef countPairs(N): count = 0 # Check for each number 1 # to cbrt(N) for i in range(1, int(math.pow(N, 1/3) + 1)): # Store cube of a number cb = i * i * i # Subtract the cube from given N diff = N - cb # Check if the difference is also # a perfect cube cbrtDiff = int(math.pow(diff, 1/3)) # If yes, then increment count if (cbrtDiff * cbrtDiff * cbrtDiff == diff): count += 1 # Return count return count # Driver program # Loop to Count no. of pairs satisfying# a ^ 3 + b ^ 3 = i for N = 1 to 10for i in range(1, 11): print('For n = ', i, ', ', countPairs(i), ' pair exists') # This code is contributed by Smitha. // C# program to count pairs whose sum// cubes is N using System;class Test{ // method to count the pairs satisfying // a ^ 3 + b ^ 3 = N static int countPairs(int N) { int count = 0; // Check for each number 1 to cbrt(N) for (int i = 1; i <= Math.Pow(N,(1.0/3.0)); i++) { // Store cube of a number int cb = i*i*i; // Subtract the cube from given N int diff = N - cb; // Check if the difference is also // a perfect cube int cbrtDiff = (int) Math.Pow(diff,(1.0/3.0)); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count; } // Driver method public static void Main() { // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (int i = 1; i<= 10; i++) Console.Write("For n = " + i + ", " + + countPairs(i) + " pair exists"+"\n"); }} <?php// PHP program to count pairs// whose sum cubes is N // Function to count the pairs// satisfying a ^ 3 + b ^ 3 = Nfunction countPairs($N){ $count = 0; // Check for each number // 1 to cbrt(N) for ($i = 1; $i <= (int)pow($N, 1 / 3); $i++) { // Store cube of a number $cb = $i * $i * $i; // Subtract the cube from // given N $diff = ($N - $cb); // Check if the difference is // also a perfect cube $cbrtDiff = (int)pow($diff, 1 / 3); // If yes, then increment count if ($cbrtDiff * $cbrtDiff * $cbrtDiff == $diff) $count++; } // Return count return $count;} // Driver Code // Loop to Count no. of pairs// satisfying a ^ 3 + b ^ 3 = i// for N = 1 to 10for ($i = 1; $i<= 10; $i++) echo "For n = " , $i , ", ", countPairs($i) ," pair exists\n"; // This code is contributed by jit_t?> <script> // Javascript program to count pairs whose sum cubes is N // method to count the pairs satisfying // a ^ 3 + b ^ 3 = N function countPairs(N) { let count = 0; // Check for each number 1 to cbrt(N) for (let i = 1; i <= parseInt(Math.pow(N,(1.0/3.0)), 10); i++) { // Store cube of a number let cb = i*i*i; // Subtract the cube from given N let diff = N - cb; // Check if the difference is also // a perfect cube let cbrtDiff = parseInt(Math.pow(diff,(1.0/3.0)), 10); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count; } // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (let i = 1; i<= 10; i++) document.write("For n = " + i + ", " + countPairs(i) + " pair exists"+"</br>"); </script> Output: For n= 1, 1 pair exists For n= 2, 1 pair exists For n= 3, 0 pair exists For n= 4, 0 pair exists For n= 5, 0 pair exists For n= 6, 0 pair exists For n= 7, 0 pair exists For n= 8, 1 pair exists For n= 9, 2 pair exists For n= 10, 0 pair exists Reference: https://www.careercup.com/question?id=5954491572551680This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Smitha Dinesh Semwal ukasp jit_t Akanksha_Rai divyeshrabadiya07 gabaa406 Adobe maths-cube Mathematical Adobe Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Program for factorial of a number Operators in C / C++ Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Program to find sum of elements in a given array Program for Decimal to Binary Conversion
[ { "code": null, "e": 26563, "s": 26535, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26648, "s": 26563, "text": "Given N, count all ‘a’ and ‘b’ that satisfy the condition a^3 + b^3 = N. Examples: " }, { "code": null, "e": 26760, "s": 26648, "text": "Input : N = 9\nOutput : 2\n1^3 + 2^3 = 9\n2^3 + 1^3 = 9\n\nInput : N = 28\nOutput : 2\n 1^3 + 3^3 = 28\n 3^3 + 1^3 = 28" }, { "code": null, "e": 26848, "s": 26760, "text": "Note:- (a, b) and (b, a) are to be considered as two different pairs. Asked in : Adobe " }, { "code": null, "e": 27085, "s": 26850, "text": "Implementation:\nTraverse numbers from 1 to cube root of N. \n a) Subtract cube of current number from \n N and check if their difference is a \n perfect cube or not.\n i) If perfect cube then increment count.\n\n2- Return count." }, { "code": null, "e": 27134, "s": 27085, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27138, "s": 27134, "text": "C++" }, { "code": null, "e": 27143, "s": 27138, "text": "Java" }, { "code": null, "e": 27152, "s": 27143, "text": "Python 3" }, { "code": null, "e": 27155, "s": 27152, "text": "C#" }, { "code": null, "e": 27159, "s": 27155, "text": "PHP" }, { "code": null, "e": 27170, "s": 27159, "text": "Javascript" }, { "code": "// C++ program to count pairs whose sum// cubes is N#include<bits/stdc++.h>using namespace std; // Function to count the pairs satisfying// a ^ 3 + b ^ 3 = Nint countPairs(int N){ int count = 0; // Check for each number 1 to cbrt(N) for (int i = 1; i <= cbrt(N); i++) { // Store cube of a number int cb = i*i*i; // Subtract the cube from given N int diff = N - cb; // Check if the difference is also // a perfect cube int cbrtDiff = cbrt(diff); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count;} // Driver programint main(){ // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (int i = 1; i<= 10; i++) cout << \"For n = \" << i << \", \" << countPairs(i) <<\" pair exists\\n\"; return 0;}", "e": 28077, "s": 27170, "text": null }, { "code": "// Java program to count pairs whose sum// cubes is N class Test{ // method to count the pairs satisfying // a ^ 3 + b ^ 3 = N static int countPairs(int N) { int count = 0; // Check for each number 1 to cbrt(N) for (int i = 1; i <= Math.cbrt(N); i++) { // Store cube of a number int cb = i*i*i; // Subtract the cube from given N int diff = N - cb; // Check if the difference is also // a perfect cube int cbrtDiff = (int) Math.cbrt(diff); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count; } // Driver method public static void main(String args[]) { // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (int i = 1; i<= 10; i++) System.out.println(\"For n = \" + i + \", \" + + countPairs(i) + \" pair exists\"); }}", "e": 29154, "s": 28077, "text": null }, { "code": "# Python 3 program to count pairs# whose sum cubes is Nimport math # Function to count the pairs# satisfying a ^ 3 + b ^ 3 = Ndef countPairs(N): count = 0 # Check for each number 1 # to cbrt(N) for i in range(1, int(math.pow(N, 1/3) + 1)): # Store cube of a number cb = i * i * i # Subtract the cube from given N diff = N - cb # Check if the difference is also # a perfect cube cbrtDiff = int(math.pow(diff, 1/3)) # If yes, then increment count if (cbrtDiff * cbrtDiff * cbrtDiff == diff): count += 1 # Return count return count # Driver program # Loop to Count no. of pairs satisfying# a ^ 3 + b ^ 3 = i for N = 1 to 10for i in range(1, 11): print('For n = ', i, ', ', countPairs(i), ' pair exists') # This code is contributed by Smitha.", "e": 30036, "s": 29154, "text": null }, { "code": "// C# program to count pairs whose sum// cubes is N using System;class Test{ // method to count the pairs satisfying // a ^ 3 + b ^ 3 = N static int countPairs(int N) { int count = 0; // Check for each number 1 to cbrt(N) for (int i = 1; i <= Math.Pow(N,(1.0/3.0)); i++) { // Store cube of a number int cb = i*i*i; // Subtract the cube from given N int diff = N - cb; // Check if the difference is also // a perfect cube int cbrtDiff = (int) Math.Pow(diff,(1.0/3.0)); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count; } // Driver method public static void Main() { // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (int i = 1; i<= 10; i++) Console.Write(\"For n = \" + i + \", \" + + countPairs(i) + \" pair exists\"+\"\\n\"); }}", "e": 31136, "s": 30036, "text": null }, { "code": "<?php// PHP program to count pairs// whose sum cubes is N // Function to count the pairs// satisfying a ^ 3 + b ^ 3 = Nfunction countPairs($N){ $count = 0; // Check for each number // 1 to cbrt(N) for ($i = 1; $i <= (int)pow($N, 1 / 3); $i++) { // Store cube of a number $cb = $i * $i * $i; // Subtract the cube from // given N $diff = ($N - $cb); // Check if the difference is // also a perfect cube $cbrtDiff = (int)pow($diff, 1 / 3); // If yes, then increment count if ($cbrtDiff * $cbrtDiff * $cbrtDiff == $diff) $count++; } // Return count return $count;} // Driver Code // Loop to Count no. of pairs// satisfying a ^ 3 + b ^ 3 = i// for N = 1 to 10for ($i = 1; $i<= 10; $i++) echo \"For n = \" , $i , \", \", countPairs($i) ,\" pair exists\\n\"; // This code is contributed by jit_t?>", "e": 32073, "s": 31136, "text": null }, { "code": "<script> // Javascript program to count pairs whose sum cubes is N // method to count the pairs satisfying // a ^ 3 + b ^ 3 = N function countPairs(N) { let count = 0; // Check for each number 1 to cbrt(N) for (let i = 1; i <= parseInt(Math.pow(N,(1.0/3.0)), 10); i++) { // Store cube of a number let cb = i*i*i; // Subtract the cube from given N let diff = N - cb; // Check if the difference is also // a perfect cube let cbrtDiff = parseInt(Math.pow(diff,(1.0/3.0)), 10); // If yes, then increment count if (cbrtDiff*cbrtDiff*cbrtDiff == diff) count++; } // Return count return count; } // Loop to Count no. of pairs satisfying // a ^ 3 + b ^ 3 = i for N = 1 to 10 for (let i = 1; i<= 10; i++) document.write(\"For n = \" + i + \", \" + countPairs(i) + \" pair exists\"+\"</br>\"); </script>", "e": 33113, "s": 32073, "text": null }, { "code": null, "e": 33123, "s": 33113, "text": "Output: " }, { "code": null, "e": 33364, "s": 33123, "text": "For n= 1, 1 pair exists\nFor n= 2, 1 pair exists\nFor n= 3, 0 pair exists\nFor n= 4, 0 pair exists\nFor n= 5, 0 pair exists\nFor n= 6, 0 pair exists\nFor n= 7, 0 pair exists\nFor n= 8, 1 pair exists\nFor n= 9, 2 pair exists\nFor n= 10, 0 pair exists" }, { "code": null, "e": 33851, "s": 33364, "text": "Reference: https://www.careercup.com/question?id=5954491572551680This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33872, "s": 33851, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 33878, "s": 33872, "text": "ukasp" }, { "code": null, "e": 33884, "s": 33878, "text": "jit_t" }, { "code": null, "e": 33897, "s": 33884, "text": "Akanksha_Rai" }, { "code": null, "e": 33915, "s": 33897, "text": "divyeshrabadiya07" }, { "code": null, "e": 33924, "s": 33915, "text": "gabaa406" }, { "code": null, "e": 33930, "s": 33924, "text": "Adobe" }, { "code": null, "e": 33941, "s": 33930, "text": "maths-cube" }, { "code": null, "e": 33954, "s": 33941, "text": "Mathematical" }, { "code": null, "e": 33960, "s": 33954, "text": "Adobe" }, { "code": null, "e": 33973, "s": 33960, "text": "Mathematical" }, { "code": null, "e": 34071, "s": 33973, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34095, "s": 34071, "text": "Merge two sorted arrays" }, { "code": null, "e": 34138, "s": 34095, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34152, "s": 34138, "text": "Prime Numbers" }, { "code": null, "e": 34225, "s": 34152, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 34259, "s": 34225, "text": "Program for factorial of a number" }, { "code": null, "e": 34280, "s": 34259, "text": "Operators in C / C++" }, { "code": null, "e": 34333, "s": 34280, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 34376, "s": 34333, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34425, "s": 34376, "text": "Program to find sum of elements in a given array" } ]
C Program to Reverse Array of Strings - GeeksforGeeks
20 Dec, 2018 Given an array of string literals, reverse the array. Examples: Input : arr[] = {"Coding", "Never", "Fail", "Me"} Output : arr[] = {"Me", "Fail", "Never", "Coding"} Input : arr[] = {"welcome", "to", "geeksforgeeks"} Output : arr[] = {"geeksforgeeks", "to", "welcome"} The idea is to create an array of pointers, store string literals in it. To reverse the array, we start from begin and end, and move both pointers toward each other. While moving, we keep swapping pointers. // C program to reverse an array of strings#include <stdio.h>#include <string.h> void PrintArray(char* arr[], int n){ for (int i = 0; i < n; i++) { printf("%s ", arr[i]); }} void ReverseArray(char* arr[], int n){ char* temp; // Move from begin and end. Keep // swapping strings. int j = n - 1; for (int i = 0; i < j; i++) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j--; }} int main(){ char* arr[] = { "Coding", "never", "fail", "me" }; int n = sizeof(arr) / sizeof(arr[0]); PrintArray(arr, n); printf("\n"); ReverseArray(arr, n); PrintArray(arr, n); return 0;} Coding never fail me me fail never Coding C-String Reverse C Programs Reverse 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 Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C program to sort an array in ascending order time() function in C C Program to Swap two Numbers Producer Consumer Problem in C unsigned char in C with Examples Program to calculate First and Follow sets of given grammar
[ { "code": null, "e": 24440, "s": 24412, "text": "\n20 Dec, 2018" }, { "code": null, "e": 24494, "s": 24440, "text": "Given an array of string literals, reverse the array." }, { "code": null, "e": 24504, "s": 24494, "text": "Examples:" }, { "code": null, "e": 24717, "s": 24504, "text": "Input : arr[] = {\"Coding\", \"Never\", \"Fail\", \"Me\"} \nOutput : arr[] = {\"Me\", \"Fail\", \"Never\", \"Coding\"}\n\nInput : arr[] = {\"welcome\", \"to\", \"geeksforgeeks\"} \nOutput : arr[] = {\"geeksforgeeks\", \"to\", \"welcome\"} \n" }, { "code": null, "e": 24924, "s": 24717, "text": "The idea is to create an array of pointers, store string literals in it. To reverse the array, we start from begin and end, and move both pointers toward each other. While moving, we keep swapping pointers." }, { "code": "// C program to reverse an array of strings#include <stdio.h>#include <string.h> void PrintArray(char* arr[], int n){ for (int i = 0; i < n; i++) { printf(\"%s \", arr[i]); }} void ReverseArray(char* arr[], int n){ char* temp; // Move from begin and end. Keep // swapping strings. int j = n - 1; for (int i = 0; i < j; i++) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j--; }} int main(){ char* arr[] = { \"Coding\", \"never\", \"fail\", \"me\" }; int n = sizeof(arr) / sizeof(arr[0]); PrintArray(arr, n); printf(\"\\n\"); ReverseArray(arr, n); PrintArray(arr, n); return 0;}", "e": 25587, "s": 24924, "text": null }, { "code": null, "e": 25631, "s": 25587, "text": "Coding never fail me \nme fail never Coding\n" }, { "code": null, "e": 25640, "s": 25631, "text": "C-String" }, { "code": null, "e": 25648, "s": 25640, "text": "Reverse" }, { "code": null, "e": 25659, "s": 25648, "text": "C Programs" }, { "code": null, "e": 25667, "s": 25659, "text": "Reverse" }, { "code": null, "e": 25765, "s": 25667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25800, "s": 25765, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 25841, "s": 25800, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 25885, "s": 25841, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 25944, "s": 25885, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 25990, "s": 25944, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 26011, "s": 25990, "text": "time() function in C" }, { "code": null, "e": 26041, "s": 26011, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 26072, "s": 26041, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 26105, "s": 26072, "text": "unsigned char in C with Examples" } ]
Implementing Rest API in Flutter - GeeksforGeeks
31 Oct, 2020 Along with building a UI in Flutter, we can also integrate it with the backend. Most applications use API to display the uses data. We will use HTTP package, which provides advanced methods to perform operations. REST API uses simple http calls to communicate with JSON data because: It uses await & async features. It provides various methods. It provides class and http to perform web requests. Let us see how a JSON file is used to Fetch, Delete & Update data in a flutter app. We will make separate dart files of Main.dart for easier debugging & cleaner code in the following steps. Install the http dependency and add it in pubspec.yaml file in order to use API in the application. dependencies: http: This basic request uses the get method to fetch the data from the specified URL in JSON format. Each request returns a Future<Response>. A Future<> is used to represent a potential value or error that will be available at some time in the future, for example, you made a request to a server now the response will take less than a few seconds, this time is represented from Future<>. Here, we use async & await feature which ensures that the response is asynchronous which means until & unless we get the response, it will not move further. Future<List<Fruit>> fetchFruit() async { final response = await http.get(url); } String url = "Your_URL"; Create a Fruit class & saving as fruit.dart as shown below: Dart class Fruit { final int id; final String title; final String imgUrl; final int quantity; Fruit( this.id, this.title, this.imgUrl, this.quantity, ); factory Fruit.fromMap(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); } factory Fruit.fromJson(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); }} Create the FruitItem in fruitItem.dart Dart import 'package:flutter/material.dart';import 'fruit.dart'; class FruitItem extends StatelessWidget { FruitItem({this.item}); final Fruit item; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( elevation: 5, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.network( this.item.imgUrl, width: 200, ), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.title, style: TextStyle(fontWeight: FontWeight.bold)), Text("id:${this.item.id}"), Text("quantity:${this.item.quantity}"), ], ))) ]), )); }} Create a FruitList class in fruitList.dart as shown below: Dart import 'package:flutter/material.dart';import 'fruit.dart';import 'fruitItem.dart'; class FruitList extends StatelessWidget { final List<Fruit> items; FruitList({Key key, this.items}); @override Widget build(BuildContext context) { return ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return FruitItem(item: items[index]); }, ); }} Display the response on the screen from main.dart file as shown below: Dart import 'package:http/http.dart' as http;import 'dart:convert';import 'package:flutter/material.dart';import 'fruit.dart';import 'fruitItem.dart';import 'fruitList.dart'; class MyHomePage extends StatelessWidget { final String title; final Future<List<Fruit>> products; MyHomePage({Key key, this.title, this.products}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color(0xFF4CAF50), title: Text("GeeksForGeeks"), ), body: Center( child: FutureBuilder<List<Fruit>>( future: products, builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? FruitList(items: snapshot.data) : Center(child: CircularProgressIndicator()); }, ), )); }} Following is the JSON Data upon running the application: Following is the UI screen of the homepage of Flutter application with decoded JSON data. Output: 1. This statement is used to import the package as http. import 'package:http/http.dart' as http; 2. This statement is used to convert the JSON data. import 'dart:convert'; 3. The following statement is used in order to handle the error code. If the response status code is 200 then we can display the requested data otherwise we can show the error message to the user. Here, you can use any URL which is taking get() request and returning response in JSON format. final response = await http.get('url'); if (response.statusCode == 200) { //display UI} else { //Show Error Message } } 4. Following statements are used in order to decode the JSON data and display the output in a user-friendly manner. This ensures that it only accepts and extracts JSON data as per our requirement. List<Fruit> decodeFruit(String responseBody) { final parsed = json.decode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList(); } Now Rest API is successfully implemented in the flutter app. If you need to update, delete, or send data in the Flutter app by using the JSON file, follow the below-mentioned steps exactly the same as the step creating the request. Since we need to send the noteID to the API, we need to update the noteID & add it to the path we are sending to the API using ‘/$id’ in put(), delete(), or post() method because we need to specify which note we are updating, deleting or sending respectively. We also need to re-fetch the notes once they are updated, deleted, or sent to display them. Dart Future<Fruit> updateFruit(String title) async { final http.Response response = await http.put( 'url/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); if (response.statusCode == 200) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update album.'); }} Dart Future<Fruit> deleteAlbum(int id) async { final http.Response response = await http.delete( 'url/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to delete album.'); }} Dart Future<Fruit> sendFruit( String title, int id, String imgUrl, int quantity) async { final http.Response response = await http.post( 'url', headers: <String, String> { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String> { 'title': title, 'id': id.toString(), 'imgUrl': imgUrl, 'quantity': quantity.toString() }), ); if (response.statusCode == 201) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }} android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget ListView Class in Flutter Flutter - Flexible Widget Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter Tutorial Flutter - Flexible Widget
[ { "code": null, "e": 25305, "s": 25277, "text": "\n31 Oct, 2020" }, { "code": null, "e": 25589, "s": 25305, "text": "Along with building a UI in Flutter, we can also integrate it with the backend. Most applications use API to display the uses data. We will use HTTP package, which provides advanced methods to perform operations. REST API uses simple http calls to communicate with JSON data because:" }, { "code": null, "e": 25621, "s": 25589, "text": "It uses await & async features." }, { "code": null, "e": 25650, "s": 25621, "text": "It provides various methods." }, { "code": null, "e": 25702, "s": 25650, "text": "It provides class and http to perform web requests." }, { "code": null, "e": 25892, "s": 25702, "text": "Let us see how a JSON file is used to Fetch, Delete & Update data in a flutter app. We will make separate dart files of Main.dart for easier debugging & cleaner code in the following steps." }, { "code": null, "e": 25992, "s": 25892, "text": "Install the http dependency and add it in pubspec.yaml file in order to use API in the application." }, { "code": null, "e": 26015, "s": 25992, "text": "dependencies:\n http:\n" }, { "code": null, "e": 26555, "s": 26015, "text": "This basic request uses the get method to fetch the data from the specified URL in JSON format. Each request returns a Future<Response>. A Future<> is used to represent a potential value or error that will be available at some time in the future, for example, you made a request to a server now the response will take less than a few seconds, this time is represented from Future<>. Here, we use async & await feature which ensures that the response is asynchronous which means until & unless we get the response, it will not move further." }, { "code": null, "e": 26662, "s": 26555, "text": "Future<List<Fruit>> fetchFruit() async {\nfinal response = await http.get(url);\n}\nString url = \"Your_URL\";\n" }, { "code": null, "e": 26722, "s": 26662, "text": "Create a Fruit class & saving as fruit.dart as shown below:" }, { "code": null, "e": 26727, "s": 26722, "text": "Dart" }, { "code": "class Fruit { final int id; final String title; final String imgUrl; final int quantity; Fruit( this.id, this.title, this.imgUrl, this.quantity, ); factory Fruit.fromMap(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); } factory Fruit.fromJson(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); }}", "e": 27163, "s": 26727, "text": null }, { "code": null, "e": 27202, "s": 27163, "text": "Create the FruitItem in fruitItem.dart" }, { "code": null, "e": 27207, "s": 27202, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'fruit.dart'; class FruitItem extends StatelessWidget { FruitItem({this.item}); final Fruit item; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( elevation: 5, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.network( this.item.imgUrl, width: 200, ), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.title, style: TextStyle(fontWeight: FontWeight.bold)), Text(\"id:${this.item.id}\"), Text(\"quantity:${this.item.quantity}\"), ], ))) ]), )); }}", "e": 28352, "s": 27207, "text": null }, { "code": null, "e": 28411, "s": 28352, "text": "Create a FruitList class in fruitList.dart as shown below:" }, { "code": null, "e": 28416, "s": 28411, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'fruit.dart';import 'fruitItem.dart'; class FruitList extends StatelessWidget { final List<Fruit> items; FruitList({Key key, this.items}); @override Widget build(BuildContext context) { return ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return FruitItem(item: items[index]); }, ); }}", "e": 28813, "s": 28416, "text": null }, { "code": null, "e": 28884, "s": 28813, "text": "Display the response on the screen from main.dart file as shown below:" }, { "code": null, "e": 28889, "s": 28884, "text": "Dart" }, { "code": "import 'package:http/http.dart' as http;import 'dart:convert';import 'package:flutter/material.dart';import 'fruit.dart';import 'fruitItem.dart';import 'fruitList.dart'; class MyHomePage extends StatelessWidget { final String title; final Future<List<Fruit>> products; MyHomePage({Key key, this.title, this.products}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color(0xFF4CAF50), title: Text(\"GeeksForGeeks\"), ), body: Center( child: FutureBuilder<List<Fruit>>( future: products, builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? FruitList(items: snapshot.data) : Center(child: CircularProgressIndicator()); }, ), )); }}", "e": 29809, "s": 28889, "text": null }, { "code": null, "e": 29866, "s": 29809, "text": "Following is the JSON Data upon running the application:" }, { "code": null, "e": 29956, "s": 29866, "text": "Following is the UI screen of the homepage of Flutter application with decoded JSON data." }, { "code": null, "e": 29964, "s": 29956, "text": "Output:" }, { "code": null, "e": 30021, "s": 29964, "text": "1. This statement is used to import the package as http." }, { "code": null, "e": 30063, "s": 30021, "text": "import 'package:http/http.dart' as http;\n" }, { "code": null, "e": 30115, "s": 30063, "text": "2. This statement is used to convert the JSON data." }, { "code": null, "e": 30139, "s": 30115, "text": "import 'dart:convert';\n" }, { "code": null, "e": 30431, "s": 30139, "text": "3. The following statement is used in order to handle the error code. If the response status code is 200 then we can display the requested data otherwise we can show the error message to the user. Here, you can use any URL which is taking get() request and returning response in JSON format." }, { "code": null, "e": 30568, "s": 30431, "text": "final response = await http.get('url');\n if (response.statusCode == 200) {\n //display UI} \n else {\n //Show Error Message\n }\n}\n" }, { "code": null, "e": 30765, "s": 30568, "text": "4. Following statements are used in order to decode the JSON data and display the output in a user-friendly manner. This ensures that it only accepts and extracts JSON data as per our requirement." }, { "code": null, "e": 30954, "s": 30765, "text": "List<Fruit> decodeFruit(String responseBody) {\n final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();\n return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList();\n}\n" }, { "code": null, "e": 31187, "s": 30954, "text": "Now Rest API is successfully implemented in the flutter app. If you need to update, delete, or send data in the Flutter app by using the JSON file, follow the below-mentioned steps exactly the same as the step creating the request. " }, { "code": null, "e": 31539, "s": 31187, "text": "Since we need to send the noteID to the API, we need to update the noteID & add it to the path we are sending to the API using ‘/$id’ in put(), delete(), or post() method because we need to specify which note we are updating, deleting or sending respectively. We also need to re-fetch the notes once they are updated, deleted, or sent to display them." }, { "code": null, "e": 31544, "s": 31539, "text": "Dart" }, { "code": "Future<Fruit> updateFruit(String title) async { final http.Response response = await http.put( 'url/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), ); if (response.statusCode == 200) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update album.'); }}", "e": 31968, "s": 31544, "text": null }, { "code": null, "e": 31973, "s": 31968, "text": "Dart" }, { "code": "Future<Fruit> deleteAlbum(int id) async { final http.Response response = await http.delete( 'url/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to delete album.'); }}", "e": 32328, "s": 31973, "text": null }, { "code": null, "e": 32333, "s": 32328, "text": "Dart" }, { "code": "Future<Fruit> sendFruit( String title, int id, String imgUrl, int quantity) async { final http.Response response = await http.post( 'url', headers: <String, String> { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String> { 'title': title, 'id': id.toString(), 'imgUrl': imgUrl, 'quantity': quantity.toString() }), ); if (response.statusCode == 201) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); }}", "e": 32879, "s": 32333, "text": null }, { "code": null, "e": 32887, "s": 32879, "text": "android" }, { "code": null, "e": 32895, "s": 32887, "text": "Flutter" }, { "code": null, "e": 32900, "s": 32895, "text": "Dart" }, { "code": null, "e": 32908, "s": 32900, "text": "Flutter" }, { "code": null, "e": 33006, "s": 32908, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33038, "s": 33006, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33077, "s": 33038, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33103, "s": 33077, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 33129, "s": 33103, "text": "ListView Class in Flutter" }, { "code": null, "e": 33155, "s": 33129, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 33187, "s": 33155, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33226, "s": 33187, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33252, "s": 33226, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 33269, "s": 33252, "text": "Flutter Tutorial" } ]
How to Use Canvas API in Android Apps? - GeeksforGeeks
26 Apr, 2021 Canvas API is also one of the most used in Android. The name of the API itself tells us that the API is being used for drawing on the drawing board. With the help of this API, we can draw different types of shapes and create custom UI components that are not present in Android. In this article, we will take a look at Canvas API and also use this API in our app to make a simple design. Canvas API is a drawing framework that is provided in Android, with the help of which we can create custom shapes like rectangle, circle, and many more in our UI design. With the help of this API, we can draw any type of shape for our app. The drawing of the different shapes is done using Bitmap. While using this API the screen of the user’s device is called Canvas on which we have to draw different types of shapes and designs. There are different methods that are used to draw different shapes on our Canvas. Below are the methods which are used for drawing shapes on Canvas. Methods Description This method is used to measure the size of the view and the children’s present in that view. This method is use to draw the different views in our Canvas. With this method we can draw different shapes on our Canvas. There are predefined methods for different shapes such as drawRect(), drawArc(), drawLine() and many more. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/idRLView" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"></RelativeLayout> Step 3: Creating a new Java class for drawing our view Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as PaintView and add the below code to it. Java import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.DisplayMetrics;import android.view.View; public class PaintView extends View { // below we are creating variables for our paint Paint otherPaint, outerPaint, textPaint; // and a floating variable for our left arc. float arcLeft; @SuppressLint("ResourceAsColor") public PaintView(Context context) { super(context); // on below line we are initializing our paint variable for our text textPaint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // on below line we are setting color to it. textPaint.setColor(Color.WHITE); // on below line we are setting text size to it. // In Paint we have to add text size using px so // we have created a method where we are converting dp to pixels. textPaint.setTextSize(pxFromDp(context, 24)); // on below line we are initializing our outer paint outerPaint = new Paint(); // on below line we are setting style to our paint. outerPaint.setStyle(Paint.Style.FILL); // on below line we are setting color to it. outerPaint.setColor(getResources().getColor(R.color.purple_200)); // on below line we are creating a display metrics DisplayMetrics displayMetrics = new DisplayMetrics(); // on below line we are getting display metrics. ((Activity) getContext()).getWindowManager() .getDefaultDisplay() .getMetrics(displayMetrics); // on below line we are assigning // the value to the arc left. arcLeft = pxFromDp(context, 20); // on below line we are creating // a new variable for our paint otherPaint = new Paint(); } // below method is use to generate px from DP. public static float pxFromDp(final Context context, final float dp) { return dp * context.getResources().getDisplayMetrics().density; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // below four lines of code is use to add // back color to our screen which is green canvas.drawPaint(outerPaint); // on below line we are setting color to our paint. otherPaint.setColor(Color.WHITE); // on below line we are setting style to out paint. otherPaint.setStyle(Paint.Style.FILL); // below 4 lines of code is use to // create white rectangle of screen canvas.drawRect( getLeft() + (getRight() - getLeft()) / 3, getTop() + (getBottom() - getTop()) / 3, getRight() - (getRight() - getLeft()) / 3, getBottom() - (getBottom() - getTop()) / 3, otherPaint); // on below line we are changing the color for our paint. otherPaint.setColor(getResources().getColor(R.color.purple_200)); // on below line we are drawing a circle and passing // width, height, left arc and paint to add color. canvas.drawCircle(getWidth() / 2, getHeight() / 2, arcLeft, otherPaint); // on below line we are adding text using paint in our canvas. canvas.drawText("Geeks for Geeks", (float) (getWidth() * 0.3), (float) (getHeight() * 0.8), textPaint); }} Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.RelativeLayout; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // creating a variable for our relative layout private RelativeLayout relativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our view. relativeLayout = findViewById(R.id.idRLView); // calling our paint view class and adding // its view to our relative layout. PaintView paintView = new PaintView(this); relativeLayout.addView(paintView); }} Now run your app and see the output of the app. Output: Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? Flutter - Custom Bottom Navigation Bar Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java
[ { "code": null, "e": 25036, "s": 25008, "text": "\n26 Apr, 2021" }, { "code": null, "e": 25425, "s": 25036, "text": "Canvas API is also one of the most used in Android. The name of the API itself tells us that the API is being used for drawing on the drawing board. With the help of this API, we can draw different types of shapes and create custom UI components that are not present in Android. In this article, we will take a look at Canvas API and also use this API in our app to make a simple design. " }, { "code": null, "e": 25724, "s": 25425, "text": "Canvas API is a drawing framework that is provided in Android, with the help of which we can create custom shapes like rectangle, circle, and many more in our UI design. With the help of this API, we can draw any type of shape for our app. The drawing of the different shapes is done using Bitmap. " }, { "code": null, "e": 26008, "s": 25724, "text": "While using this API the screen of the user’s device is called Canvas on which we have to draw different types of shapes and designs. There are different methods that are used to draw different shapes on our Canvas. Below are the methods which are used for drawing shapes on Canvas. " }, { "code": null, "e": 26016, "s": 26008, "text": "Methods" }, { "code": null, "e": 26028, "s": 26016, "text": "Description" }, { "code": null, "e": 26080, "s": 26028, "text": "This method is used to measure the size of the view" }, { "code": null, "e": 26122, "s": 26080, "text": "and the children’s present in that view. " }, { "code": null, "e": 26185, "s": 26122, "text": "This method is use to draw the different views in our Canvas. " }, { "code": null, "e": 26247, "s": 26185, "text": "With this method we can draw different shapes on our Canvas. " }, { "code": null, "e": 26317, "s": 26247, "text": "There are predefined methods for different shapes such as drawRect()," }, { "code": null, "e": 26354, "s": 26317, "text": "drawArc(), drawLine() and many more." }, { "code": null, "e": 26383, "s": 26354, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26545, "s": 26383, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 26593, "s": 26545, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26736, "s": 26593, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26740, "s": 26736, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/idRLView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"></RelativeLayout>", "e": 27067, "s": 26740, "text": null }, { "code": null, "e": 27123, "s": 27067, "text": "Step 3: Creating a new Java class for drawing our view " }, { "code": null, "e": 27270, "s": 27123, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as PaintView and add the below code to it." }, { "code": null, "e": 27275, "s": 27270, "text": "Java" }, { "code": "import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.DisplayMetrics;import android.view.View; public class PaintView extends View { // below we are creating variables for our paint Paint otherPaint, outerPaint, textPaint; // and a floating variable for our left arc. float arcLeft; @SuppressLint(\"ResourceAsColor\") public PaintView(Context context) { super(context); // on below line we are initializing our paint variable for our text textPaint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // on below line we are setting color to it. textPaint.setColor(Color.WHITE); // on below line we are setting text size to it. // In Paint we have to add text size using px so // we have created a method where we are converting dp to pixels. textPaint.setTextSize(pxFromDp(context, 24)); // on below line we are initializing our outer paint outerPaint = new Paint(); // on below line we are setting style to our paint. outerPaint.setStyle(Paint.Style.FILL); // on below line we are setting color to it. outerPaint.setColor(getResources().getColor(R.color.purple_200)); // on below line we are creating a display metrics DisplayMetrics displayMetrics = new DisplayMetrics(); // on below line we are getting display metrics. ((Activity) getContext()).getWindowManager() .getDefaultDisplay() .getMetrics(displayMetrics); // on below line we are assigning // the value to the arc left. arcLeft = pxFromDp(context, 20); // on below line we are creating // a new variable for our paint otherPaint = new Paint(); } // below method is use to generate px from DP. public static float pxFromDp(final Context context, final float dp) { return dp * context.getResources().getDisplayMetrics().density; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // below four lines of code is use to add // back color to our screen which is green canvas.drawPaint(outerPaint); // on below line we are setting color to our paint. otherPaint.setColor(Color.WHITE); // on below line we are setting style to out paint. otherPaint.setStyle(Paint.Style.FILL); // below 4 lines of code is use to // create white rectangle of screen canvas.drawRect( getLeft() + (getRight() - getLeft()) / 3, getTop() + (getBottom() - getTop()) / 3, getRight() - (getRight() - getLeft()) / 3, getBottom() - (getBottom() - getTop()) / 3, otherPaint); // on below line we are changing the color for our paint. otherPaint.setColor(getResources().getColor(R.color.purple_200)); // on below line we are drawing a circle and passing // width, height, left arc and paint to add color. canvas.drawCircle(getWidth() / 2, getHeight() / 2, arcLeft, otherPaint); // on below line we are adding text using paint in our canvas. canvas.drawText(\"Geeks for Geeks\", (float) (getWidth() * 0.3), (float) (getHeight() * 0.8), textPaint); }}", "e": 30860, "s": 27275, "text": null }, { "code": null, "e": 30908, "s": 30860, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 31098, "s": 30908, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31103, "s": 31098, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.RelativeLayout; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // creating a variable for our relative layout private RelativeLayout relativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our view. relativeLayout = findViewById(R.id.idRLView); // calling our paint view class and adding // its view to our relative layout. PaintView paintView = new PaintView(this); relativeLayout.addView(paintView); }}", "e": 31829, "s": 31103, "text": null }, { "code": null, "e": 31878, "s": 31829, "text": "Now run your app and see the output of the app. " }, { "code": null, "e": 31886, "s": 31878, "text": "Output:" }, { "code": null, "e": 31893, "s": 31886, "text": "Picked" }, { "code": null, "e": 31901, "s": 31893, "text": "Android" }, { "code": null, "e": 31906, "s": 31901, "text": "Java" }, { "code": null, "e": 31911, "s": 31906, "text": "Java" }, { "code": null, "e": 31919, "s": 31911, "text": "Android" }, { "code": null, "e": 32017, "s": 31919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32026, "s": 32017, "text": "Comments" }, { "code": null, "e": 32039, "s": 32026, "text": "Old Comments" }, { "code": null, "e": 32081, "s": 32039, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32119, "s": 32081, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32169, "s": 32119, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32242, "s": 32169, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 32281, "s": 32242, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32296, "s": 32281, "text": "Arrays in Java" }, { "code": null, "e": 32340, "s": 32296, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32362, "s": 32340, "text": "For-each loop in Java" }, { "code": null, "e": 32398, "s": 32362, "text": "Arrays.sort() in Java with examples" } ]
Python Machine Learning Multiple Regression
Multiple regression is like linear regression, but with more than one independent value, meaning that we try to predict a value based on two or more variables. Take a look at the data set below, it contains some information about cars. We can predict the CO2 emission of a car based on the size of the engine, but with multiple regression we can throw in more variables, like the weight of the car, to make the prediction more accurate. In Python we have modules that will do the work for us. Start by importing the Pandas module. import pandas Learn about the Pandas module in our Pandas Tutorial. The Pandas module allows us to read csv files and return a DataFrame object. The file is meant for testing purposes only, you can download it here: cars.csv df = pandas.read_csv("cars.csv") Then make a list of the independent values and call this variable X. Put the dependent values in a variable called y. X = df[['Weight', 'Volume']] y = df['CO2'] Tip: It is common to name the list of independent values with a upper case X, and the list of dependent values with a lower case y. We will use some methods from the sklearn module, so we will have to import that module as well: from sklearn import linear_model From the sklearn module we will use the LinearRegression() method to create a linear regression object. This object has a method called fit() that takes the independent and dependent values as parameters and fills the regression object with data that describes the relationship: regr = linear_model.LinearRegression() regr.fit(X, y) Now we have a regression object that are ready to predict CO2 values based on a car's weight and volume: #predict the CO2 emission of a car where the weight is 2300kg, and the volume is 1300cm3: predictedCO2 = regr.predict([[2300, 1300]]) See the whole example in action: [107.2087328] Run example » We have predicted that a car with 1.3 liter engine, and a weight of 2300 kg, will release approximately 107 grams of CO2 for every kilometer it drives. The coefficient is a factor that describes the relationship with an unknown variable. Example: if x is a variable, then 2x is x two times. x is the unknown variable, and the number 2 is the coefficient. In this case, we can ask for the coefficient value of weight against CO2, and for volume against CO2. The answer(s) we get tells us what would happen if we increase, or decrease, one of the independent values. Print the coefficient values of the regression object: [0.00755095 0.00780526] Run example » The result array represents the coefficient values of weight and volume. Weight: 0.00755095 Volume: 0.00780526 These values tell us that if the weight increase by 1kg, the CO2 emission increases by 0.00755095g. And if the engine size (Volume) increases by 1 cm3, the CO2 emission increases by 0.00780526 g. I think that is a fair guess, but let test it! We have already predicted that if a car with a 1300cm3 engine weighs 2300kg, the CO2 emission will be approximately 107g. What if we increase the weight with 1000kg? Copy the example from before, but change the weight from 2300 to 3300: [114.75968007] Run example » We have predicted that a car with 1.3 liter engine, and a weight of 3300 kg, will release approximately 115 grams of CO2 for every kilometer it drives. Which shows that the coefficient of 0.00755095 is correct: 107.2087328 + (1000 * 0.00755095) = 114.75968 We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 162, "s": 0, "text": "Multiple regression is like linear regression, but with more than one \nindependent value, meaning that we try to predict a value based on two \nor more variables." }, { "code": null, "e": 238, "s": 162, "text": "Take a look at the data set below, it contains some information about cars." }, { "code": null, "e": 441, "s": 238, "text": "We can predict the CO2 emission of a car based on \nthe size of the engine, but with multiple regression we can throw in more \nvariables, like the weight of the car, to make the prediction more accurate." }, { "code": null, "e": 536, "s": 441, "text": "In Python we have modules that will do the work for us. Start by importing \nthe Pandas module." }, { "code": null, "e": 551, "s": 536, "text": "import pandas " }, { "code": null, "e": 605, "s": 551, "text": "Learn about the Pandas module in our Pandas Tutorial." }, { "code": null, "e": 682, "s": 605, "text": "The Pandas module allows us to read csv files and return a DataFrame object." }, { "code": null, "e": 762, "s": 682, "text": "The file is meant for testing purposes only, you can download it here: cars.csv" }, { "code": null, "e": 796, "s": 762, "text": "df = pandas.read_csv(\"cars.csv\") " }, { "code": null, "e": 867, "s": 796, "text": "Then make a list of the independent values and call this \nvariable X. " }, { "code": null, "e": 916, "s": 867, "text": "Put the dependent values in a variable called y." }, { "code": null, "e": 960, "s": 916, "text": "X = df[['Weight', 'Volume']]\ny = df['CO2'] " }, { "code": null, "e": 1094, "s": 960, "text": "Tip: It is common to name the list of independent values with a upper \ncase X, and the list of dependent values with a lower case y." }, { "code": null, "e": 1191, "s": 1094, "text": "We will use some methods from the sklearn module, so we will have to import that module as well:" }, { "code": null, "e": 1225, "s": 1191, "text": "from sklearn import linear_model " }, { "code": null, "e": 1330, "s": 1225, "text": "From the sklearn module we will use the LinearRegression() method \nto create a linear regression object." }, { "code": null, "e": 1506, "s": 1330, "text": "This object has a method called fit() that takes \nthe independent and dependent values as parameters and fills the regression object with data that describes the relationship:" }, { "code": null, "e": 1561, "s": 1506, "text": "regr = linear_model.LinearRegression()\nregr.fit(X, y) " }, { "code": null, "e": 1667, "s": 1561, "text": "Now we have a regression object that are ready to predict CO2 values based on \na car's weight and volume:" }, { "code": null, "e": 1807, "s": 1667, "text": "#predict the CO2 emission of a car where the weight \n is 2300kg, and the volume is 1300cm3:\n predictedCO2 = regr.predict([[2300, 1300]]) " }, { "code": null, "e": 1840, "s": 1807, "text": "See the whole example in action:" }, { "code": null, "e": 1854, "s": 1840, "text": "[107.2087328]" }, { "code": null, "e": 1870, "s": 1854, "text": "\nRun example »\n" }, { "code": null, "e": 2023, "s": 1870, "text": "We have predicted that a car with 1.3 liter engine, and a weight of 2300 kg, will release approximately 107 grams of CO2 for every \nkilometer it drives." }, { "code": null, "e": 2110, "s": 2023, "text": "The coefficient is a factor that describes the relationship \nwith an unknown variable." }, { "code": null, "e": 2229, "s": 2110, "text": "Example: if x is a variable, then\n2x is x two \ntimes. x is the unknown variable, and the \nnumber 2 is the coefficient." }, { "code": null, "e": 2441, "s": 2229, "text": "In this case, we can ask for the coefficient value of weight against CO2, and \nfor volume against CO2. The answer(s) we get tells us what would happen if we \nincrease, or decrease, one of the independent values." }, { "code": null, "e": 2496, "s": 2441, "text": "Print the coefficient values of the regression object:" }, { "code": null, "e": 2520, "s": 2496, "text": "[0.00755095 0.00780526]" }, { "code": null, "e": 2536, "s": 2520, "text": "\nRun example »\n" }, { "code": null, "e": 2609, "s": 2536, "text": "The result array represents the coefficient values of weight and volume." }, { "code": null, "e": 2647, "s": 2609, "text": "Weight: 0.00755095\nVolume: 0.00780526" }, { "code": null, "e": 2748, "s": 2647, "text": "These values tell us that if the weight increase by 1kg, the CO2 \nemission increases by 0.00755095g." }, { "code": null, "e": 2845, "s": 2748, "text": "And if the engine size (Volume) increases by 1 cm3, the CO2 emission \nincreases by 0.00780526 g." }, { "code": null, "e": 2892, "s": 2845, "text": "I think that is a fair guess, but let test it!" }, { "code": null, "e": 3014, "s": 2892, "text": "We have already predicted that if a car with a 1300cm3 engine weighs 2300kg, the CO2 emission will be approximately 107g." }, { "code": null, "e": 3058, "s": 3014, "text": "What if we increase the weight with 1000kg?" }, { "code": null, "e": 3129, "s": 3058, "text": "Copy the example from before, but change the weight from 2300 to 3300:" }, { "code": null, "e": 3144, "s": 3129, "text": "[114.75968007]" }, { "code": null, "e": 3160, "s": 3144, "text": "\nRun example »\n" }, { "code": null, "e": 3314, "s": 3160, "text": "\nWe have predicted that a car with 1.3 liter engine, and a weight of \n3300 kg, will release approximately 115 grams of CO2 for every kilometer it drives." }, { "code": null, "e": 3374, "s": 3314, "text": "\nWhich shows that the coefficient of 0.00755095 is correct:" }, { "code": null, "e": 3421, "s": 3374, "text": "\n107.2087328 + (1000 * 0.00755095) = 114.75968" }, { "code": null, "e": 3454, "s": 3421, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3496, "s": 3454, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3603, "s": 3496, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3622, "s": 3603, "text": "help@w3schools.com" } ]
Elixir - Functions
A function is a set of statements organized together to perform a specific task. Functions in programming work mostly like function in Math. You give functions some input, they generate output based on the input provided. There are 2 types of functions in Elixir − Functions defined using the fn..end construct are anonymous functions. These functions are sometimes also called as lambdas. They are used by assigning them to variable names. Functions defined using the def keyword are named functions. These are native functions provided in Elixir. Just as the name implies, an anonymous function has no name. These are frequently passed to other functions. To define an anonymous function in Elixir, we need the fn and end keywords. Within these, we can define any number of parameters and function bodies separated by ->. For example, sum = fn (a, b) -> a + b end IO.puts(sum.(1, 5)) When running above program, is run, it generates the following result − 6 Note that these functions are not called like the named functions. We have a '.' between the function name and its arguments. We can also define these functions using the capture operator. This is an easier method to create functions. We will now define the above sum function using the capture operator, sum = &(&1 + &2) IO.puts(sum.(1, 2)) When the above program is run, it generates the following result − 3 In the shorthand version, our parameters are not named but are available to us as &1, &2, &3, and so on. Pattern matching is not only limited to variables and data structures. We can use pattern matching to make our functions polymorphic. For example, we will declare a function that can either take 1 or 2 inputs (within a tuple) and print them to the console, handle_result = fn {var1} -> IO.puts("#{var1} found in a tuple!") {var_2, var_3} -> IO.puts("#{var_2} and #{var_3} found!") end handle_result.({"Hey people"}) handle_result.({"Hello", "World"}) When the above program is run, it produces the following result − Hey people found in a tuple! Hello and World found! We can define functions with names so we can easily refer to them later. Named functions are defined within a module using the def keyword. Named functions are always defined in a module. To call named functions, we need to reference them using their module name. The following is the syntax for named functions − def function_name(argument_1, argument_2) do #code to be executed when function is called end Let us now define our named function sum within the Math module. defmodule Math do def sum(a, b) do a + b end end IO.puts(Math.sum(5, 6)) When running above program, it produces following result − 11 For 1-liner functions, there is a shorthand notation to define these functions, using do:. For example − defmodule Math do def sum(a, b), do: a + b end IO.puts(Math.sum(5, 6)) When running above program, it produces following result − 11 Elixir provides us the ability to define private functions that can be accessed from within the module in which they are defined. To define a private function, use defp instead of def. For example, defmodule Greeter do def hello(name), do: phrase <> name defp phrase, do: "Hello " end Greeter.hello("world") When the above program is run, it produces the following result − Hello world But if we just try to explicitly call phrase function, using the Greeter.phrase() function, it will raise an error. If we want a default value for an argument, we use the argument \\ value syntax − defmodule Greeter do def hello(name, country \\ "en") do phrase(country) <> name end defp phrase("en"), do: "Hello, " defp phrase("es"), do: "Hola, " end Greeter.hello("Ayush", "en") Greeter.hello("Ayush") Greeter.hello("Ayush", "es") When the above program is run, it produces the following result − Hello, Ayush Hello, Ayush Hola, Ayush 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2404, "s": 2182, "text": "A function is a set of statements organized together to perform a specific task. Functions in programming work mostly like function in Math. You give functions some input, they generate output based on the input provided." }, { "code": null, "e": 2447, "s": 2404, "text": "There are 2 types of functions in Elixir −" }, { "code": null, "e": 2623, "s": 2447, "text": "Functions defined using the fn..end construct are anonymous functions. These functions are sometimes also called as lambdas. They are used by assigning them to variable names." }, { "code": null, "e": 2731, "s": 2623, "text": "Functions defined using the def keyword are named functions. These are native functions provided in Elixir." }, { "code": null, "e": 3019, "s": 2731, "text": "Just as the name implies, an anonymous function has no name. These are frequently passed to other functions. To define an anonymous function in Elixir, we need the fn and end keywords. Within these, we can define any number of parameters and function bodies separated by ->. For example," }, { "code": null, "e": 3068, "s": 3019, "text": "sum = fn (a, b) -> a + b end\nIO.puts(sum.(1, 5))" }, { "code": null, "e": 3140, "s": 3068, "text": "When running above program, is run, it generates the following result −" }, { "code": null, "e": 3143, "s": 3140, "text": "6\n" }, { "code": null, "e": 3269, "s": 3143, "text": "Note that these functions are not called like the named functions. We have a '.' between the function name and its arguments." }, { "code": null, "e": 3448, "s": 3269, "text": "We can also define these functions using the capture operator. This is an easier method to create functions. We will now define the above sum function using the capture operator," }, { "code": null, "e": 3486, "s": 3448, "text": "sum = &(&1 + &2) \nIO.puts(sum.(1, 2))" }, { "code": null, "e": 3553, "s": 3486, "text": "When the above program is run, it generates the following result −" }, { "code": null, "e": 3556, "s": 3553, "text": "3\n" }, { "code": null, "e": 3661, "s": 3556, "text": "In the shorthand version, our parameters are not named but are available to us as &1, &2, &3, and so on." }, { "code": null, "e": 3918, "s": 3661, "text": "Pattern matching is not only limited to variables and data structures. We can use pattern matching to make our functions polymorphic. For example, we will declare a function that can either take 1 or 2 inputs (within a tuple) and print them to the console," }, { "code": null, "e": 4118, "s": 3918, "text": "handle_result = fn\n {var1} -> IO.puts(\"#{var1} found in a tuple!\")\n {var_2, var_3} -> IO.puts(\"#{var_2} and #{var_3} found!\")\nend\nhandle_result.({\"Hey people\"})\nhandle_result.({\"Hello\", \"World\"})" }, { "code": null, "e": 4184, "s": 4118, "text": "When the above program is run, it produces the following result −" }, { "code": null, "e": 4237, "s": 4184, "text": "Hey people found in a tuple!\nHello and World found!\n" }, { "code": null, "e": 4501, "s": 4237, "text": "We can define functions with names so we can easily refer to them later. Named functions are defined within a module using the def keyword. Named functions are always defined in a module. To call named functions, we need to reference them using their module name." }, { "code": null, "e": 4551, "s": 4501, "text": "The following is the syntax for named functions −" }, { "code": null, "e": 4649, "s": 4551, "text": "def function_name(argument_1, argument_2) do\n #code to be executed when function is called\nend\n" }, { "code": null, "e": 4714, "s": 4649, "text": "Let us now define our named function sum within the Math module." }, { "code": null, "e": 4800, "s": 4714, "text": "defmodule Math do\n def sum(a, b) do\n a + b\n end\nend\n\nIO.puts(Math.sum(5, 6))" }, { "code": null, "e": 4859, "s": 4800, "text": "When running above program, it produces following result −" }, { "code": null, "e": 4863, "s": 4859, "text": "11\n" }, { "code": null, "e": 4968, "s": 4863, "text": "For 1-liner functions, there is a shorthand notation to define these functions, using do:. For example −" }, { "code": null, "e": 5042, "s": 4968, "text": "defmodule Math do\n def sum(a, b), do: a + b\nend\nIO.puts(Math.sum(5, 6))" }, { "code": null, "e": 5101, "s": 5042, "text": "When running above program, it produces following result −" }, { "code": null, "e": 5105, "s": 5101, "text": "11\n" }, { "code": null, "e": 5304, "s": 5105, "text": "Elixir provides us the ability to define private functions that can be accessed from within the module in which they are defined. To define a private function, use defp instead of def. For example, " }, { "code": null, "e": 5421, "s": 5304, "text": "defmodule Greeter do\n def hello(name), do: phrase <> name\n defp phrase, do: \"Hello \"\nend\n\nGreeter.hello(\"world\")" }, { "code": null, "e": 5487, "s": 5421, "text": "When the above program is run, it produces the following result −" }, { "code": null, "e": 5500, "s": 5487, "text": "Hello world\n" }, { "code": null, "e": 5616, "s": 5500, "text": "But if we just try to explicitly call phrase function, using the Greeter.phrase() function, it will raise an error." }, { "code": null, "e": 5698, "s": 5616, "text": "If we want a default value for an argument, we use the argument \\\\ value syntax −" }, { "code": null, "e": 5953, "s": 5698, "text": "defmodule Greeter do\n def hello(name, country \\\\ \"en\") do\n phrase(country) <> name\n end\n\n defp phrase(\"en\"), do: \"Hello, \"\n defp phrase(\"es\"), do: \"Hola, \"\nend\n\nGreeter.hello(\"Ayush\", \"en\")\nGreeter.hello(\"Ayush\")\nGreeter.hello(\"Ayush\", \"es\")" }, { "code": null, "e": 6019, "s": 5953, "text": "When the above program is run, it produces the following result −" }, { "code": null, "e": 6058, "s": 6019, "text": "Hello, Ayush\nHello, Ayush\nHola, Ayush\n" }, { "code": null, "e": 6091, "s": 6058, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 6111, "s": 6091, "text": " Pranjal Srivastava" }, { "code": null, "e": 6144, "s": 6111, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 6184, "s": 6144, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 6219, "s": 6184, "text": "\n 80 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6239, "s": 6219, "text": " Pranjal Srivastava" }, { "code": null, "e": 6272, "s": 6239, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 6289, "s": 6272, "text": " Mohammad Nauman" }, { "code": null, "e": 6296, "s": 6289, "text": " Print" }, { "code": null, "e": 6307, "s": 6296, "text": " Add Notes" } ]
What are the differences between the TableCellRenderer and TableCellEditor in Java?
A TableCellRenderer creates a component that displays the value of a JTable cell. The default renderer uses JLabel to display the value of each table cell. The TableCellRenderer interface can be specified in two ways : By class of the object to be rendered using table.setDefaultRenderer() method and by a column using tableColumn.setCellRenderer() method and tableColumn.setHeaderRenderer() method for a specific column headers. The TableCellRenderer interface has only one method getTableCellRendererComponent() and this method can return different rendering components based on the value, a cell has the focus or is selected, row and column that can contain the value. A TableCellEditor is an interface and by default, the cells can be editable. A TableCellEditor can be determined by calling isCellEditable() method of a TableModel. If the class of a cell value is Boolean, a JCheckBox can be used. If must double click to put in edit mode, a JTextField can be used. The TableCellEditor interface has only one method getTableCellEditorComponent() and this method can return different editing components based on the value, a cell is selected, row and column that can contain the value. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class TableCellRendererEditorTest extends JFrame { private JTable table; public TableCellRendererEditorTest() { setTitle("TableCellRendererEditor Test"); DefaultTableModel dtm = new DefaultTableModel() { public boolean isCellEditable(int row, int column) { return !(column == 0); } }; dtm.setDataVector(new Object[][]{{"Table Cell Renderer", "Table Cell Editor"}, {"Table Cell Renderer","Table Cell Editor"}}, new Object[]{"Renderer","Editor"}); table = new JTable(dtm); table.getColumn("Editor").setCellRenderer(new TextAreaRenderer()); table.getColumn("Editor").setCellEditor(new TextAreaEditor()); table.setRowHeight(80); JScrollPane spane = new JScrollPane(table); add(spane); setSize(400, 275); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new TableCellRendererEditorTest(); } } class TextAreaRenderer extends JScrollPane implements TableCellRenderer { JTextArea textarea; public TextAreaRenderer() { textarea = new JTextArea(); textarea.setLineWrap(true); textarea.setWrapStyleWord(true); getViewport().add(textarea); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); textarea.setForeground(table.getSelectionForeground()); textarea.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); textarea.setForeground(table.getForeground()); textarea.setBackground(table.getBackground()); } textarea.setText((String) value); textarea.setCaretPosition(0); return this; } } class TextAreaEditor extends DefaultCellEditor { protected JScrollPane scrollpane; protected JTextArea textarea; public TextAreaEditor() { super(new JCheckBox()); scrollpane = new JScrollPane(); textarea = new JTextArea(); textarea.setLineWrap(true); textarea.setWrapStyleWord(true); scrollpane.getViewport().add(textarea); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { textarea.setText((String) value); return scrollpane; } public Object getCellEditorValue() { return textarea.getText(); } }
[ { "code": null, "e": 1144, "s": 1062, "text": "A TableCellRenderer creates a component that displays the value of a JTable cell." }, { "code": null, "e": 1218, "s": 1144, "text": "The default renderer uses JLabel to display the value of each table cell." }, { "code": null, "e": 1492, "s": 1218, "text": "The TableCellRenderer interface can be specified in two ways : By class of the object to be rendered using table.setDefaultRenderer() method and by a column using tableColumn.setCellRenderer() method and tableColumn.setHeaderRenderer() method for a specific column headers." }, { "code": null, "e": 1734, "s": 1492, "text": "The TableCellRenderer interface has only one method getTableCellRendererComponent() and this method can return different rendering components based on the value, a cell has the focus or is selected, row and column that can contain the value." }, { "code": null, "e": 1811, "s": 1734, "text": "A TableCellEditor is an interface and by default, the cells can be editable." }, { "code": null, "e": 1899, "s": 1811, "text": "A TableCellEditor can be determined by calling isCellEditable() method of a TableModel." }, { "code": null, "e": 2033, "s": 1899, "text": "If the class of a cell value is Boolean, a JCheckBox can be used. If must double click to put in edit mode, a JTextField can be used." }, { "code": null, "e": 2252, "s": 2033, "text": "The TableCellEditor interface has only one method getTableCellEditorComponent() and this method can return different editing components based on the value, a cell is selected, row and column that can contain the value." }, { "code": null, "e": 5028, "s": 2252, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\npublic class TableCellRendererEditorTest extends JFrame {\n private JTable table;\n public TableCellRendererEditorTest() {\n setTitle(\"TableCellRendererEditor Test\");\n DefaultTableModel dtm = new DefaultTableModel() {\n public boolean isCellEditable(int row, int column) {\n return !(column == 0);\n }\n };\n dtm.setDataVector(new Object[][]{{\"Table Cell Renderer\", \"Table Cell Editor\"}, {\"Table Cell Renderer\",\"Table Cell Editor\"}}, new Object[]{\"Renderer\",\"Editor\"});\n table = new JTable(dtm);\n table.getColumn(\"Editor\").setCellRenderer(new TextAreaRenderer());\n table.getColumn(\"Editor\").setCellEditor(new TextAreaEditor());\n table.setRowHeight(80);\n JScrollPane spane = new JScrollPane(table);\n add(spane);\n setSize(400, 275);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new TableCellRendererEditorTest();\n }\n}\nclass TextAreaRenderer extends JScrollPane implements TableCellRenderer {\n JTextArea textarea;\n public TextAreaRenderer() {\n textarea = new JTextArea();\n textarea.setLineWrap(true);\n textarea.setWrapStyleWord(true);\n getViewport().add(textarea);\n }\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row, int column) {\n if (isSelected) {\n setForeground(table.getSelectionForeground());\n setBackground(table.getSelectionBackground());\n textarea.setForeground(table.getSelectionForeground());\n textarea.setBackground(table.getSelectionBackground());\n } else {\n setForeground(table.getForeground());\n setBackground(table.getBackground());\n textarea.setForeground(table.getForeground());\n textarea.setBackground(table.getBackground());\n }\n textarea.setText((String) value);\n textarea.setCaretPosition(0);\n return this;\n }\n}\nclass TextAreaEditor extends DefaultCellEditor {\n protected JScrollPane scrollpane;\n protected JTextArea textarea;\n public TextAreaEditor() {\n super(new JCheckBox());\n scrollpane = new JScrollPane();\n textarea = new JTextArea();\n textarea.setLineWrap(true);\n textarea.setWrapStyleWord(true);\n scrollpane.getViewport().add(textarea);\n }\n public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {\n textarea.setText((String) value);\n return scrollpane;\n }\n public Object getCellEditorValue() {\n return textarea.getText();\n }\n}" } ]
jQuery | appendTo() with Examples - GeeksforGeeks
13 Feb, 2019 The appendTo() is an inbuilt method in jQuery that is used to insert HTML element at the end of the selected element.Syntax: $(content).appendTo(selector) Here the element content specifies the content to be inserted.Parameters: It accepts a parameters “selector” which specifies the elements to which content will be appended.Return Value: It returns the modified selected element. <html> <head> <meta charset="utf-8"> <style> #hel { background: lightgreen; display: block; border: 2px solid green; padding: 10px; width: 300px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script> </head> <body> <span>geeks Writer !!!</span> <div id="hel">Hello- </div> <script> $("span").appendTo("#hel"); </script> </body></html> Output: Code #2:In the below code, we are directly appending a “p” element using this method. <html> <head> <meta charset="utf-8"> <style> body{ display: block; width: 250px; height: 100px; border: 2px solid green; padding: 10px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script> </head> <body> <h2>Greetings from gfg !</h2> <div class="container"> <div class="inner"> Hello </div> </div> <script> $( "<p>Everyone !!!</p>").appendTo( ".inner" ); </script> </body></html> Output: jQuery-HTML/CSS JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js 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 change the background color after clicking the button in JavaScript ? How to add options to a select element using jQuery?
[ { "code": null, "e": 40332, "s": 40304, "text": "\n13 Feb, 2019" }, { "code": null, "e": 40457, "s": 40332, "text": "The appendTo() is an inbuilt method in jQuery that is used to insert HTML element at the end of the selected element.Syntax:" }, { "code": null, "e": 40488, "s": 40457, "text": "$(content).appendTo(selector)\n" }, { "code": null, "e": 40716, "s": 40488, "text": "Here the element content specifies the content to be inserted.Parameters: It accepts a parameters “selector” which specifies the elements to which content will be appended.Return Value: It returns the modified selected element." }, { "code": "<html> <head> <meta charset=\"utf-8\"> <style> #hel { background: lightgreen; display: block; border: 2px solid green; padding: 10px; width: 300px; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script> </head> <body> <span>geeks Writer !!!</span> <div id=\"hel\">Hello- </div> <script> $(\"span\").appendTo(\"#hel\"); </script> </body></html>", "e": 41192, "s": 40716, "text": null }, { "code": null, "e": 41200, "s": 41192, "text": "Output:" }, { "code": null, "e": 41286, "s": 41200, "text": "Code #2:In the below code, we are directly appending a “p” element using this method." }, { "code": "<html> <head> <meta charset=\"utf-8\"> <style> body{ display: block; width: 250px; height: 100px; border: 2px solid green; padding: 10px; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script> </head> <body> <h2>Greetings from gfg !</h2> <div class=\"container\"> <div class=\"inner\"> Hello </div> </div> <script> $( \"<p>Everyone !!!</p>\").appendTo( \".inner\" ); </script> </body></html>", "e": 41839, "s": 41286, "text": null }, { "code": null, "e": 41847, "s": 41839, "text": "Output:" }, { "code": null, "e": 41863, "s": 41847, "text": "jQuery-HTML/CSS" }, { "code": null, "e": 41874, "s": 41863, "text": "JavaScript" }, { "code": null, "e": 41881, "s": 41874, "text": "JQuery" }, { "code": null, "e": 41979, "s": 41881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41988, "s": 41979, "text": "Comments" }, { "code": null, "e": 42001, "s": 41988, "text": "Old Comments" }, { "code": null, "e": 42062, "s": 42001, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42107, "s": 42062, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42179, "s": 42107, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42248, "s": 42179, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42275, "s": 42248, "text": "File uploading in React.js" }, { "code": null, "e": 42321, "s": 42275, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 42350, "s": 42321, "text": "Form validation using jQuery" }, { "code": null, "e": 42413, "s": 42350, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 42490, "s": 42413, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Chrome input type=“number” CSS styling
To style input type = number, use the following CSS − input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; } The above shows without a spinner. To show and style a spinner, use input[type=number]::-webkit-inner-spin-button { opacity: 1; } The above shows the following output −
[ { "code": null, "e": 1116, "s": 1062, "text": "To style input type = number, use the following CSS −" }, { "code": null, "e": 1195, "s": 1116, "text": "input[type=number]::-webkit-inner-spin-button {\n -webkit-appearance: none;\n}" }, { "code": null, "e": 1230, "s": 1195, "text": "The above shows without a spinner." }, { "code": null, "e": 1263, "s": 1230, "text": "To show and style a spinner, use" }, { "code": null, "e": 1328, "s": 1263, "text": "input[type=number]::-webkit-inner-spin-button {\n opacity: 1;\n}" }, { "code": null, "e": 1367, "s": 1328, "text": "The above shows the following output −" } ]
Plot the Size of each Group in a Groupby object in Pandas - GeeksforGeeks
31 Aug, 2021 Pandas dataframe.groupby() function is one of the most useful function in the library it splits the data into groups based on columns/conditions and then apply some operations eg. size() which counts the number of entries/rows in each group. The groupby() can also be applied on series. Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)Parameters : by : mapping, function, str, or iterable axis : int, default 0 level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group. group_keys : When calling apply, add group keys to index to identify pieces squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent typeReturns : GroupBy object In the following example, we are going to make use to two libraries seaborn and pandas where seaborn is used for plotting and pandas for reading data. We are going to use the load_dataset() methods from seaborn to load the penguins.csv data set. Python3 # import the moduleimport seaborn as snsdataset = sns.load_dataset('penguins') # displaying the dataprint(dataset.head()) Output : Top five rows of the dataset More information about the data set using the info() method Python3 # display the number of columns and their data typesdataset.info() Output : Info about the dataset We will be grouping the data using the groupby() method according to ‘island’ and plotting it. Plotting using Pandas : Python3 # apply groupby on the island column# plottingdataset.groupby(['island']).size().plot(kind = "bar") Plot of groupby() size using Pandas Plotting using Seaborn Python3 # use the groupby() function to group island column# and apply size() function# size() is equivalent to counting the distinct rowsresult = dataset.groupby(['island']).size() # plot the resultsns.barplot(x = result.index, y = result.values) Plot of size using Seaborn gulshankumarar231 Python pandas-groupby Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24188, "s": 23901, "text": "Pandas dataframe.groupby() function is one of the most useful function in the library it splits the data into groups based on columns/conditions and then apply some operations eg. size() which counts the number of entries/rows in each group. The groupby() can also be applied on series." }, { "code": null, "e": 25049, "s": 24188, "text": "Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)Parameters : by : mapping, function, str, or iterable axis : int, default 0 level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group. group_keys : When calling apply, add group keys to index to identify pieces squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent typeReturns : GroupBy object " }, { "code": null, "e": 25295, "s": 25049, "text": "In the following example, we are going to make use to two libraries seaborn and pandas where seaborn is used for plotting and pandas for reading data. We are going to use the load_dataset() methods from seaborn to load the penguins.csv data set." }, { "code": null, "e": 25303, "s": 25295, "text": "Python3" }, { "code": "# import the moduleimport seaborn as snsdataset = sns.load_dataset('penguins') # displaying the dataprint(dataset.head())", "e": 25426, "s": 25303, "text": null }, { "code": null, "e": 25435, "s": 25426, "text": "Output :" }, { "code": null, "e": 25464, "s": 25435, "text": "Top five rows of the dataset" }, { "code": null, "e": 25524, "s": 25464, "text": "More information about the data set using the info() method" }, { "code": null, "e": 25532, "s": 25524, "text": "Python3" }, { "code": "# display the number of columns and their data typesdataset.info()", "e": 25599, "s": 25532, "text": null }, { "code": null, "e": 25609, "s": 25599, "text": "Output : " }, { "code": null, "e": 25632, "s": 25609, "text": "Info about the dataset" }, { "code": null, "e": 25727, "s": 25632, "text": "We will be grouping the data using the groupby() method according to ‘island’ and plotting it." }, { "code": null, "e": 25752, "s": 25727, "text": "Plotting using Pandas : " }, { "code": null, "e": 25760, "s": 25752, "text": "Python3" }, { "code": "# apply groupby on the island column# plottingdataset.groupby(['island']).size().plot(kind = \"bar\")", "e": 25860, "s": 25760, "text": null }, { "code": null, "e": 25897, "s": 25860, "text": "Plot of groupby() size using Pandas " }, { "code": null, "e": 25921, "s": 25897, "text": "Plotting using Seaborn " }, { "code": null, "e": 25929, "s": 25921, "text": "Python3" }, { "code": "# use the groupby() function to group island column# and apply size() function# size() is equivalent to counting the distinct rowsresult = dataset.groupby(['island']).size() # plot the resultsns.barplot(x = result.index, y = result.values)", "e": 26169, "s": 25929, "text": null }, { "code": null, "e": 26197, "s": 26169, "text": "Plot of size using Seaborn " }, { "code": null, "e": 26215, "s": 26197, "text": "gulshankumarar231" }, { "code": null, "e": 26237, "s": 26215, "text": "Python pandas-groupby" }, { "code": null, "e": 26251, "s": 26237, "text": "Python-pandas" }, { "code": null, "e": 26258, "s": 26251, "text": "Python" }, { "code": null, "e": 26356, "s": 26258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26365, "s": 26356, "text": "Comments" }, { "code": null, "e": 26378, "s": 26365, "text": "Old Comments" }, { "code": null, "e": 26410, "s": 26378, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26466, "s": 26410, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26508, "s": 26466, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26550, "s": 26508, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26586, "s": 26550, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26608, "s": 26586, "text": "Defaultdict in Python" }, { "code": null, "e": 26647, "s": 26608, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26674, "s": 26647, "text": "Python Classes and Objects" }, { "code": null, "e": 26705, "s": 26674, "text": "Python | os.path.join() method" } ]
MATLAB - Addition & Subtraction of Matrices
You can add or subtract matrices. Both the operand matrices must have the same number of rows and columns. Create a script file with the following code − a = [ 1 2 3 ; 4 5 6; 7 8 9]; b = [ 7 5 6 ; 2 0 8; 5 7 1]; c = a + b d = a - b When you run the file, it displays the following result − c = 8 7 9 6 5 14 12 15 10 d = -6 -3 -3 2 5 -2 2 1 8 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2248, "s": 2141, "text": "You can add or subtract matrices. Both the operand matrices must have the same number of rows and columns." }, { "code": null, "e": 2295, "s": 2248, "text": "Create a script file with the following code −" }, { "code": null, "e": 2373, "s": 2295, "text": "a = [ 1 2 3 ; 4 5 6; 7 8 9];\nb = [ 7 5 6 ; 2 0 8; 5 7 1];\nc = a + b\nd = a - b" }, { "code": null, "e": 2431, "s": 2373, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 2562, "s": 2431, "text": "c =\n 8 7 9\n 6 5 14\n 12 15 10\nd =\n -6 -3 -3\n 2 5 -2\n 2 1 8\n" }, { "code": null, "e": 2595, "s": 2562, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 2608, "s": 2595, "text": " Nouman Azam" }, { "code": null, "e": 2643, "s": 2608, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 2656, "s": 2643, "text": " Nouman Azam" }, { "code": null, "e": 2689, "s": 2656, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 2698, "s": 2689, "text": " Sanjeev" }, { "code": null, "e": 2731, "s": 2698, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 2747, "s": 2731, "text": " TELCOMA Global" }, { "code": null, "e": 2780, "s": 2747, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 2796, "s": 2780, "text": " TELCOMA Global" }, { "code": null, "e": 2829, "s": 2796, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 2846, "s": 2829, "text": " Phinite Academy" }, { "code": null, "e": 2853, "s": 2846, "text": " Print" }, { "code": null, "e": 2864, "s": 2853, "text": " Add Notes" } ]
Graph Theory | Center of a Tree. Let’s see how we can find the center of... | by Kelvin Jose | Towards Data Science
Welcome back all. We’re here at the 9th post of this series called Graph Theory: Go Hero. Go and check out the index page for previous posts. I try to update it every weekend. Let’s see how we can find the center of a tree. Finding the center of a tree is a handy algorithm to know because we see it very often in the subroutine of other algorithms and also it’s a useful way of selecting the root node when we are rooting a tree. One thing to keep in mind is that trees could have more than one center but not more than two. Note that the center is always the middle vertex or middle two vertices in every longest path along the tree. For example, the orange-coloured path in the above image is the longest path and the red node is considered to be the center among them. If we repeat the process and choose another possible long path, the center would stay the same. Another approach to finding the center is to iteratively pick off each leaf node like peel an onion. So, we start from the outskirt and end up in the center - gradually. The nodes with a horizontal line in the middle are the leaves in our example. If we calculate the degree of these nodes, Degree of a node is the number of nodes it is connected to. it would be 1, for sure. Because each all of these leaf nodes are connected to exactly one node. All other nodes would also get affected as we prune the leaves i.e. nodes’ degree would start to decrease. As we can see in the above image, our graph would start to loose it’s leaves iteratively until we find the center of it. Remember, we might either find a center or centers. Let’s now look at some pseudo code. function treeCenters(g): n = g.numberOfNodes() degree = [0] * n leaves = [] for(i=0; i<n; i++): if degree[i] == 0 or degree[i] == 1: leaves.add(i) degree[i] = 0 count = leaves.size() while count < n: new_leaves = [] for node in leaves: for neighbor in g[node]: degree[neighbor] = degree[neighbor] - 1 if degree[neighbor] == 1: new_leaves.add(neighbor) count += new_leaves.size() leaves = new_leaves The parameter g to the function treeCenters() is an undirected graph. Variable n represents the number of nodes in our tree. We have defined two arrays, degree and leaves. The former has the size of n and stores the degree of each node in the tree, the latter keeps the most recent layer of leaf nodes. Then we are entering into a loop where we calculate the degree of every nodes of the graph, also we check whether we are considering a tree with single node or it’s a leaf node. If either of these conditions is true, we add the entry into the leaves array and mark its value in degrees array as 0 - because we don’t have to visit the node again. The variable count is going to keep track of the number of nodes we have processed so far. We then continuously check for leaves and prune them. We would end up having the center of the tree, at last. That’s pretty easy, right? We will discuss identifying isomorphic trees in the next post. Stay tuned until then.
[ { "code": null, "e": 396, "s": 172, "text": "Welcome back all. We’re here at the 9th post of this series called Graph Theory: Go Hero. Go and check out the index page for previous posts. I try to update it every weekend. Let’s see how we can find the center of a tree." }, { "code": null, "e": 603, "s": 396, "text": "Finding the center of a tree is a handy algorithm to know because we see it very often in the subroutine of other algorithms and also it’s a useful way of selecting the root node when we are rooting a tree." }, { "code": null, "e": 698, "s": 603, "text": "One thing to keep in mind is that trees could have more than one center but not more than two." }, { "code": null, "e": 808, "s": 698, "text": "Note that the center is always the middle vertex or middle two vertices in every longest path along the tree." }, { "code": null, "e": 1041, "s": 808, "text": "For example, the orange-coloured path in the above image is the longest path and the red node is considered to be the center among them. If we repeat the process and choose another possible long path, the center would stay the same." }, { "code": null, "e": 1142, "s": 1041, "text": "Another approach to finding the center is to iteratively pick off each leaf node like peel an onion." }, { "code": null, "e": 1211, "s": 1142, "text": "So, we start from the outskirt and end up in the center - gradually." }, { "code": null, "e": 1332, "s": 1211, "text": "The nodes with a horizontal line in the middle are the leaves in our example. If we calculate the degree of these nodes," }, { "code": null, "e": 1392, "s": 1332, "text": "Degree of a node is the number of nodes it is connected to." }, { "code": null, "e": 1596, "s": 1392, "text": "it would be 1, for sure. Because each all of these leaf nodes are connected to exactly one node. All other nodes would also get affected as we prune the leaves i.e. nodes’ degree would start to decrease." }, { "code": null, "e": 1769, "s": 1596, "text": "As we can see in the above image, our graph would start to loose it’s leaves iteratively until we find the center of it. Remember, we might either find a center or centers." }, { "code": null, "e": 1805, "s": 1769, "text": "Let’s now look at some pseudo code." }, { "code": null, "e": 2343, "s": 1805, "text": "function treeCenters(g): n = g.numberOfNodes() degree = [0] * n leaves = [] for(i=0; i<n; i++): if degree[i] == 0 or degree[i] == 1: leaves.add(i) degree[i] = 0 count = leaves.size() while count < n: new_leaves = [] for node in leaves: for neighbor in g[node]: degree[neighbor] = degree[neighbor] - 1 if degree[neighbor] == 1: new_leaves.add(neighbor) count += new_leaves.size() leaves = new_leaves" }, { "code": null, "e": 3193, "s": 2343, "text": "The parameter g to the function treeCenters() is an undirected graph. Variable n represents the number of nodes in our tree. We have defined two arrays, degree and leaves. The former has the size of n and stores the degree of each node in the tree, the latter keeps the most recent layer of leaf nodes. Then we are entering into a loop where we calculate the degree of every nodes of the graph, also we check whether we are considering a tree with single node or it’s a leaf node. If either of these conditions is true, we add the entry into the leaves array and mark its value in degrees array as 0 - because we don’t have to visit the node again. The variable count is going to keep track of the number of nodes we have processed so far. We then continuously check for leaves and prune them. We would end up having the center of the tree, at last." }, { "code": null, "e": 3220, "s": 3193, "text": "That’s pretty easy, right?" } ]
Header files in C/C++ and its uses - GeeksforGeeks
21 Apr, 2022 C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. Your request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a ‘.h’ an extension. By including a header file, we can use its contents in our program.C++ also offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the “.h” extension but in C, all the header files must necessarily end with the “.h” extension. A header file contains: Function definitionsData type definitionsMacros Function definitions Data type definitions Macros It offers the above features by importing them into the program with the help of a preprocessor directive “#include”. These preprocessor directives are used for instructing compiler that these files need to be processed before compilation. In C program should necessarily contain the header file which stands for standard input and output used to take input with the help of scanf() and printf() function respectively. In C++ program has the header file which stands for input and output stream used to take input with the help of “cin” and “cout” respectively. There are of 2 types of header file: Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them.User-defined header files: These files are defined by the user and can be imported using “#include”. Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them. User-defined header files: These files are defined by the user and can be imported using “#include”. Syntax: #include <filename.h> or #include "filename.h" We can include header files in our program by using one of the above two syntax whether it is pre-defined or user-defined header file. The “#include” preprocessor is responsible for directing the compiler that the header file needs to be processed before compilation and includes all the necessary data type and function definitions.Note: We can’t include the same header file twice in any program.Create your own Header File: Instead of writing a large and complex code, we can create your own header files and include them in our program to use it whenever we want. It enhances code functionality and readability. Below are the steps to create our own header file: Write your own C/C++ code and save that file with “.h” extension. Below is the illustration of header file: Write your own C/C++ code and save that file with “.h” extension. Below is the illustration of header file: CPP // Function to find the sum of two// numbers passedint sumOfTwoNumbers(int a, int b){ return (a + b);} Include your header file with “#include” in your C/C++ program as shown below: Include your header file with “#include” in your C/C++ program as shown below: CPP // C++ program to find the sum of two// numbers using function declared in// header file#include "iostream" // Including header file#include "sum.h"using namespace std; // Driver Codeint main(){ // Given two numbers int a = 13, b = 22; // Function declared in header // file to find the sum cout << "Sum is: " << sumOfTwoNumbers(a, b) << endl;} Below is the output of the above program: The output of the above program. Including Multiple Header Files: You can use various header files in a program. When a header file is included twice within a program, the compiler processes the contents of that header file twice. This leads to an error in the program. To eliminate this error, conditional preprocessor directives are used. Syntax: #ifndef HEADER_FILE_NAME #define HEADER_FILE_NAME the entire header file #endif This construct is called wrapper “#ifndef”. When the header is included again, the conditional will become false, because HEADER_FILE_NAME is defined. The preprocessor will skip over the entire contents of the file and the compiler will not see it twice. Sometimes it’s essential to include several diverse header files based on the requirements of the program. For this, multiple conditionals are used.Syntax: #if SYSTEM_ONE #include "system1.h" #elif SYSTEM_TWO #include "system2.h" #elif SYSTEM_THREE .... #endif Standard Header Files And Their Uses: #include<stdio.h>: It is used to perform input and output operations using functions scanf() and printf().#include<iostream>: It is used as a stream of Input and Output using cin and cout.#include<string.h>: It is used to perform various functionalities related to string manipulation like strlen(), strcmp(), strcpy(), size(), etc.#include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(), etc.#include<iomanip.h>: It is used to access set() and setprecision() function to limit the decimal places in variables.#include<signal.h>: It is used to perform signal handling functions like signal() and raise().#include<stdarg.h>:It is used to perform standard argument functions like va_start() and va_arg(). It is also used to indicate start of the variable-length argument list and to fetch the arguments from the variable-length argument list in the program respectively.#include<errno.h>: It is used to perform error handling operations like errno(), strerror(), perror(), etc.#include<fstream.h>: It is used to control the data to read from a file as an input and data to write into the file as an output.#include<time.h>: It is used to perform functions related to date() and time() like setdate() and getdate(). It is also used to modify the system date and get the CPU time respectively.#include<float.h>: It contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making programs more portable. Some examples of constants included in this header file are- e(exponent), b(base/radix), etc.#include<limits.h>: It determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int, and long. These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255.#include<assert.h>: It contains information for adding diagnostics that aid program debugging.#include<ctype.h>: It contains function prototypes for functions that test characters for certain properties , and also function prototypes for functions that can be used to convert uppercase letters to lowercase letters and vice versa.#include<locale.h>: It contains function prototypes and other information that enables a program to be modified for the current locale on which it’s running. It enable sthe computer system to handle different conventions for expressing data such as times, dates or large numbers throughout the world.#include<setjmp.h>: It contains function prototypes for functions that allow bypassing of the usual function call and return sequence.#include<stddef.h>: It contains common type definitions used by C for performing calculations. #include<stdio.h>: It is used to perform input and output operations using functions scanf() and printf(). #include<iostream>: It is used as a stream of Input and Output using cin and cout. #include<string.h>: It is used to perform various functionalities related to string manipulation like strlen(), strcmp(), strcpy(), size(), etc. #include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(), etc. #include<iomanip.h>: It is used to access set() and setprecision() function to limit the decimal places in variables. #include<signal.h>: It is used to perform signal handling functions like signal() and raise(). #include<stdarg.h>:It is used to perform standard argument functions like va_start() and va_arg(). It is also used to indicate start of the variable-length argument list and to fetch the arguments from the variable-length argument list in the program respectively. #include<errno.h>: It is used to perform error handling operations like errno(), strerror(), perror(), etc. #include<fstream.h>: It is used to control the data to read from a file as an input and data to write into the file as an output. #include<time.h>: It is used to perform functions related to date() and time() like setdate() and getdate(). It is also used to modify the system date and get the CPU time respectively. #include<float.h>: It contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making programs more portable. Some examples of constants included in this header file are- e(exponent), b(base/radix), etc. #include<limits.h>: It determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int, and long. These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255. #include<assert.h>: It contains information for adding diagnostics that aid program debugging. #include<ctype.h>: It contains function prototypes for functions that test characters for certain properties , and also function prototypes for functions that can be used to convert uppercase letters to lowercase letters and vice versa. #include<locale.h>: It contains function prototypes and other information that enables a program to be modified for the current locale on which it’s running. It enable sthe computer system to handle different conventions for expressing data such as times, dates or large numbers throughout the world. #include<setjmp.h>: It contains function prototypes for functions that allow bypassing of the usual function call and return sequence. #include<stddef.h>: It contains common type definitions used by C for performing calculations. Below is the program to illustrate the use of header file: C // C program to illustrate the use of// header file in C#include <math.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver Codeint main(){ char s1[20] = "12345"; char s2[10] = "Geeks"; char s3[10] = "ForGeeks"; long int res; // Find the value of 9^3 using a // function in math.h library res = pow(9, 3); printf("Using math.h, " "The value is: %ld\n", res); // Convert a string to long long int // using a function in stdlib.h library long int a = atol(s1); printf("Using stdlib.h, the string"); printf(" to long int: %ld\n", a); // Copy the string s3 into s2 using // using a function in string.h library strcpy(s2, s3); printf("Using string.h, the strings" " s2 and s3: %s %s\n", s2, s3); return 0;} abhishek0719kadiyan ashishsingh13122000 Picked C Programs C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C C++ Program for QuickSort C++ program for hashing with chaining Sorting a Map by value in C++ STL cin in C++ delete keyword in C++
[ { "code": null, "e": 24495, "s": 24467, "text": "\n21 Apr, 2022" }, { "code": null, "e": 25170, "s": 24495, "text": "C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. Your request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a ‘.h’ an extension. By including a header file, we can use its contents in our program.C++ also offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the “.h” extension but in C, all the header files must necessarily end with the “.h” extension. A header file contains: " }, { "code": null, "e": 25218, "s": 25170, "text": "Function definitionsData type definitionsMacros" }, { "code": null, "e": 25239, "s": 25218, "text": "Function definitions" }, { "code": null, "e": 25261, "s": 25239, "text": "Data type definitions" }, { "code": null, "e": 25268, "s": 25261, "text": "Macros" }, { "code": null, "e": 25869, "s": 25268, "text": "It offers the above features by importing them into the program with the help of a preprocessor directive “#include”. These preprocessor directives are used for instructing compiler that these files need to be processed before compilation. In C program should necessarily contain the header file which stands for standard input and output used to take input with the help of scanf() and printf() function respectively. In C++ program has the header file which stands for input and output stream used to take input with the help of “cin” and “cout” respectively. There are of 2 types of header file: " }, { "code": null, "e": 26077, "s": 25869, "text": "Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them.User-defined header files: These files are defined by the user and can be imported using “#include”." }, { "code": null, "e": 26185, "s": 26077, "text": "Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them." }, { "code": null, "e": 26286, "s": 26185, "text": "User-defined header files: These files are defined by the user and can be imported using “#include”." }, { "code": null, "e": 26296, "s": 26286, "text": "Syntax: " }, { "code": null, "e": 26343, "s": 26296, "text": "#include <filename.h>\nor\n#include \"filename.h\"" }, { "code": null, "e": 27011, "s": 26343, "text": "We can include header files in our program by using one of the above two syntax whether it is pre-defined or user-defined header file. The “#include” preprocessor is responsible for directing the compiler that the header file needs to be processed before compilation and includes all the necessary data type and function definitions.Note: We can’t include the same header file twice in any program.Create your own Header File: Instead of writing a large and complex code, we can create your own header files and include them in our program to use it whenever we want. It enhances code functionality and readability. Below are the steps to create our own header file: " }, { "code": null, "e": 27121, "s": 27011, "text": "Write your own C/C++ code and save that file with “.h” extension. Below is the illustration of header file: " }, { "code": null, "e": 27231, "s": 27121, "text": "Write your own C/C++ code and save that file with “.h” extension. Below is the illustration of header file: " }, { "code": null, "e": 27235, "s": 27231, "text": "CPP" }, { "code": "// Function to find the sum of two// numbers passedint sumOfTwoNumbers(int a, int b){ return (a + b);}", "e": 27341, "s": 27235, "text": null }, { "code": null, "e": 27422, "s": 27341, "text": "Include your header file with “#include” in your C/C++ program as shown below: " }, { "code": null, "e": 27503, "s": 27422, "text": "Include your header file with “#include” in your C/C++ program as shown below: " }, { "code": null, "e": 27507, "s": 27503, "text": "CPP" }, { "code": "// C++ program to find the sum of two// numbers using function declared in// header file#include \"iostream\" // Including header file#include \"sum.h\"using namespace std; // Driver Codeint main(){ // Given two numbers int a = 13, b = 22; // Function declared in header // file to find the sum cout << \"Sum is: \" << sumOfTwoNumbers(a, b) << endl;}", "e": 27885, "s": 27507, "text": null }, { "code": null, "e": 27929, "s": 27885, "text": "Below is the output of the above program: " }, { "code": null, "e": 27962, "s": 27929, "text": "The output of the above program." }, { "code": null, "e": 28280, "s": 27962, "text": "Including Multiple Header Files: You can use various header files in a program. When a header file is included twice within a program, the compiler processes the contents of that header file twice. This leads to an error in the program. To eliminate this error, conditional preprocessor directives are used. Syntax: " }, { "code": null, "e": 28365, "s": 28280, "text": "#ifndef HEADER_FILE_NAME\n#define HEADER_FILE_NAME\n\n the entire header file\n\n#endif" }, { "code": null, "e": 28778, "s": 28365, "text": "This construct is called wrapper “#ifndef”. When the header is included again, the conditional will become false, because HEADER_FILE_NAME is defined. The preprocessor will skip over the entire contents of the file and the compiler will not see it twice. Sometimes it’s essential to include several diverse header files based on the requirements of the program. For this, multiple conditionals are used.Syntax: " }, { "code": null, "e": 28902, "s": 28778, "text": "#if SYSTEM_ONE\n #include \"system1.h\"\n#elif SYSTEM_TWO\n #include \"system2.h\"\n#elif SYSTEM_THREE\n ....\n#endif" }, { "code": null, "e": 28942, "s": 28902, "text": "Standard Header Files And Their Uses: " }, { "code": null, "e": 31754, "s": 28942, "text": "#include<stdio.h>: It is used to perform input and output operations using functions scanf() and printf().#include<iostream>: It is used as a stream of Input and Output using cin and cout.#include<string.h>: It is used to perform various functionalities related to string manipulation like strlen(), strcmp(), strcpy(), size(), etc.#include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(), etc.#include<iomanip.h>: It is used to access set() and setprecision() function to limit the decimal places in variables.#include<signal.h>: It is used to perform signal handling functions like signal() and raise().#include<stdarg.h>:It is used to perform standard argument functions like va_start() and va_arg(). It is also used to indicate start of the variable-length argument list and to fetch the arguments from the variable-length argument list in the program respectively.#include<errno.h>: It is used to perform error handling operations like errno(), strerror(), perror(), etc.#include<fstream.h>: It is used to control the data to read from a file as an input and data to write into the file as an output.#include<time.h>: It is used to perform functions related to date() and time() like setdate() and getdate(). It is also used to modify the system date and get the CPU time respectively.#include<float.h>: It contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making programs more portable. Some examples of constants included in this header file are- e(exponent), b(base/radix), etc.#include<limits.h>: It determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int, and long. These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255.#include<assert.h>: It contains information for adding diagnostics that aid program debugging.#include<ctype.h>: It contains function prototypes for functions that test characters for certain properties , and also function prototypes for functions that can be used to convert uppercase letters to lowercase letters and vice versa.#include<locale.h>: It contains function prototypes and other information that enables a program to be modified for the current locale on which it’s running. It enable sthe computer system to handle different conventions for expressing data such as times, dates or large numbers throughout the world.#include<setjmp.h>: It contains function prototypes for functions that allow bypassing of the usual function call and return sequence.#include<stddef.h>: It contains common type definitions used by C for performing calculations." }, { "code": null, "e": 31861, "s": 31754, "text": "#include<stdio.h>: It is used to perform input and output operations using functions scanf() and printf()." }, { "code": null, "e": 31944, "s": 31861, "text": "#include<iostream>: It is used as a stream of Input and Output using cin and cout." }, { "code": null, "e": 32089, "s": 31944, "text": "#include<string.h>: It is used to perform various functionalities related to string manipulation like strlen(), strcmp(), strcpy(), size(), etc." }, { "code": null, "e": 32186, "s": 32089, "text": "#include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(), etc." }, { "code": null, "e": 32304, "s": 32186, "text": "#include<iomanip.h>: It is used to access set() and setprecision() function to limit the decimal places in variables." }, { "code": null, "e": 32399, "s": 32304, "text": "#include<signal.h>: It is used to perform signal handling functions like signal() and raise()." }, { "code": null, "e": 32664, "s": 32399, "text": "#include<stdarg.h>:It is used to perform standard argument functions like va_start() and va_arg(). It is also used to indicate start of the variable-length argument list and to fetch the arguments from the variable-length argument list in the program respectively." }, { "code": null, "e": 32772, "s": 32664, "text": "#include<errno.h>: It is used to perform error handling operations like errno(), strerror(), perror(), etc." }, { "code": null, "e": 32902, "s": 32772, "text": "#include<fstream.h>: It is used to control the data to read from a file as an input and data to write into the file as an output." }, { "code": null, "e": 33088, "s": 32902, "text": "#include<time.h>: It is used to perform functions related to date() and time() like setdate() and getdate(). It is also used to modify the system date and get the CPU time respectively." }, { "code": null, "e": 33375, "s": 33088, "text": "#include<float.h>: It contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making programs more portable. Some examples of constants included in this header file are- e(exponent), b(base/radix), etc." }, { "code": null, "e": 33719, "s": 33375, "text": "#include<limits.h>: It determines various properties of the various variable types. The macros defined in this header, limits the values of various variable types like char, int, and long. These limits specify that a variable cannot store any value beyond these limits, for example an unsigned character can store up to a maximum value of 255." }, { "code": null, "e": 33814, "s": 33719, "text": "#include<assert.h>: It contains information for adding diagnostics that aid program debugging." }, { "code": null, "e": 34051, "s": 33814, "text": "#include<ctype.h>: It contains function prototypes for functions that test characters for certain properties , and also function prototypes for functions that can be used to convert uppercase letters to lowercase letters and vice versa." }, { "code": null, "e": 34352, "s": 34051, "text": "#include<locale.h>: It contains function prototypes and other information that enables a program to be modified for the current locale on which it’s running. It enable sthe computer system to handle different conventions for expressing data such as times, dates or large numbers throughout the world." }, { "code": null, "e": 34487, "s": 34352, "text": "#include<setjmp.h>: It contains function prototypes for functions that allow bypassing of the usual function call and return sequence." }, { "code": null, "e": 34582, "s": 34487, "text": "#include<stddef.h>: It contains common type definitions used by C for performing calculations." }, { "code": null, "e": 34642, "s": 34582, "text": "Below is the program to illustrate the use of header file: " }, { "code": null, "e": 34644, "s": 34642, "text": "C" }, { "code": "// C program to illustrate the use of// header file in C#include <math.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // Driver Codeint main(){ char s1[20] = \"12345\"; char s2[10] = \"Geeks\"; char s3[10] = \"ForGeeks\"; long int res; // Find the value of 9^3 using a // function in math.h library res = pow(9, 3); printf(\"Using math.h, \" \"The value is: %ld\\n\", res); // Convert a string to long long int // using a function in stdlib.h library long int a = atol(s1); printf(\"Using stdlib.h, the string\"); printf(\" to long int: %ld\\n\", a); // Copy the string s3 into s2 using // using a function in string.h library strcpy(s2, s3); printf(\"Using string.h, the strings\" \" s2 and s3: %s %s\\n\", s2, s3); return 0;}", "e": 35461, "s": 34644, "text": null }, { "code": null, "e": 35481, "s": 35461, "text": "abhishek0719kadiyan" }, { "code": null, "e": 35501, "s": 35481, "text": "ashishsingh13122000" }, { "code": null, "e": 35508, "s": 35501, "text": "Picked" }, { "code": null, "e": 35519, "s": 35508, "text": "C Programs" }, { "code": null, "e": 35532, "s": 35519, "text": "C++ Programs" }, { "code": null, "e": 35630, "s": 35532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35639, "s": 35630, "text": "Comments" }, { "code": null, "e": 35652, "s": 35639, "text": "Old Comments" }, { "code": null, "e": 35693, "s": 35652, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 35724, "s": 35693, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 35765, "s": 35724, "text": "C program to find the length of a string" }, { "code": null, "e": 35799, "s": 35765, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 35852, "s": 35799, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 35878, "s": 35852, "text": "C++ Program for QuickSort" }, { "code": null, "e": 35916, "s": 35878, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 35950, "s": 35916, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 35961, "s": 35950, "text": "cin in C++" } ]
Java Program to write int array to a file
Here’s our file − FileWriter writer = new FileWriter("E:/demo.txt"); Now, consider an Integer array − Integer arr[] = { 10, 20, 30, 40, 50 }; Write the above array to the file “demo.txt” − int len = arr.length; for (int i = 0; i < len; i++) { writer.write(arr[i] + "\t" + ""); } The following is an example. Here, our file is “E:/input.txt” − import java.io.FileWriter; public class Demo { public static void main(String[] argv) throws Exception { FileWriter writer = new FileWriter("E:/input.txt"); Integer arr[] = { 10, 20, 30, 40, 50 }; int len = arr.length; for (int i = 0; i < len; i++) { writer.write(arr[i] + "\t"+ ""); } writer.close(); } } The output is as follows i.e. the text in the file is − 1020304050
[ { "code": null, "e": 1080, "s": 1062, "text": "Here’s our file −" }, { "code": null, "e": 1131, "s": 1080, "text": "FileWriter writer = new FileWriter(\"E:/demo.txt\");" }, { "code": null, "e": 1164, "s": 1131, "text": "Now, consider an Integer array −" }, { "code": null, "e": 1204, "s": 1164, "text": "Integer arr[] = { 10, 20, 30, 40, 50 };" }, { "code": null, "e": 1251, "s": 1204, "text": "Write the above array to the file “demo.txt” −" }, { "code": null, "e": 1344, "s": 1251, "text": "int len = arr.length;\nfor (int i = 0; i < len; i++) {\n writer.write(arr[i] + \"\\t\" + \"\");\n}" }, { "code": null, "e": 1408, "s": 1344, "text": "The following is an example. Here, our file is “E:/input.txt” −" }, { "code": null, "e": 1765, "s": 1408, "text": "import java.io.FileWriter;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n FileWriter writer = new FileWriter(\"E:/input.txt\");\n Integer arr[] = { 10, 20, 30, 40, 50 };\n int len = arr.length;\n for (int i = 0; i < len; i++) {\n writer.write(arr[i] + \"\\t\"+ \"\");\n }\n writer.close();\n }\n}" }, { "code": null, "e": 1821, "s": 1765, "text": "The output is as follows i.e. the text in the file is −" }, { "code": null, "e": 1832, "s": 1821, "text": "1020304050" } ]
All the Pandas shift() you should know for data analysis | by B. Chen | Towards Data Science
Suppose you encountered a situation where you need to push all rows in a DataFrame or require to use the previous row in a DataFrame. Maybe you want to calculate the difference in consecutive rows, Pandas shift() would be an ideal way to achieve these objectives. In this article, we’ll be going through some examples of manipulating data using Pandas shift() function. We will focus on practical problems and should help you get started with data analysis. Shifting values with periodsShifting time-series data with freqA practical example: calculating the difference in consecutive rowsA practical example: calculating the 7 days difference for time-series data Shifting values with periods Shifting time-series data with freq A practical example: calculating the difference in consecutive rows A practical example: calculating the 7 days difference for time-series data Please check out Notebook for the source code. Pandas shift() shift index by the desired number of periods. The simplest call should have an argument periods (It defaults to 1) and it represents the number of shifts for the desired axis. And by default, it is shifting values vertically along the axis 0 . NaN will be filled for missing values introduced as a result of the shifting. Let’s see how this works with the help of an example. df = pd.DataFrame({ "A": [1, 2, 3, 4, 5], "B": [10, 20, 30, 40, 50]}) To shift index by 1 row vertically df.shift(periods=1)# You can do below insteaddf.shift(1) To replace NaN , you can use the argument fill_value , for example, replace NaN with 0 df.shift(periods=1, fill_value=0) In addition, you can pass a negative number to periods and it will shift values in the oppositive direction. To shift values horizontally, you can set axis=1 df.shift(periods=1, axis=1) Pandas shift() function has an argument called freq which allows you to do the frequency-based shifting. The Pandas shift() function is beneficial when dealing with time-series data. In order to use the argument freq, you need to make sure the index of DataFrame is date or datetime, otherwise, it will raise a NotImplementedError. Let’s see how this works with the help of an example. df = pd.DataFrame({ "A": [1, 2, 3, 4, 5], "B": [10, 20, 30, 40, 50] }, index=pd.date_range("2020-01-01", freq='D', periods=5)) To shift the index by 10 days. df.shift(freq='10D')# The equivalentdf.shift(periods=10, freq='D') You will get the following result if run with periods only. Certainly, that isn’t what we want. Suppose you need to use the previous row value to calculate the sales change, Pandas shift() would be a way to achieve this task. df = pd.DataFrame({ "date": pd.date_range("2020-01-01", freq='D', periods=5), "sales": [22, 30, 32, 25, 42]}) To calculate the sales change in consecutive rows. df['diff'] = df['sales'] - df.shift(1)['sales'] This function is beneficial when dealing with time-series data. Let’s take a look at another practical example. Now, suppose you have been asked to calculate the 7 days sales change as follows value_1 = Day_8 - Day_1value_2 = Day_9 - Day_2value_3 = Day_10 - Day_3...value_n = Day_N - Day_N-7 Pandas shift() with the argument freq would be an ideal way to achieve this task. Let’s use read_csv() with the argument parse_dates and index_col to load data into a DataFrame. df = pd.read_csv( 'data/sales.csv', parse_dates=['date'], index_col=['date'],) Notice that the record for “2020–01–08” is missing in the DataFrame. By running df.shift(freq='7D') , you should get a result with a record for “2020–01–08”. Then, to calculate the 7 days sales change: the_7_days_diff = df['sales'] - df.shift(freq='7D')['sales'] Notice that There is a record for “2020–01–08” in the result The value of “2020–01–08” is NaN because df doesn’t have this value Values for the date from “2020–01–01” to “2020–01–07” are NaN. This is because df.shift(freq='7D') doesn’t have these values. The last 6 records are NaN because df doesn’t have these values Pandas shift() function can be very useful when you need to push all rows in a DataFrame or require to use the previous row in a DataFrame. The function is beneficial when dealing with time-series data, as shown in the above examples. I hope this article will help you to save time in analyzing data. I recommend you to check out the documentation for the shift() API and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. Using Pandas method chaining to improve code readability How to do a Custom Sort on Pandas DataFrame When to use Pandas transform() function Pandas concat() tricks you should know Difference between apply() and transform() in Pandas All the Pandas merge() you should know Working with datetime in Pandas DataFrame Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More tutorials can be found on my Github
[ { "code": null, "e": 436, "s": 172, "text": "Suppose you encountered a situation where you need to push all rows in a DataFrame or require to use the previous row in a DataFrame. Maybe you want to calculate the difference in consecutive rows, Pandas shift() would be an ideal way to achieve these objectives." }, { "code": null, "e": 630, "s": 436, "text": "In this article, we’ll be going through some examples of manipulating data using Pandas shift() function. We will focus on practical problems and should help you get started with data analysis." }, { "code": null, "e": 836, "s": 630, "text": "Shifting values with periodsShifting time-series data with freqA practical example: calculating the difference in consecutive rowsA practical example: calculating the 7 days difference for time-series data" }, { "code": null, "e": 865, "s": 836, "text": "Shifting values with periods" }, { "code": null, "e": 901, "s": 865, "text": "Shifting time-series data with freq" }, { "code": null, "e": 969, "s": 901, "text": "A practical example: calculating the difference in consecutive rows" }, { "code": null, "e": 1045, "s": 969, "text": "A practical example: calculating the 7 days difference for time-series data" }, { "code": null, "e": 1092, "s": 1045, "text": "Please check out Notebook for the source code." }, { "code": null, "e": 1429, "s": 1092, "text": "Pandas shift() shift index by the desired number of periods. The simplest call should have an argument periods (It defaults to 1) and it represents the number of shifts for the desired axis. And by default, it is shifting values vertically along the axis 0 . NaN will be filled for missing values introduced as a result of the shifting." }, { "code": null, "e": 1483, "s": 1429, "text": "Let’s see how this works with the help of an example." }, { "code": null, "e": 1559, "s": 1483, "text": "df = pd.DataFrame({ \"A\": [1, 2, 3, 4, 5], \"B\": [10, 20, 30, 40, 50]})" }, { "code": null, "e": 1594, "s": 1559, "text": "To shift index by 1 row vertically" }, { "code": null, "e": 1651, "s": 1594, "text": "df.shift(periods=1)# You can do below insteaddf.shift(1)" }, { "code": null, "e": 1738, "s": 1651, "text": "To replace NaN , you can use the argument fill_value , for example, replace NaN with 0" }, { "code": null, "e": 1772, "s": 1738, "text": "df.shift(periods=1, fill_value=0)" }, { "code": null, "e": 1881, "s": 1772, "text": "In addition, you can pass a negative number to periods and it will shift values in the oppositive direction." }, { "code": null, "e": 1930, "s": 1881, "text": "To shift values horizontally, you can set axis=1" }, { "code": null, "e": 1958, "s": 1930, "text": "df.shift(periods=1, axis=1)" }, { "code": null, "e": 2141, "s": 1958, "text": "Pandas shift() function has an argument called freq which allows you to do the frequency-based shifting. The Pandas shift() function is beneficial when dealing with time-series data." }, { "code": null, "e": 2290, "s": 2141, "text": "In order to use the argument freq, you need to make sure the index of DataFrame is date or datetime, otherwise, it will raise a NotImplementedError." }, { "code": null, "e": 2344, "s": 2290, "text": "Let’s see how this works with the help of an example." }, { "code": null, "e": 2493, "s": 2344, "text": "df = pd.DataFrame({ \"A\": [1, 2, 3, 4, 5], \"B\": [10, 20, 30, 40, 50] }, index=pd.date_range(\"2020-01-01\", freq='D', periods=5))" }, { "code": null, "e": 2524, "s": 2493, "text": "To shift the index by 10 days." }, { "code": null, "e": 2591, "s": 2524, "text": "df.shift(freq='10D')# The equivalentdf.shift(periods=10, freq='D')" }, { "code": null, "e": 2687, "s": 2591, "text": "You will get the following result if run with periods only. Certainly, that isn’t what we want." }, { "code": null, "e": 2817, "s": 2687, "text": "Suppose you need to use the previous row value to calculate the sales change, Pandas shift() would be a way to achieve this task." }, { "code": null, "e": 2933, "s": 2817, "text": "df = pd.DataFrame({ \"date\": pd.date_range(\"2020-01-01\", freq='D', periods=5), \"sales\": [22, 30, 32, 25, 42]})" }, { "code": null, "e": 2984, "s": 2933, "text": "To calculate the sales change in consecutive rows." }, { "code": null, "e": 3032, "s": 2984, "text": "df['diff'] = df['sales'] - df.shift(1)['sales']" }, { "code": null, "e": 3144, "s": 3032, "text": "This function is beneficial when dealing with time-series data. Let’s take a look at another practical example." }, { "code": null, "e": 3225, "s": 3144, "text": "Now, suppose you have been asked to calculate the 7 days sales change as follows" }, { "code": null, "e": 3324, "s": 3225, "text": "value_1 = Day_8 - Day_1value_2 = Day_9 - Day_2value_3 = Day_10 - Day_3...value_n = Day_N - Day_N-7" }, { "code": null, "e": 3502, "s": 3324, "text": "Pandas shift() with the argument freq would be an ideal way to achieve this task. Let’s use read_csv() with the argument parse_dates and index_col to load data into a DataFrame." }, { "code": null, "e": 3592, "s": 3502, "text": "df = pd.read_csv( 'data/sales.csv', parse_dates=['date'], index_col=['date'],)" }, { "code": null, "e": 3750, "s": 3592, "text": "Notice that the record for “2020–01–08” is missing in the DataFrame. By running df.shift(freq='7D') , you should get a result with a record for “2020–01–08”." }, { "code": null, "e": 3794, "s": 3750, "text": "Then, to calculate the 7 days sales change:" }, { "code": null, "e": 3855, "s": 3794, "text": "the_7_days_diff = df['sales'] - df.shift(freq='7D')['sales']" }, { "code": null, "e": 3867, "s": 3855, "text": "Notice that" }, { "code": null, "e": 3916, "s": 3867, "text": "There is a record for “2020–01–08” in the result" }, { "code": null, "e": 3984, "s": 3916, "text": "The value of “2020–01–08” is NaN because df doesn’t have this value" }, { "code": null, "e": 4110, "s": 3984, "text": "Values for the date from “2020–01–01” to “2020–01–07” are NaN. This is because df.shift(freq='7D') doesn’t have these values." }, { "code": null, "e": 4174, "s": 4110, "text": "The last 6 records are NaN because df doesn’t have these values" }, { "code": null, "e": 4409, "s": 4174, "text": "Pandas shift() function can be very useful when you need to push all rows in a DataFrame or require to use the previous row in a DataFrame. The function is beneficial when dealing with time-series data, as shown in the above examples." }, { "code": null, "e": 4585, "s": 4409, "text": "I hope this article will help you to save time in analyzing data. I recommend you to check out the documentation for the shift() API and to know about other things you can do." }, { "code": null, "e": 4737, "s": 4585, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 4794, "s": 4737, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 4838, "s": 4794, "text": "How to do a Custom Sort on Pandas DataFrame" }, { "code": null, "e": 4878, "s": 4838, "text": "When to use Pandas transform() function" }, { "code": null, "e": 4917, "s": 4878, "text": "Pandas concat() tricks you should know" }, { "code": null, "e": 4970, "s": 4917, "text": "Difference between apply() and transform() in Pandas" }, { "code": null, "e": 5009, "s": 4970, "text": "All the Pandas merge() you should know" }, { "code": null, "e": 5051, "s": 5009, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 5092, "s": 5051, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 5162, "s": 5092, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" } ]
Predicting Inpatient Length of Stay at Hospitals Using Python + Big Data | by Vishal Tien | Towards Data Science
Patient length of stay is a critical indicator of the efficiency of hospital management. Hospitals have limited resources, requiring efficient use of beds and clinician time. With the recent onset of the COVID-19 pandemic, this notion has been exemplified. Now more than ever, we can see that it is in the best interest of patients, hospitals, and public health to limit hospital stays to no longer than necessary and to have an idea of how long a given inpatient may need to stay. The ability to predict how long a patient will stay, only with information available as soon as they enter the hospital and are diagnosed, can therefore have many positive effects for a hospital and its efficiency. A model that can predict patient length of stay could allow hospitals to better analyze the factors that influence length of stay the most. Such analysis could pave the path for reductions in the length of inpatient stay, which could, in turn, have the effect of decreased risk of infection and medication side effects, improvement in the quality of treatment, and increased hospital profit with more efficient bed management. Furthermore, predicting patient’s length of stay also greatly benefits the patients and patient’s families as they can have an idea of how long they can expect to stay upon being admitted. The goal of this project is to create a model that can predict length of stay for patients upon admission to a hospital, and the steps to accomplish such a task are detailed here. The entire code used throughout this analysis can be found here. To conduct this analysis, I used the publicly available “NY Hospital Inpatient Discharges in 2015” dataset, which can be found on the New York State Government health data website. This dataset contains 2.3+ million rows of patient data, including information such as patient demographics, diagnoses, treatments, services, costs, and charges. Patient data has been de-identified according to HIPAA regulations. To analyze a dataset of this size, I utilized various big data analytic tools within a Python interface such as Spark, AWS clusters, SQL query optimization, and dimensionality reduction techniques. However, the bulk of the code shown in this post uses Pandas and scikit learn. Let’s first take a look at all the features and associated datatypes in the dataset. Next, let’s take a look at how our numerical features are correlated with each other. We can achieve this through the use of a correlation heat map. From this initial look at a correlation map of our data, it is evident that a couple of features are strongly correlated with each other, and perhaps more importantly, with length of stay. Although the correlation matrix does not make sense to look at for all of our columns (such as the license numbers), we can see from it that APR Severity of Illness Code has a strong positive correlation with length of stay, along with total charges and total costs. CCS Diagnosis Code also seems to have a slight positive correlation with length of stay. We can see other positive correlations in the dataset between features such as CCS Diagnosis codes and APR DRG codes. This plot gives us an idea about which features might be especially important to look at to predict length of stay, in addition to letting us know if there is multicollinearity present in the data. Next, let’s explore and visualize underlying relationships in the data. For the following analysis, length of stay is kept as the primary variable along the y-axis of the plots I create since it is the predictor variable for this project. First, the univariate distribution of length of stay is visualized. As we can see, length of stay values range from 1 to 120+ days (120 has been aggregated to include all lengths of stay 120 days or longer). In addition, the distribution is very skewed, with most of the patients in the data having lengths of stay between ~1 to 5 days. This is an important aspect of the data to keep in mind. We’ll put a pin in this for now and revisit it later. Next, let’s take a look at how different age groups vary in their length of stay distributions. Does length of stay vary with age of the patient? From this plot, the trend of longer lengths of stay distributions on average as we go up in age groups is easily apparent. Which diagnoses have the longest average length of stay? On average, patients with diagnoses related to birth complications have the longest length of stay on average, followed by those with respiratory diseases. Let’s also look at how some features, which we might not expect to have much influence, vary with length of stay. Does length of stay vary with race? We can see that as one might suspects, a patient’s race does not result in largely different distributions of length of stay. However, it is interesting to note that Black/African Americans have the largest spread in length of stay values by ~2 days from the group with the next largest distribution (white). How does length of stay vary with patient payment types? From this plot, it is evident that different health insurance forms of payment tend to have different length of stay distributions. Specifically, we can see that Medicare patients, for example, tend to have some of the longest lengths of stay on average. However, health insurance programs are strongly correlated with other factors, such as income and age. Thus, it may be that Medicare patients tend to have longer lengths of stay because they also are in an older age bracket. Let’s dig deeper into this idea: What is the age distribution of patients with Medicare as their primary payment typology? This idea is supported by the plot above and gives us an idea of how different variables can interact to affect the length of stay. Let’s move on to some of the most important features present in the dataset: the severity of illness and the type of patient admission into the hospital. How much does length of stay vary with the severity of the illness? We can see a large amount of variance within the APR Severity of Illness feature, indicating it will most likely be an important feature to include in machine learning (ML) models. How does length of stay vary with type of admission? How do diagnosis descriptions vary for each illness severity type? Here, I perform text parsing analysis on the diagnosis descriptions column of the dataset, followed by the creation of wordclouds to visualize these results. Wordclouds were created using the diagnosis descriptions for each patient stratified by their illness severity category. From this analysis, we can see some similarities but also some large differences in the diagnosis descriptions for each illness severity type. In the brief discussion of health insurance programs above, I also mentioned patient income as potentially playing a role, and ultimately being a feature that might be correlated with length of stay. One example of how this might be the case is that for some low-income patients, the hospital provides better living conditions than their situation outside of the hospital. Thus, these patients are motivated to do everything in their ability to lengthen their stay. Unfortunately, our dataset does not include any information about patient income. However, it does include the 3 digit zipcode of the patient. As we prepare to begin the modeling section of this project, is important to consider the fact that zipcode is not a good feature for most ML models. Although its information is encoded by numbers, it is not a numerical feature, as its numbers do not mathematically mean anything. In turn, this makes zipcodes hard to understand and create patterns from for prediction by ML models. As a result, the next step in my analysis will be replacing this raw 3 digit zipcode data with a rough measure of patient income, while will prove a much more useful feature. To achieve this, I webscraped average income data by zipcode from this website, which contains data from 2006–2010. Below is a plot of the median income for each 3 digit zipcode present in the dataset, achieved by inner joining (through SQL in python) the webscraped data onto our dataframe. We can use this new income feature to visualize how other features vary with the new constructed feature. We are now ready to begin preparing for the modeling portion of this analysis. To begin this section, I first will drop all columns that will not be useful for predictive modeling. This includes zipcodes, diagnosis descriptions, operating certificate numbers, etc., in addition to features that would not be present at the time of patient admittance, such as total costs and total charges, thereby preventing data leakage. Next, I performed feature encoding of all categorical columns containing strings. Categories that had corresponding numerical codes, such as APR Severity of Illness Code vs. APR Severity of Illness Description, were used as opposed to their string counterparts in order to prevent the need for category binarization and thus potentially large increases in dimensionality. In addition, I will utilize string indexing for a particular subset of the features. For both Age Group and APR Risk of Mortality, string indexing is performed due to the fact that there is an inherent ordinality to the categories within these features. For example, age group ‘0 to 17’ is a younger age group than ’70 or Older’. As such, it makes sense to encode the youngest age group ‘0 to 17’ with a 1, and larger age groups with increasingly larger integers. Similarly, a 1 is given to the ‘Minor’ category in APR Risk of Mortality, whereas a 4 is given to ‘Extreme’. String indexing on particular features such as this can be extremely beneficial as it prevents increasing the dimensionality of the dataset and allows for models to learn the ordinality present in the feature categories. The code to manually accomplish this is shown below. However, it is important to be wary of using string indexing on features that do not have an inherent ordinality, such as ‘Health Service Area’. Thus, one-hot encoding of the remaining categorical features is performed. mort_string_index = {'Minor': 1, 'Moderate': 2, 'Major': 3, 'Extreme': 4}age_string_index = {'0 to 17': 1, '18 to 29': 2, '30 to 49': 3, '50 to 69': 4, '70 or Older': 5}df['Age Group'] = df['Age Group'].apply(lambda x: age_string_index[x])df['APR Risk of Mortality'] = df['APR Risk of Mortality'].apply(lambda x: mort_string_index[x]) Now, let’s take a look at our predictor feature, length of stay. Length of stay ranges from 1 to 120 and only takes on integer values. I decide to treat predicting length of stay as a multi-class classification problem (instead of regression). Multi-class classification yields one large advantage in comparison to regression that I utilize: the ability to manually define class bins to manually control prediction specificity. Instead of treating length of stay as having 120 different classes, we can group these values into bins that make more sense for predictions without a significant loss in specificity of predictions. Following the exploration of multiple options for these bins, which involved trading off usefulness of the model (if bins are too large, the predictions will no longer be useful) and model accuracy, I ultimately settled on the following bin format: 1–5 days, 6–10 days, 11–20 days, 21–30 days, 31–50 days, and 50–120+ days From this visualization, a large class imbalance is apparent. Upon revisiting the univariate distribution of the raw length of stay data that was plotted at the beginning of this analysis, the same trend is apparent. This imbalance in the data must be handled carefully, as it can lead to misleading accuracy scores. Class imbalance can lead to a model over-predicting the class that occurs the most often, as simply predicting this class for most of the data instances, regardless of their features, will lead to the highest overall accuracy score. Thus, a model aiming to optimize accuracy score may fall into this trap. For example, even if the model were to always predict an inpatient’s stay would be 1 to 5 days (the most common length of stay in this dataset), it would achieve an accuracy of ~1.6e6/2.3e6 = 69%. In comparison to the baseline accuracy of the model (the accuracy the model would achieve if it randomly guessed), which is 1/6 or ~17%, this is significantly better model performance at first look. Under-sampling the most occurring class and assigning penalties for over-predicting classes are two of the most common methods for dealing with class imbalance, both of which were explored on this dataset. Ultimately, I found that assigning penalties was the most effective method, resulting in higher model accuracies than the under sampling method, while equally preventing the associated risks with class imbalance as when under sampling was performed. In order to assign these penalties to classes, I made use of the ‘class weight’ parameter in scikit learn’s ML functions, and set this parameter to ‘balanced’. This effectively assigns a weight to each class inversely proportional to the frequency with which it appears. PCA: Prior to training any models, I perform PCA on the data after using the StandardScaler() function to normalize the train and test data sets. PCA is a powerful tool that allows one to reduce the dimensionality of a dataset, which can be extremely beneficial for large datasets such as the one we are dealing with here. In addition, it removes any multicollinearity in the data. Although PCA is not intended for use on datasets with a mix of numerical and categorical features (that have been one-hot encoded/string indexed), performance was found to not be harmed significantly with the use of PCA (more can be read here about when to use PCA vs. MFA). It is important always normalize the data before applying PCA because PCA projects the raw data onto directions which maximize variance by calculating relative distances between points within a feature. Thus, when features are on different scales, PCA can be thrown off. import numpy as npfrom sklearn.decomposition import PCAfrom sklearn.preprocessing import StandardScalerx_train = StandardScaler().fit_transform(X_train)x_test = StandardScaler().fit_transform(X_test)pca1 = PCA()pca1.fit(x_train)explained_variance_ratio = pca1.explained_variance_ratio_pc_vs_variance = np.cumsum(pca1.explained_variance_ratio_) Below, I plot the % explained variance against the number of components from PCA that are used. From this graph, we can decide how many components to use for the rest of the analysis in order to retain a certain percentage of explained variance in the data. Here, I choose to keep 29 components as this is the minimum number of components required to explain 95% of the variance in the data. Logistic Regression: Next, let’s train a one-vs-rest logistic regression classifier. Logistic regression classifiers are strong models for classification problems. Let’s train a model after applying PCA to the standardized data, as shown below. pca = PCA(n_components=29) #29 components, as found abovex_train = pca.fit_transform(x_train)x_test = pca.transform(x_test)from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoreimport numpy as nplog_reg = LogisticRegression(multi_class='ovr').fit(x_train, y_train)y_train_pred = log_reg.predict(x_train)y_pred = log_reg.predict(x_test)test_acc = accuracy_score(y_test, y_pred)train_acc = accuracy_score(y_train, y_train_pred)print('Test accuracy:', test_acc)print('Train accuracy:', train_acc) Train accuracy: 0.7315117403879348Test accuracy: 0.7318516452316673 We get very good results given the baseline accuracy and nature of this dataset. However, this model was trained on the data without balancing any class weights. It is good practice to create a confusion matrix after making predictions to allow for closer examination of model performance, as an accuracy score alone can be misleading. The confusion matrix showcases the dangers of ignoring class imbalance in a dataset. Although we get a very high accuracy score, the model is significantly over-predicting prediction label 5 as it is the label with the highest frequency. On the other hand, the model never predicted labels 30 and 50. Both these trends are evident in the darker colors within the heat map for the first column in contrast to the lightest colors in the 30 and 50 columns (also denoted by 0's). Now, let’s see if we can deal with this issue. Logistic Regression with balanced class weight parameter: from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoreimport numpy as nplog_reg = LogisticRegression(class_weight='balanced', multi_class='ovr').fit(x_train, y_train)y_train_pred = log_reg.predict(x_train)y_pred = log_reg.predict(x_test)test_acc = accuracy_score(y_test, y_pred)train_acc = accuracy_score(y_train, y_train_pred)print('Test accuracy:', test_acc)print('Train accuracy:', train_acc) Train accuracy: 0.5892498813701775Test accuracy: 0.5889674625391544 As we can see, defining the class weight parameter had huge improvements on the performance of our model, preventing the classifier from simply over-predicting the highest frequency classes. Although the overall accuracy drops, our model will now be a better predictor for any given instance during future “real-world” testing. Furthermore, depicted by the darker colors along the diagonal of the heat map, even when the model does predict the wrong label, it is usually off by one label to the right or left. Let’s print out some more classification metrics to get an even closer look at how our model is performing: from sklearn.metrics import classification_reportprint(classification_report(y_test, y_pred)) Let’s use the f1-score to compare the logistic regression classifier to the rest of the models we will create. F1-score is a measure of a model’s accuracy that is calculated by taking the harmonic mean of precision and recall, thus combining both precision and recall, into one metric. If you are unfamiliar with the concepts of precision and recall, refer to this article to learn more. In essence, f1-score provides a quantitative measure for assessing the tendency to over-predict certain class labels and the ability for a model to separate classes. Decision Tree: For our next model, let’s try training a decision tree classifier on our data. Decision trees tend to perform very well in multi-class classification problems and are intuitive to understand. However, before we create the model, let’s optimize the hyperparameters for the decision tree classifier first. To do this, we can run a randomized search across a range of hyperparameter value combinations defined by a dictionary. From this search, we can then return the optimal values that are found. This hyperparameter search is enabled through the scikit RandomizedSearchCV function. Here, I choose to optimize the max_depth and max_leaf_nodes parameters, as they are key parameters in preventing overfitting, a property that decision trees are especially prone to. 3-fold cross validation is utilized. from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import RandomizedSearchCVdtree = DecisionTreeClassifier(class_weight='balanced')search_vals = dict(max_depth=[35,50,75,100], max_leaf_nodes=[800,1000,1500,2000])dtree_search = RandomizedSearchCV(dtree, search_vals, cv=3)search = dtree_search.fit(X_train,y_train)search.best_params_ Output: {‘max_depth’: 50, ‘max_leaf_nodes’: 1000} I also plot a validation curve while utilizing 3-fold cross validation in order to visualize the effect of hyperparameter optimization and model complexity against model accuracy. The validation curve for the max_depth parameter is shown below. The validation curve highlights tendency for decision trees to overfit as the max_depth parameter becomes less stringent (allowing deeper trees). However, it is interesting to note that although there is a large gap between training and validation accuracy, validation accuracy does not go down between this max depth range. Using the hyperparameters found above, let’s train a decision tree classifier and use it to create predictions. Below is the code I used to train the model. Let’s set the ‘class_weight’ parameter to ‘balanced’ just as before. Note that I train the model on the raw training data, and not the PCA scaled + transformed data, as decision trees are scale-invariant. Thus, they do not require the training data to be scaled. In addition, lower accuracy was achieved when the decision tree was trained on the PCA transformed data. from sklearn.tree import DecisionTreeClassifierdtree=DecisionTreeClassifier(max_depth= 50, max_leaf_nodes=1000, class_weight='balanced')dtree.fit(X_train,y_train)from sklearn import metricstrain_predictions = dtree.predict(X_train)test_predictions = dtree.predict(X_test)print("Train Accuracy:",metrics.accuracy_score(y_train, train_predictions))print("Test Accuracy:",metrics.accuracy_score(y_test, test_predictions)) Train Accuracy: 0.6170775710955541Test Accuracy: 0.6134612839367724 Ultimately, we can see that accuracy has gone up with the decision tree classifier! F1 scores for each class label has also increased, indicating an increase in model performance. Let’s see if we can do better with a decision tree ensemble, otherwise known as a random forest model. Random Forest: We can improve upon the decision tree classifier by bagging the trees into an ensemble and utilizing the power of majority voting between all of the trees built. This is called a random forest model. Below is the code and model performance for this model. Note that model parameters were chosen by trial and error (observing f1 and accuracy scores simultaneously) as a grid search/randomized search was very computationally expensive. However, parameters could be further optimized using said techniques. from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(n_estimators=150, max_depth=15, class_weight='balanced')rf.fit(X_train,y_train)train_predictions = rf.predict(X_train)test_predictions = rf.predict(X_test)print("Train Accuracy:",metrics.accuracy_score(y_train, train_predictions))print("Test Accuracy:",metrics.accuracy_score(y_test, test_predictions)) Train Accuracy: 0.6729519125323106Test Accuracy: 0.6436519717021008 We have improved on the accuracy of the decision tree, as well as on the f1 scores for each class. Next, let’s take advantage of one of the functions in scikit to generate a plot of feature importances in the random forest model. Here, feature importance is calculated as the decrease in node impurity weighted by the probability of reaching that node in the tree. From this plot, we can see that the APR DRG Code (a classification system that classifies patients according to their reason of admission, severity of illness and risk of mortality) and the APR Severity of Illness Code are the two most important features in predicting a patient’s length of stay. Interestingly, the payment typology medicare subgroup has a relatively high importance in predicting length of stay in comparison to the other payment typology groups. Average income of the patient also played a significant role. Boosted Decision Trees: Lastly, let’s see what performance we can achieve with another type of ensemble method: boosting. Using the AdaBoostClassifier in scikit learn, we can create a boosted decision tree classifier. This model works by creating n short decision tree stumps, where each successive tree stump that is built aims to improve on the classification error of the one before it. The majority vote of these trees is then combined to produce final predictions. The code used to achieve this is shown below, where hyperparameters were optmized using equivalent methods to those used for the random forest model. from sklearn.ensemble import AdaBoostClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scoredtree = DecisionTreeClassifier(random_state = 1, class_weight = "balanced", max_depth = 15)boost = AdaBoostClassifier(dtree, n_estimators=75, random_state=0)boost.fit(X_train, y_train)train_predictions = boost.predict(X_train)test_predictions = boost.predict(X_test)print("Train Accuracy:", accuracy_score(y_train, train_predictions))print("Test Accuracy:", accuracy_score(y_test, test_predictions)) Train Accuracy: 0.9397049441494455Test Accuracy: 0.7065437824744865 Here, we can see boosted decision trees achieved the highest model accuracy, beating out both the logistic regression classifier and the random forest ensemble. However, most of the f1 scores for the minority classes (less frequently occurring), are slightly lower. Thus, changes in how severe a false positive or false negative may be on a patient to patient basis may warrant switching between the use of the random forest model or the boosted decision tree classifier as the optimal model. Spark Cluster Environment: Due to the size of this data, some modeling aspects such as hyperparameter optimization took a long time to run. Thus, I wanted to include a note on the benefits of Apache Spark. We can achieve significant code speedup if we take advantage of Apache Spark and AWS clusters by parallelizing many computationally intensive tasks. Check out the full code I have linked at the beginning of this blog post for scripts that can be used to accomplish this. This code includes how to set Spark up in a Python environment, connect an AWS cluster to the notebook, retrieve the dataset from an S3 bucket, and create models. One of the drawbacks I found of using Spark for this project was the lack of the class weight parameter in the Spark ML model functions. In the full code, I also show a method for manually assigning class weights. This code was adapted from a blog post that can be viewed here. Ultimately, through the steps highlighted in this blog post, I was able to predict a patient’s length of stay using data only available from the moment they enter the hospital and are diagnosed with an accuracy of ~70%. Such a model has the ability to profoundly improve hospital management and patient well-being. Future directions could look to a develop a second model that would allow for a sequence of model predictions to be made that would ultimately predict how much a given patient will cost to treat over the course of their stay. This could be accomplished through first predicting length of stay through models such as the one created here. Next, a second model could be created to predict “Total Costs” from length of stay. Before putting a model such as the one created here into use, important ethical considerations need to be taken into account as well, since features such as patient income and race were used to predict length of stay. More on this topic can be read about here. Takeaways: Benefits of classification vs. regression in a multi-class classification setting Importance of string indexing vs. one-hot encoding categorical variables Importance of dealing with class imbalance The effectiveness of the class_weights parameter, which removes the need to under sample the highest frequency class (under sampling has the drawback of reducing the amount of training data available to train on) General steps required to take a raw dataset and use it to gather insights and generate predictions APR DRG Codes and APR Severity of Illness Codes are the two most important features in predicting a patient’s length of stay. In addition, the payment typology medicare subgroup has a relatively high importance in predicting length of stay in comparison to the other payment typology groups. Average income also had a significant influence on length of stay. References: [1]. Baek, H., Cho, M., Kim, S., Hwang, H., Song, M., & Yoo, S. (2018). Analysis of length of hospital stay using electronic health records: A statistical and data mining approach. PloS one, 13(4), e0195901. https://doi.org/10.1371/journal.pone.0195901 [2]. Scikit-Learn. (n.d.). Retrieved from https://scikit-learn.org/stable/ The work in this article expanded upon my final project and leveraged concepts I learned in CIS 545: Big Data Analytics at the University of Pennsylvania
[ { "code": null, "e": 653, "s": 171, "text": "Patient length of stay is a critical indicator of the efficiency of hospital management. Hospitals have limited resources, requiring efficient use of beds and clinician time. With the recent onset of the COVID-19 pandemic, this notion has been exemplified. Now more than ever, we can see that it is in the best interest of patients, hospitals, and public health to limit hospital stays to no longer than necessary and to have an idea of how long a given inpatient may need to stay." }, { "code": null, "e": 1664, "s": 653, "text": "The ability to predict how long a patient will stay, only with information available as soon as they enter the hospital and are diagnosed, can therefore have many positive effects for a hospital and its efficiency. A model that can predict patient length of stay could allow hospitals to better analyze the factors that influence length of stay the most. Such analysis could pave the path for reductions in the length of inpatient stay, which could, in turn, have the effect of decreased risk of infection and medication side effects, improvement in the quality of treatment, and increased hospital profit with more efficient bed management. Furthermore, predicting patient’s length of stay also greatly benefits the patients and patient’s families as they can have an idea of how long they can expect to stay upon being admitted. The goal of this project is to create a model that can predict length of stay for patients upon admission to a hospital, and the steps to accomplish such a task are detailed here." }, { "code": null, "e": 1729, "s": 1664, "text": "The entire code used throughout this analysis can be found here." }, { "code": null, "e": 2502, "s": 1729, "text": "To conduct this analysis, I used the publicly available “NY Hospital Inpatient Discharges in 2015” dataset, which can be found on the New York State Government health data website. This dataset contains 2.3+ million rows of patient data, including information such as patient demographics, diagnoses, treatments, services, costs, and charges. Patient data has been de-identified according to HIPAA regulations. To analyze a dataset of this size, I utilized various big data analytic tools within a Python interface such as Spark, AWS clusters, SQL query optimization, and dimensionality reduction techniques. However, the bulk of the code shown in this post uses Pandas and scikit learn. Let’s first take a look at all the features and associated datatypes in the dataset." }, { "code": null, "e": 2651, "s": 2502, "text": "Next, let’s take a look at how our numerical features are correlated with each other. We can achieve this through the use of a correlation heat map." }, { "code": null, "e": 3512, "s": 2651, "text": "From this initial look at a correlation map of our data, it is evident that a couple of features are strongly correlated with each other, and perhaps more importantly, with length of stay. Although the correlation matrix does not make sense to look at for all of our columns (such as the license numbers), we can see from it that APR Severity of Illness Code has a strong positive correlation with length of stay, along with total charges and total costs. CCS Diagnosis Code also seems to have a slight positive correlation with length of stay. We can see other positive correlations in the dataset between features such as CCS Diagnosis codes and APR DRG codes. This plot gives us an idea about which features might be especially important to look at to predict length of stay, in addition to letting us know if there is multicollinearity present in the data." }, { "code": null, "e": 3819, "s": 3512, "text": "Next, let’s explore and visualize underlying relationships in the data. For the following analysis, length of stay is kept as the primary variable along the y-axis of the plots I create since it is the predictor variable for this project. First, the univariate distribution of length of stay is visualized." }, { "code": null, "e": 4295, "s": 3819, "text": "As we can see, length of stay values range from 1 to 120+ days (120 has been aggregated to include all lengths of stay 120 days or longer). In addition, the distribution is very skewed, with most of the patients in the data having lengths of stay between ~1 to 5 days. This is an important aspect of the data to keep in mind. We’ll put a pin in this for now and revisit it later. Next, let’s take a look at how different age groups vary in their length of stay distributions." }, { "code": null, "e": 4345, "s": 4295, "text": "Does length of stay vary with age of the patient?" }, { "code": null, "e": 4468, "s": 4345, "text": "From this plot, the trend of longer lengths of stay distributions on average as we go up in age groups is easily apparent." }, { "code": null, "e": 4525, "s": 4468, "text": "Which diagnoses have the longest average length of stay?" }, { "code": null, "e": 4795, "s": 4525, "text": "On average, patients with diagnoses related to birth complications have the longest length of stay on average, followed by those with respiratory diseases. Let’s also look at how some features, which we might not expect to have much influence, vary with length of stay." }, { "code": null, "e": 4831, "s": 4795, "text": "Does length of stay vary with race?" }, { "code": null, "e": 5140, "s": 4831, "text": "We can see that as one might suspects, a patient’s race does not result in largely different distributions of length of stay. However, it is interesting to note that Black/African Americans have the largest spread in length of stay values by ~2 days from the group with the next largest distribution (white)." }, { "code": null, "e": 5197, "s": 5140, "text": "How does length of stay vary with patient payment types?" }, { "code": null, "e": 5710, "s": 5197, "text": "From this plot, it is evident that different health insurance forms of payment tend to have different length of stay distributions. Specifically, we can see that Medicare patients, for example, tend to have some of the longest lengths of stay on average. However, health insurance programs are strongly correlated with other factors, such as income and age. Thus, it may be that Medicare patients tend to have longer lengths of stay because they also are in an older age bracket. Let’s dig deeper into this idea:" }, { "code": null, "e": 5800, "s": 5710, "text": "What is the age distribution of patients with Medicare as their primary payment typology?" }, { "code": null, "e": 5932, "s": 5800, "text": "This idea is supported by the plot above and gives us an idea of how different variables can interact to affect the length of stay." }, { "code": null, "e": 6086, "s": 5932, "text": "Let’s move on to some of the most important features present in the dataset: the severity of illness and the type of patient admission into the hospital." }, { "code": null, "e": 6154, "s": 6086, "text": "How much does length of stay vary with the severity of the illness?" }, { "code": null, "e": 6335, "s": 6154, "text": "We can see a large amount of variance within the APR Severity of Illness feature, indicating it will most likely be an important feature to include in machine learning (ML) models." }, { "code": null, "e": 6388, "s": 6335, "text": "How does length of stay vary with type of admission?" }, { "code": null, "e": 6455, "s": 6388, "text": "How do diagnosis descriptions vary for each illness severity type?" }, { "code": null, "e": 6734, "s": 6455, "text": "Here, I perform text parsing analysis on the diagnosis descriptions column of the dataset, followed by the creation of wordclouds to visualize these results. Wordclouds were created using the diagnosis descriptions for each patient stratified by their illness severity category." }, { "code": null, "e": 6877, "s": 6734, "text": "From this analysis, we can see some similarities but also some large differences in the diagnosis descriptions for each illness severity type." }, { "code": null, "e": 8044, "s": 6877, "text": "In the brief discussion of health insurance programs above, I also mentioned patient income as potentially playing a role, and ultimately being a feature that might be correlated with length of stay. One example of how this might be the case is that for some low-income patients, the hospital provides better living conditions than their situation outside of the hospital. Thus, these patients are motivated to do everything in their ability to lengthen their stay. Unfortunately, our dataset does not include any information about patient income. However, it does include the 3 digit zipcode of the patient. As we prepare to begin the modeling section of this project, is important to consider the fact that zipcode is not a good feature for most ML models. Although its information is encoded by numbers, it is not a numerical feature, as its numbers do not mathematically mean anything. In turn, this makes zipcodes hard to understand and create patterns from for prediction by ML models. As a result, the next step in my analysis will be replacing this raw 3 digit zipcode data with a rough measure of patient income, while will prove a much more useful feature." }, { "code": null, "e": 8336, "s": 8044, "text": "To achieve this, I webscraped average income data by zipcode from this website, which contains data from 2006–2010. Below is a plot of the median income for each 3 digit zipcode present in the dataset, achieved by inner joining (through SQL in python) the webscraped data onto our dataframe." }, { "code": null, "e": 8442, "s": 8336, "text": "We can use this new income feature to visualize how other features vary with the new constructed feature." }, { "code": null, "e": 8521, "s": 8442, "text": "We are now ready to begin preparing for the modeling portion of this analysis." }, { "code": null, "e": 8865, "s": 8521, "text": "To begin this section, I first will drop all columns that will not be useful for predictive modeling. This includes zipcodes, diagnosis descriptions, operating certificate numbers, etc., in addition to features that would not be present at the time of patient admittance, such as total costs and total charges, thereby preventing data leakage." }, { "code": null, "e": 9237, "s": 8865, "text": "Next, I performed feature encoding of all categorical columns containing strings. Categories that had corresponding numerical codes, such as APR Severity of Illness Code vs. APR Severity of Illness Description, were used as opposed to their string counterparts in order to prevent the need for category binarization and thus potentially large increases in dimensionality." }, { "code": null, "e": 10304, "s": 9237, "text": "In addition, I will utilize string indexing for a particular subset of the features. For both Age Group and APR Risk of Mortality, string indexing is performed due to the fact that there is an inherent ordinality to the categories within these features. For example, age group ‘0 to 17’ is a younger age group than ’70 or Older’. As such, it makes sense to encode the youngest age group ‘0 to 17’ with a 1, and larger age groups with increasingly larger integers. Similarly, a 1 is given to the ‘Minor’ category in APR Risk of Mortality, whereas a 4 is given to ‘Extreme’. String indexing on particular features such as this can be extremely beneficial as it prevents increasing the dimensionality of the dataset and allows for models to learn the ordinality present in the feature categories. The code to manually accomplish this is shown below. However, it is important to be wary of using string indexing on features that do not have an inherent ordinality, such as ‘Health Service Area’. Thus, one-hot encoding of the remaining categorical features is performed." }, { "code": null, "e": 10639, "s": 10304, "text": "mort_string_index = {'Minor': 1, 'Moderate': 2, 'Major': 3, 'Extreme': 4}age_string_index = {'0 to 17': 1, '18 to 29': 2, '30 to 49': 3, '50 to 69': 4, '70 or Older': 5}df['Age Group'] = df['Age Group'].apply(lambda x: age_string_index[x])df['APR Risk of Mortality'] = df['APR Risk of Mortality'].apply(lambda x: mort_string_index[x])" }, { "code": null, "e": 11515, "s": 10639, "text": "Now, let’s take a look at our predictor feature, length of stay. Length of stay ranges from 1 to 120 and only takes on integer values. I decide to treat predicting length of stay as a multi-class classification problem (instead of regression). Multi-class classification yields one large advantage in comparison to regression that I utilize: the ability to manually define class bins to manually control prediction specificity. Instead of treating length of stay as having 120 different classes, we can group these values into bins that make more sense for predictions without a significant loss in specificity of predictions. Following the exploration of multiple options for these bins, which involved trading off usefulness of the model (if bins are too large, the predictions will no longer be useful) and model accuracy, I ultimately settled on the following bin format:" }, { "code": null, "e": 11589, "s": 11515, "text": "1–5 days, 6–10 days, 11–20 days, 21–30 days, 31–50 days, and 50–120+ days" }, { "code": null, "e": 12608, "s": 11589, "text": "From this visualization, a large class imbalance is apparent. Upon revisiting the univariate distribution of the raw length of stay data that was plotted at the beginning of this analysis, the same trend is apparent. This imbalance in the data must be handled carefully, as it can lead to misleading accuracy scores. Class imbalance can lead to a model over-predicting the class that occurs the most often, as simply predicting this class for most of the data instances, regardless of their features, will lead to the highest overall accuracy score. Thus, a model aiming to optimize accuracy score may fall into this trap. For example, even if the model were to always predict an inpatient’s stay would be 1 to 5 days (the most common length of stay in this dataset), it would achieve an accuracy of ~1.6e6/2.3e6 = 69%. In comparison to the baseline accuracy of the model (the accuracy the model would achieve if it randomly guessed), which is 1/6 or ~17%, this is significantly better model performance at first look." }, { "code": null, "e": 13335, "s": 12608, "text": "Under-sampling the most occurring class and assigning penalties for over-predicting classes are two of the most common methods for dealing with class imbalance, both of which were explored on this dataset. Ultimately, I found that assigning penalties was the most effective method, resulting in higher model accuracies than the under sampling method, while equally preventing the associated risks with class imbalance as when under sampling was performed. In order to assign these penalties to classes, I made use of the ‘class weight’ parameter in scikit learn’s ML functions, and set this parameter to ‘balanced’. This effectively assigns a weight to each class inversely proportional to the frequency with which it appears." }, { "code": null, "e": 13340, "s": 13335, "text": "PCA:" }, { "code": null, "e": 14263, "s": 13340, "text": "Prior to training any models, I perform PCA on the data after using the StandardScaler() function to normalize the train and test data sets. PCA is a powerful tool that allows one to reduce the dimensionality of a dataset, which can be extremely beneficial for large datasets such as the one we are dealing with here. In addition, it removes any multicollinearity in the data. Although PCA is not intended for use on datasets with a mix of numerical and categorical features (that have been one-hot encoded/string indexed), performance was found to not be harmed significantly with the use of PCA (more can be read here about when to use PCA vs. MFA). It is important always normalize the data before applying PCA because PCA projects the raw data onto directions which maximize variance by calculating relative distances between points within a feature. Thus, when features are on different scales, PCA can be thrown off." }, { "code": null, "e": 14607, "s": 14263, "text": "import numpy as npfrom sklearn.decomposition import PCAfrom sklearn.preprocessing import StandardScalerx_train = StandardScaler().fit_transform(X_train)x_test = StandardScaler().fit_transform(X_test)pca1 = PCA()pca1.fit(x_train)explained_variance_ratio = pca1.explained_variance_ratio_pc_vs_variance = np.cumsum(pca1.explained_variance_ratio_)" }, { "code": null, "e": 14999, "s": 14607, "text": "Below, I plot the % explained variance against the number of components from PCA that are used. From this graph, we can decide how many components to use for the rest of the analysis in order to retain a certain percentage of explained variance in the data. Here, I choose to keep 29 components as this is the minimum number of components required to explain 95% of the variance in the data." }, { "code": null, "e": 15020, "s": 14999, "text": "Logistic Regression:" }, { "code": null, "e": 15244, "s": 15020, "text": "Next, let’s train a one-vs-rest logistic regression classifier. Logistic regression classifiers are strong models for classification problems. Let’s train a model after applying PCA to the standardized data, as shown below." }, { "code": null, "e": 15777, "s": 15244, "text": "pca = PCA(n_components=29) #29 components, as found abovex_train = pca.fit_transform(x_train)x_test = pca.transform(x_test)from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoreimport numpy as nplog_reg = LogisticRegression(multi_class='ovr').fit(x_train, y_train)y_train_pred = log_reg.predict(x_train)y_pred = log_reg.predict(x_test)test_acc = accuracy_score(y_test, y_pred)train_acc = accuracy_score(y_train, y_train_pred)print('Test accuracy:', test_acc)print('Train accuracy:', train_acc)" }, { "code": null, "e": 15845, "s": 15777, "text": "Train accuracy: 0.7315117403879348Test accuracy: 0.7318516452316673" }, { "code": null, "e": 16181, "s": 15845, "text": "We get very good results given the baseline accuracy and nature of this dataset. However, this model was trained on the data without balancing any class weights. It is good practice to create a confusion matrix after making predictions to allow for closer examination of model performance, as an accuracy score alone can be misleading." }, { "code": null, "e": 16704, "s": 16181, "text": "The confusion matrix showcases the dangers of ignoring class imbalance in a dataset. Although we get a very high accuracy score, the model is significantly over-predicting prediction label 5 as it is the label with the highest frequency. On the other hand, the model never predicted labels 30 and 50. Both these trends are evident in the darker colors within the heat map for the first column in contrast to the lightest colors in the 30 and 50 columns (also denoted by 0's). Now, let’s see if we can deal with this issue." }, { "code": null, "e": 16762, "s": 16704, "text": "Logistic Regression with balanced class weight parameter:" }, { "code": null, "e": 17197, "s": 16762, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scoreimport numpy as nplog_reg = LogisticRegression(class_weight='balanced', multi_class='ovr').fit(x_train, y_train)y_train_pred = log_reg.predict(x_train)y_pred = log_reg.predict(x_test)test_acc = accuracy_score(y_test, y_pred)train_acc = accuracy_score(y_train, y_train_pred)print('Test accuracy:', test_acc)print('Train accuracy:', train_acc)" }, { "code": null, "e": 17265, "s": 17197, "text": "Train accuracy: 0.5892498813701775Test accuracy: 0.5889674625391544" }, { "code": null, "e": 17775, "s": 17265, "text": "As we can see, defining the class weight parameter had huge improvements on the performance of our model, preventing the classifier from simply over-predicting the highest frequency classes. Although the overall accuracy drops, our model will now be a better predictor for any given instance during future “real-world” testing. Furthermore, depicted by the darker colors along the diagonal of the heat map, even when the model does predict the wrong label, it is usually off by one label to the right or left." }, { "code": null, "e": 17883, "s": 17775, "text": "Let’s print out some more classification metrics to get an even closer look at how our model is performing:" }, { "code": null, "e": 17977, "s": 17883, "text": "from sklearn.metrics import classification_reportprint(classification_report(y_test, y_pred))" }, { "code": null, "e": 18531, "s": 17977, "text": "Let’s use the f1-score to compare the logistic regression classifier to the rest of the models we will create. F1-score is a measure of a model’s accuracy that is calculated by taking the harmonic mean of precision and recall, thus combining both precision and recall, into one metric. If you are unfamiliar with the concepts of precision and recall, refer to this article to learn more. In essence, f1-score provides a quantitative measure for assessing the tendency to over-predict certain class labels and the ability for a model to separate classes." }, { "code": null, "e": 18546, "s": 18531, "text": "Decision Tree:" }, { "code": null, "e": 19347, "s": 18546, "text": "For our next model, let’s try training a decision tree classifier on our data. Decision trees tend to perform very well in multi-class classification problems and are intuitive to understand. However, before we create the model, let’s optimize the hyperparameters for the decision tree classifier first. To do this, we can run a randomized search across a range of hyperparameter value combinations defined by a dictionary. From this search, we can then return the optimal values that are found. This hyperparameter search is enabled through the scikit RandomizedSearchCV function. Here, I choose to optimize the max_depth and max_leaf_nodes parameters, as they are key parameters in preventing overfitting, a property that decision trees are especially prone to. 3-fold cross validation is utilized." }, { "code": null, "e": 19705, "s": 19347, "text": "from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import RandomizedSearchCVdtree = DecisionTreeClassifier(class_weight='balanced')search_vals = dict(max_depth=[35,50,75,100], max_leaf_nodes=[800,1000,1500,2000])dtree_search = RandomizedSearchCV(dtree, search_vals, cv=3)search = dtree_search.fit(X_train,y_train)search.best_params_" }, { "code": null, "e": 19755, "s": 19705, "text": "Output: {‘max_depth’: 50, ‘max_leaf_nodes’: 1000}" }, { "code": null, "e": 20000, "s": 19755, "text": "I also plot a validation curve while utilizing 3-fold cross validation in order to visualize the effect of hyperparameter optimization and model complexity against model accuracy. The validation curve for the max_depth parameter is shown below." }, { "code": null, "e": 20325, "s": 20000, "text": "The validation curve highlights tendency for decision trees to overfit as the max_depth parameter becomes less stringent (allowing deeper trees). However, it is interesting to note that although there is a large gap between training and validation accuracy, validation accuracy does not go down between this max depth range." }, { "code": null, "e": 20850, "s": 20325, "text": "Using the hyperparameters found above, let’s train a decision tree classifier and use it to create predictions. Below is the code I used to train the model. Let’s set the ‘class_weight’ parameter to ‘balanced’ just as before. Note that I train the model on the raw training data, and not the PCA scaled + transformed data, as decision trees are scale-invariant. Thus, they do not require the training data to be scaled. In addition, lower accuracy was achieved when the decision tree was trained on the PCA transformed data." }, { "code": null, "e": 21269, "s": 20850, "text": "from sklearn.tree import DecisionTreeClassifierdtree=DecisionTreeClassifier(max_depth= 50, max_leaf_nodes=1000, class_weight='balanced')dtree.fit(X_train,y_train)from sklearn import metricstrain_predictions = dtree.predict(X_train)test_predictions = dtree.predict(X_test)print(\"Train Accuracy:\",metrics.accuracy_score(y_train, train_predictions))print(\"Test Accuracy:\",metrics.accuracy_score(y_test, test_predictions))" }, { "code": null, "e": 21337, "s": 21269, "text": "Train Accuracy: 0.6170775710955541Test Accuracy: 0.6134612839367724" }, { "code": null, "e": 21620, "s": 21337, "text": "Ultimately, we can see that accuracy has gone up with the decision tree classifier! F1 scores for each class label has also increased, indicating an increase in model performance. Let’s see if we can do better with a decision tree ensemble, otherwise known as a random forest model." }, { "code": null, "e": 21635, "s": 21620, "text": "Random Forest:" }, { "code": null, "e": 22140, "s": 21635, "text": "We can improve upon the decision tree classifier by bagging the trees into an ensemble and utilizing the power of majority voting between all of the trees built. This is called a random forest model. Below is the code and model performance for this model. Note that model parameters were chosen by trial and error (observing f1 and accuracy scores simultaneously) as a grid search/randomized search was very computationally expensive. However, parameters could be further optimized using said techniques." }, { "code": null, "e": 22522, "s": 22140, "text": "from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(n_estimators=150, max_depth=15, class_weight='balanced')rf.fit(X_train,y_train)train_predictions = rf.predict(X_train)test_predictions = rf.predict(X_test)print(\"Train Accuracy:\",metrics.accuracy_score(y_train, train_predictions))print(\"Test Accuracy:\",metrics.accuracy_score(y_test, test_predictions))" }, { "code": null, "e": 22590, "s": 22522, "text": "Train Accuracy: 0.6729519125323106Test Accuracy: 0.6436519717021008" }, { "code": null, "e": 22955, "s": 22590, "text": "We have improved on the accuracy of the decision tree, as well as on the f1 scores for each class. Next, let’s take advantage of one of the functions in scikit to generate a plot of feature importances in the random forest model. Here, feature importance is calculated as the decrease in node impurity weighted by the probability of reaching that node in the tree." }, { "code": null, "e": 23482, "s": 22955, "text": "From this plot, we can see that the APR DRG Code (a classification system that classifies patients according to their reason of admission, severity of illness and risk of mortality) and the APR Severity of Illness Code are the two most important features in predicting a patient’s length of stay. Interestingly, the payment typology medicare subgroup has a relatively high importance in predicting length of stay in comparison to the other payment typology groups. Average income of the patient also played a significant role." }, { "code": null, "e": 23506, "s": 23482, "text": "Boosted Decision Trees:" }, { "code": null, "e": 24102, "s": 23506, "text": "Lastly, let’s see what performance we can achieve with another type of ensemble method: boosting. Using the AdaBoostClassifier in scikit learn, we can create a boosted decision tree classifier. This model works by creating n short decision tree stumps, where each successive tree stump that is built aims to improve on the classification error of the one before it. The majority vote of these trees is then combined to produce final predictions. The code used to achieve this is shown below, where hyperparameters were optmized using equivalent methods to those used for the random forest model." }, { "code": null, "e": 24638, "s": 24102, "text": "from sklearn.ensemble import AdaBoostClassifierfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.metrics import accuracy_scoredtree = DecisionTreeClassifier(random_state = 1, class_weight = \"balanced\", max_depth = 15)boost = AdaBoostClassifier(dtree, n_estimators=75, random_state=0)boost.fit(X_train, y_train)train_predictions = boost.predict(X_train)test_predictions = boost.predict(X_test)print(\"Train Accuracy:\", accuracy_score(y_train, train_predictions))print(\"Test Accuracy:\", accuracy_score(y_test, test_predictions))" }, { "code": null, "e": 24706, "s": 24638, "text": "Train Accuracy: 0.9397049441494455Test Accuracy: 0.7065437824744865" }, { "code": null, "e": 25199, "s": 24706, "text": "Here, we can see boosted decision trees achieved the highest model accuracy, beating out both the logistic regression classifier and the random forest ensemble. However, most of the f1 scores for the minority classes (less frequently occurring), are slightly lower. Thus, changes in how severe a false positive or false negative may be on a patient to patient basis may warrant switching between the use of the random forest model or the boosted decision tree classifier as the optimal model." }, { "code": null, "e": 25226, "s": 25199, "text": "Spark Cluster Environment:" }, { "code": null, "e": 26117, "s": 25226, "text": "Due to the size of this data, some modeling aspects such as hyperparameter optimization took a long time to run. Thus, I wanted to include a note on the benefits of Apache Spark. We can achieve significant code speedup if we take advantage of Apache Spark and AWS clusters by parallelizing many computationally intensive tasks. Check out the full code I have linked at the beginning of this blog post for scripts that can be used to accomplish this. This code includes how to set Spark up in a Python environment, connect an AWS cluster to the notebook, retrieve the dataset from an S3 bucket, and create models. One of the drawbacks I found of using Spark for this project was the lack of the class weight parameter in the Spark ML model functions. In the full code, I also show a method for manually assigning class weights. This code was adapted from a blog post that can be viewed here." }, { "code": null, "e": 26854, "s": 26117, "text": "Ultimately, through the steps highlighted in this blog post, I was able to predict a patient’s length of stay using data only available from the moment they enter the hospital and are diagnosed with an accuracy of ~70%. Such a model has the ability to profoundly improve hospital management and patient well-being. Future directions could look to a develop a second model that would allow for a sequence of model predictions to be made that would ultimately predict how much a given patient will cost to treat over the course of their stay. This could be accomplished through first predicting length of stay through models such as the one created here. Next, a second model could be created to predict “Total Costs” from length of stay." }, { "code": null, "e": 27115, "s": 26854, "text": "Before putting a model such as the one created here into use, important ethical considerations need to be taken into account as well, since features such as patient income and race were used to predict length of stay. More on this topic can be read about here." }, { "code": null, "e": 27126, "s": 27115, "text": "Takeaways:" }, { "code": null, "e": 27208, "s": 27126, "text": "Benefits of classification vs. regression in a multi-class classification setting" }, { "code": null, "e": 27281, "s": 27208, "text": "Importance of string indexing vs. one-hot encoding categorical variables" }, { "code": null, "e": 27324, "s": 27281, "text": "Importance of dealing with class imbalance" }, { "code": null, "e": 27537, "s": 27324, "text": "The effectiveness of the class_weights parameter, which removes the need to under sample the highest frequency class (under sampling has the drawback of reducing the amount of training data available to train on)" }, { "code": null, "e": 27637, "s": 27537, "text": "General steps required to take a raw dataset and use it to gather insights and generate predictions" }, { "code": null, "e": 27996, "s": 27637, "text": "APR DRG Codes and APR Severity of Illness Codes are the two most important features in predicting a patient’s length of stay. In addition, the payment typology medicare subgroup has a relatively high importance in predicting length of stay in comparison to the other payment typology groups. Average income also had a significant influence on length of stay." }, { "code": null, "e": 28008, "s": 27996, "text": "References:" }, { "code": null, "e": 28261, "s": 28008, "text": "[1]. Baek, H., Cho, M., Kim, S., Hwang, H., Song, M., & Yoo, S. (2018). Analysis of length of hospital stay using electronic health records: A statistical and data mining approach. PloS one, 13(4), e0195901. https://doi.org/10.1371/journal.pone.0195901" }, { "code": null, "e": 28336, "s": 28261, "text": "[2]. Scikit-Learn. (n.d.). Retrieved from https://scikit-learn.org/stable/" } ]
filepath.Join() Function in Golang With Examples
10 May, 2020 In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Join() function in Go language used to join any number of the specified path elements into a single path, adding a Separator if necessary. This function calls Clean on the result and all empty strings are ignored. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions. Syntax: func Join(elem ...string) string Here, ‘elem’ is the specified path elements. Return Value: It returns the joined single path. Example 1: // Golang program to illustrate the usage of// filepath.Join() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Join() function fmt.Println(filepath.Join("G", "F", "G")) fmt.Println(filepath.Join("G/F", "G")) fmt.Println(filepath.Join("gfg", "GFG")) fmt.Println(filepath.Join("Geeks", "for", "Geeks"))} Output: G/F/G G/F/G gfg/GFG Geeks/for/Geeks Example 2: // Golang program to illustrate the usage of// filepath.Join() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Join() function fmt.Println(filepath.Join("/", "/")) fmt.Println(filepath.Join("")) fmt.Println(filepath.Join("a/b", "/c")) fmt.Println(filepath.Join("5", "10")) fmt.Println(filepath.Join(".")) } Output: / a/b/c 5/10 . Golang-filepath Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to convert a string in lower case in Golang? How to Trim a String in Golang? How to compare times in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 504, "s": 28, "text": "In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Join() function in Go language used to join any number of the specified path elements into a single path, adding a Separator if necessary. This function calls Clean on the result and all empty strings are ignored. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions." }, { "code": null, "e": 512, "s": 504, "text": "Syntax:" }, { "code": null, "e": 546, "s": 512, "text": "func Join(elem ...string) string\n" }, { "code": null, "e": 591, "s": 546, "text": "Here, ‘elem’ is the specified path elements." }, { "code": null, "e": 640, "s": 591, "text": "Return Value: It returns the joined single path." }, { "code": null, "e": 651, "s": 640, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// filepath.Join() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Join() function fmt.Println(filepath.Join(\"G\", \"F\", \"G\")) fmt.Println(filepath.Join(\"G/F\", \"G\")) fmt.Println(filepath.Join(\"gfg\", \"GFG\")) fmt.Println(filepath.Join(\"Geeks\", \"for\", \"Geeks\"))}", "e": 1092, "s": 651, "text": null }, { "code": null, "e": 1100, "s": 1092, "text": "Output:" }, { "code": null, "e": 1137, "s": 1100, "text": "G/F/G\nG/F/G\ngfg/GFG\nGeeks/for/Geeks\n" }, { "code": null, "e": 1148, "s": 1137, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// filepath.Join() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Join() function fmt.Println(filepath.Join(\"/\", \"/\")) fmt.Println(filepath.Join(\"\")) fmt.Println(filepath.Join(\"a/b\", \"/c\")) fmt.Println(filepath.Join(\"5\", \"10\")) fmt.Println(filepath.Join(\".\")) }", "e": 1598, "s": 1148, "text": null }, { "code": null, "e": 1606, "s": 1598, "text": "Output:" }, { "code": null, "e": 1623, "s": 1606, "text": "/\n\na/b/c\n5/10\n.\n" }, { "code": null, "e": 1639, "s": 1623, "text": "Golang-filepath" }, { "code": null, "e": 1651, "s": 1639, "text": "Go Language" }, { "code": null, "e": 1749, "s": 1651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1762, "s": 1749, "text": "Arrays in Go" }, { "code": null, "e": 1774, "s": 1762, "text": "Golang Maps" }, { "code": null, "e": 1807, "s": 1774, "text": "How to Split a String in Golang?" }, { "code": null, "e": 1828, "s": 1807, "text": "Interfaces in Golang" }, { "code": null, "e": 1845, "s": 1828, "text": "Slices in Golang" }, { "code": null, "e": 1899, "s": 1845, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 1928, "s": 1899, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 1977, "s": 1928, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 2009, "s": 1977, "text": "How to Trim a String in Golang?" } ]
How to display animated GIF images in Android using Kotlin?
This example demonstrates how to display animated GIF images in Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project. Step 2 − Add the following dependency in build.gradle (module:app) implementation 'com.github.bumptech.glide:glide:4.9.0' Step 3 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:onClick="showGif" android:text="SHOW GIF" android:textAlignment="center" /> </RelativeLayout> Step 4 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.view.View import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" } fun showGif(view: View) { val imageView: ImageView = findViewById(R.id.imageView) Glide.with(this).load(R.drawable.giphy).into(imageView) } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1273, "s": 1187, "text": "This example demonstrates how to display animated GIF images in Android using Kotlin." }, { "code": null, "e": 1401, "s": 1273, "text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project." }, { "code": null, "e": 1468, "s": 1401, "text": "Step 2 − Add the following dependency in build.gradle (module:app)" }, { "code": null, "e": 1523, "s": 1468, "text": "implementation 'com.github.bumptech.glide:glide:4.9.0'" }, { "code": null, "e": 1588, "s": 1523, "text": "Step 3 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2285, "s": 1588, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:onClick=\"showGif\"\n android:text=\"SHOW GIF\"\n android:textAlignment=\"center\" />\n</RelativeLayout>" }, { "code": null, "e": 2340, "s": 2285, "text": "Step 4 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2878, "s": 2340, "text": "import android.os.Bundle\nimport android.view.View\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity\nimport com.bumptech.glide.Glide\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n fun showGif(view: View) {\n val imageView: ImageView = findViewById(R.id.imageView)\n Glide.with(this).load(R.drawable.giphy).into(imageView)\n }\n}" }, { "code": null, "e": 2933, "s": 2878, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3606, "s": 2933, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3956, "s": 3606, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
MSD( Most Significant Digit ) Radix Sort
31 Mar, 2022 In this article, two types of Radix Sort are discussed: LSD Radix Sort: It starts sorting from the end of strings (the Least significant digit). MSD Radix Sort: It starts sorting from the beginning of strings (the Most significant digit). In this article, the task is to discuss the MSD Radix Sort and compare it with LSD Radix Sort. Approach: The idea is to perform the following steps for each digit i where the value of i varies from the most significant digit to the least significant digit: Store elements in different buckets according to their ith digit. Recursively sort each bucket that has more than one element. The idea is to sort the fixed-length integers, MSD is more efficient than LSD because it may not have to examine every digit of each integer: LSD Radix Sort: MSD Radix Sort: MSD Radix sort MSD can be used to sort strings of variable length, unlike LSD. LSD has to be stable in order to work correctly, but MSD can either be made stable or unstable and MSD can work with random strings. MSD Radix sort variable length string Time Complexity:LSD Radix sort: Best and Worst-Case time complexity is O(N*M) where M = length of the longest string.MSD Radix sort: Best Case time complexity is O(N) and the Worst-Case time complexity is O(N*M) where M = the average length of strings. LSD Radix sort: Best and Worst-Case time complexity is O(N*M) where M = length of the longest string.MSD Radix sort: Best Case time complexity is O(N) and the Worst-Case time complexity is O(N*M) where M = the average length of strings. Auxiliary Space:LSD Radix sort: O(N + B)MSD Radix sort: O(N + MB), where M = length of the longest string and B = size of radix (B=10 possible numbers or B=256 characters or B=2 for Binary). LSD Radix sort: O(N + B) MSD Radix sort: O(N + MB), where M = length of the longest string and B = size of radix (B=10 possible numbers or B=256 characters or B=2 for Binary). MSD uses recursion, so it requires more space than LSD. This means that MSD is much slower than LSD when working with a few inputs. Implementation of MSD Radix Sort: Using linked list: This implementation is for integers using linked list. A fixed-length array for every node will take a very large amount of storage. Below is the implementation of MSD Radix Sort using a linked list: C++ C Java C# Javascript // C++ program for the implementation// of MSD Radix Sort using linked list#include <iostream>#include <vector> using namespace std; // Linked list node structurestruct node { vector<int> arr; struct node* nxt[10];}; // Function to create a new node of// the Linked Liststruct node* new_node(void){ struct node* tempNode = new node; for (int i = 0; i < 10; i++) { tempNode->nxt[i] = NULL; } // Return the created node return tempNode;} // Function to sort the given array// using MSD Radix Sort recursivelyvoid msd_sort(struct node* root, int exp, vector<int>& sorted_arr){ if (exp <= 0) { return; } int j; // Stores the numbers in different // buckets according their MSD for (int i = 0; i < root->arr.size(); i++) { // Get the MSD in j j = (root->arr[i] / exp) % 10; // If j-th index in the node // array is empty create and // link a new node in index if (root->nxt[j] == NULL) { root->nxt[j] = new_node(); } // Store the number in j-th node root->nxt[j]->arr.push_back( root->arr[i]); } // Sort again every child node that // has more than one number for (int i = 0; i < 10; i++) { // If root->next is NULL if (root->nxt[i] != NULL) { if (root->nxt[i]->arr.size() > 1) { // Sort recursively msd_sort(root->nxt[i], exp / 10, sorted_arr); } // If any node have only // one number then it means // the number is sorted else { sorted_arr.push_back( root->nxt[i]->arr[0]); } } }} // Function to calculate the MSD of the// maximum value in the arrayint get_max_exp(vector<int> arr){ // Stores the maximum element int mx = arr[0]; // Traverse the given array for (int i = 1; i < arr.size(); i++) { // Update the value of maximum if (arr[i] > mx) { mx = arr[i]; } } int exp = 1; while (mx > 10) { mx /= 10; exp *= 10; } // Return the resultant value return exp;} // Function to print an arrayvoid print(vector<int> arr){ for (int i = 0; i < arr.size(); i++) cout << arr[i] << " "; cout << endl;} // Driver Codeint main(){ // create the root node struct node* root = new_node(); // Stores the unsorted array // in the root node root->arr.insert(root->arr.end(), { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }); cout << "Unsorted array : "; // Print the unsorted array print(root->arr); // Find the optimal longest exponent int exp = get_max_exp(root->arr); // Stores the sorted numbers vector<int> sorted_arr; // Function Call msd_sort(root, exp, sorted_arr); cout << "Sorted array : "; // Print the sorted array print(sorted_arr); return 0;} // C program for the implementation// of MSD Radix Sort using linked list// Linked list node structure#include <stdio.h>#include <stdlib.h> // For using malloc#include <string.h> // For using memset // Output array filled lengthint sorted_array_length = 0; struct node { int arr[100]; int arr_length; struct node* nxt[10];}; // Function to create a new node of// the Linked Liststruct node* new_node(void){ struct node* tempNode = (struct node*)malloc(sizeof(struct node)); tempNode->arr_length = 0; for (int i = 0; i < 10; i++) { tempNode->nxt[i] = NULL; } // Return the created node return tempNode;} // Function to sort the given array// using MSD Radix Sort recursivelyvoid msd_sort(struct node* root, int exp, int* sorted_arr){ if (exp <= 0) { return; } int j; // Stores the numbers in different // buckets according their MSD for (int i = 0; i < root->arr_length; i++) { // Get the MSD in j j = (root->arr[i] / exp) % 10; // If j-th index in the node // array is empty create and // link a new node in index if (root->nxt[j] == NULL) { root->nxt[j] = new_node(); } // Store the number in j-th node root->nxt[j]->arr[root->nxt[j]->arr_length++] = root->arr[i]; } // Sort again every child node that // has more than one number for (int i = 0; i < 10; i++) { // If root->next is NULL if (root->nxt[i] != NULL) { if (root->nxt[i]->arr_length > 1) { // Sort recursively msd_sort(root->nxt[i], exp / 10, sorted_arr); } // If any node have only // one number then it means // the number is sorted else { sorted_arr[sorted_array_length++] = root->nxt[i]->arr[0]; } } }} // Function to calculate the MSD of the// maximum value in the arrayint get_max_exp(int* arr, int n){ // Stores the maximum element int mx = arr[0]; // Traverse the given array for (int i = 1; i < n; i++) { // Update the value of maximum if (arr[i] > mx) { mx = arr[i]; } } int exp = 1; while (mx > 10) { mx /= 10; exp *= 10; } // Return the resultant value return exp;} // Function to print an arrayvoid print(int* arr, int n){ for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver Codeint main(){ // Unsorted array int array[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Input array length int n = sizeof(array) / sizeof(array[0]); // create the root node struct node* root = new_node(); // Stores the unsorted array // in the root node and // set arr_length memcpy(root->arr, array, sizeof(array)); root->arr_length = n; printf("Unsorted array : "); // Print the unsorted array print(root->arr, n); // Find the optimal longest exponent int exp = get_max_exp(root->arr, root->arr_length); // Stores the sorted numbers int output[n]; int* sorted_arr = &output[0]; // Function Call msd_sort(root, exp, sorted_arr); printf("Sorted array : "); // Print the sorted array print(sorted_arr, n); return 0;} // Java implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()import java.util.*; class GFG{ // A utility function to print an arraystatic void print(int[] arr, int n){ for (int i = 0; i < n; i++) { System.out.print(arr[i]+ " "); } System.out.println();} // A utility function to get the digit// at index d in a integerstatic int digit_at(int x, int d){ return (int)(x / Math.pow(10, d - 1)) % 10;} // The main function to sort array using// MSD Radix Sort recursivelystatic int[] MSD_sort(int[] arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return arr; } int count[] = new int[10 + 2]; // temp is created to easily swap Strings in arr[] HashMap<Integer,Integer> temp = new HashMap<>(); // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); if(temp.containsKey(count+1)) temp.put(count++, arr[i]); else temp.put(count++, arr[i]); } // Copy all integers of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) if(temp.containsKey(i-lo)) arr[i] = temp.get(i - lo); // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) arr = MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); return arr;} // function find the largest integerstatic int getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortstatic int[] radixsort(int[] arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int)Math.floor(Math.log10(Math.abs(m))) + 1; // function call return MSD_sort(arr, 0, n - 1, d);} // Driver Codepublic static void main(String[] args){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.length; System.out.printf("Unsorted array : "); // Print the unsorted array print(arr, n); // Function Call arr = radixsort(arr, n); System.out.printf("Sorted array : "); // Print the sorted array print(arr, n); }} // This code is contributed by gauravrajput1 // C# implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()using System;using System.Collections.Generic; public class GFG { // A utility function to print an array static void print(int[] arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); } // A utility function to get the digit // at index d in a integer static int digit_at(int x, int d) { return (int) (x / Math.Pow(10, d - 1)) % 10; } // The main function to sort array using // MSD Radix Sort recursively static int[] MSD_sort(int[] arr, int lo, int hi, int d) { // recursion break condition if (hi <= lo) { return arr; } int []count = new int[10 + 2]; // temp is created to easily swap Strings in []arr Dictionary<int, int> temp = new Dictionary<int, int>(); // Store occurrences of most significant character // from each integer in []count for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change []count so that []count now contains actual // position of this digits in []temp for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); if (temp.ContainsKey(count + 1)) temp.Add(count++, arr[i]); else temp.Add(count++, arr[i]); } // Copy all integers of temp to []arr, so that []arr now // contains partially sorted integers for (int i = lo; i <= hi; i++) if (temp.ContainsKey(i - lo)) arr[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) arr = MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); return arr; } // function find the largest integer static int getMax(int []arr, int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // Main function to call MSD_sort static int[] radixsort(int[] arr, int n) { // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int) Math.Floor(Math.Log10(Math.Abs(m))) + 1; // function call return MSD_sort(arr, 0, n - 1, d); } // Driver Code public static void Main(String[] args) { // Input array int []arr = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.Length; Console.Write("Unsorted array : "); // Print the unsorted array print(arr, n); // Function Call arr = radixsort(arr, n); Console.Write("Sorted array : "); // Print the sorted array print(arr, n); }} // This code is contributed by Rajput-Ji <script>// javascript implementation of MSD Radix Sort// of MSD Radix Sort using counting sort() // A utility function to print an array function print(arr , n) { for (var i = 0; i < n; i++) { document.write(arr[i] + " "); } document.write(); } // A utility function to get the digit // at index d in a integer function digit_at(x , d) { return parseInt( x / Math.pow(10, d - 1)) % 10; } // The main function to sort array using // MSD Radix Sort recursively function MSD_sort(arr , lo , hi , d) { // recursion break condition if (hi <= lo) { return arr; } var count = Array(10 + 2).fill(0); // temp is created to easily swap Strings in arr var temp = new Map(); // Store occurrences of most significant character // from each integer in count for (var i = lo; i <= hi; i++) { var c = digit_at(arr[i], d); count++; } // Change count so that count now contains actual // position of this digits in temp for (var r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (i = lo; i <= hi; i++) { var c = digit_at(arr[i], d); if (temp.has(count + 1)) temp.set(count++, arr[i]); else temp.set(count++, arr[i]); } // Copy all integers of temp to arr, so that arr now // contains partially sorted integers for (i = lo; i <= hi; i++) if (temp.has(i - lo)) arr[i] = temp.get(i - lo); // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (r = 0; r < 10; r++) arr = MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); return arr; } // function find the largest integer function getMax(arr , n) { var mx = arr[0]; for (i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // Main function to call MSD_sort function radixsort(arr , n) { // Find the maximum number to know number of digits var m = getMax(arr, n); // get the length of the largest integer var d = parseInt( Math.floor(Math.log10(Math.abs(m)))) + 1; // function call return MSD_sort(arr, 0, n - 1, d); } // Driver Code // Input array var arr = [ 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 ]; // Size of the array var n = arr.length; document.write("Unsorted array : "); // Print the unsorted array print(arr, n); // Function Call arr = radixsort(arr, n); document.write("<br/>Sorted array : "); // Print the sorted array print(arr, n); // This code is contributed by Rajput-Ji</script> Unsorted array : 9330 9950 718 8977 6790 95 9807 741 8586 5710 Sorted array : 95 718 741 5710 6790 8586 8977 9330 9807 9950 Using Counting Sort() method: This implementation is for the strings based on the counting sort() method. As C style ASCII character is 1 byte. So, the 256 size array is used to count occurrences of characters, and it sorts the strings lexicographically. Below is the implementation of MSD Radix Sort using the counting sort() method: C++ C Java C# // C++ implementation of MSD Radix Sort#include <iostream>#include <unordered_map> using namespace std; // A utility function to print an arrayvoid print(string* str, int n){ for (int i = 0; i < n; i++) { cout << str[i] << " "; } cout << endl;} // A utility function to get the ASCII value// of the character at index d in a stringint char_at(string str, int d){ if (str.size() <= d) return -1; else return str.at(d);} // The main function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(string* str, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return; } int count[256 + 2] = { 0 }; // temp is created to easily swap strings in str[] // int temp[n] can also be used but, // it will take more space. unordered_map<int, string> temp; // Store occurrences of most significant character // from each string in count[] for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 256 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); temp[count++] = str[i]; } // Copy all strings of temp to str[], so that str[] now // contains partially sorted strings for (int i = lo; i <= hi; i++) str[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // strings set to sort them by their next character for (int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1);} int main(){ string str[] = { "midnight", "badge", "bag", "worker", "banner", "wander" }; int n = sizeof(str) / sizeof(str[0]); cout << "Unsorted array : "; // print the unsorted array print(str, n); // Function call MSD_sort(str, 0, n - 1, 0); cout << "Sorted array : "; // print the sorted array print(str, n); return 0;} // C program for the implementation// of MSD Radix Sort using counting sort()#include <stdio.h>#include <string.h> // A utility function to get the ASCII value// of the character at index d in a stringint char_at(char* str, int d){ if (sizeof(str) / sizeof(str[0]) <= d) return -1; else return str[d];} int n; // The main function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(char** str, int lo, int hi, int d){ // recursion break condition if (hi <= lo + 1) { return; } int count[256 + 2] = { 0 }; // temp is created to easily swap strings in str[] char temp[n][100]; // Store occurrences of most significant character // from each string in count[] for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 256 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); memcpy(temp[count++], str[i], strlen(str[i]) + 1); } // Copy all strings of temp to str[], so that str[] now // contains partially sorted strings for (int i = lo; i <= hi; i++) { str[i] = strdup(temp[i - lo]); } // Recursively MSD_sort() on each partially sorted // strings set to sort them by their next character for (int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1);} // Function to print an arrayvoid print(char** str, int n){ for (int i = 0; i < n; i++) { printf("%s ", str[i]); } printf("\n");} // Driver Codeint main(){ // Input String char* str[] = { (char*)"midnight", (char*)"badge", (char*)"bag", (char*)"worker", (char*)"banner", (char*)"wander" }; // Size of the string n = sizeof(str) / sizeof(str[0]); printf("Unsorted array : "); // Print the unsorted array print(str, n); // Function Call MSD_sort(str, 0, n - 1, 0); printf("Sorted array : "); // Print the sorted array print(str, n); return 0;} // Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Utility function to get the ASCII // value of the character at index d // in the string static int char_at(String str, int d) { if (str.length() <= d) return -1; else return (int)(str.charAt(d)); } // Function to sort the array using // MSD Radix Sort recursively static void MSD_sort(String str[], int lo, int hi, int d) { // Recursive break condition if (hi <= lo) { return; } // Stores the ASCII Values int count[] = new int[256 + 1]; // Temp is created to easily // swap strings in str[] HashMap<Integer, String> temp = new HashMap<>(); // Store the occurrences of the most // significant character from // each string in count[] for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change count[] so that count[] // now contains actual position // of this digits in temp[] for (int r = 0; r < 256; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); temp.put(count++, str[i]); } // Copy all strings of temp to str[], // so that str[] now contains // partially sorted strings for (int i = lo; i <= hi; i++) str[i] = temp.get(i - lo); // Recursively MSD_sort() on each // partially sorted strings set to // sort them by their next character for (int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1); } // Function to print an array static void print(String str[], int n) { for (int i = 0; i < n; i++) { System.out.print(str[i] + " "); } System.out.println(); } // Driver Code public static void main(String[] args) { // Input String String str[] = { "midnight", "badge", "bag", "worker", "banner", "wander" }; // Size of the string int n = str.length; System.out.print("Unsorted array : "); // Print the unsorted array print(str, n); // Function Call MSD_sort(str, 0, n - 1, 0); System.out.print("Sorted array : "); // Print the sorted array print(str, n); }} // This code is contributed by Kingash. // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Utility function to get the ASCII// value of the character at index d// in the stringstatic int char_at(String str, int d){ if (str.Length <= d) return -1; else return(int)(str[d]);} // Function to sort the array using// MSD Radix Sort recursivelystatic void MSD_sort(String []str, int lo, int hi, int d){ // Recursive break condition if (hi <= lo) { return; } // Stores the ASCII Values int []count = new int[256 + 1]; // Temp is created to easily // swap strings in []str Dictionary<int, String> temp = new Dictionary<int, String>(); // Store the occurrences of the most // significant character from // each string in []count for(int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change []count so that []count // now contains actual position // of this digits in []temp for(int r = 0; r < 256; r++) count[r + 1] += count[r]; // Build the temp for(int i = lo; i <= hi; i++) { int c = char_at(str[i], d); temp.Add(count++, str[i]); } // Copy all strings of temp to []str, // so that []str now contains // partially sorted strings for(int i = lo; i <= hi; i++) str[i] = temp[i - lo]; // Recursively MSD_sort() on each // partially sorted strings set to // sort them by their next character for(int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1);} // Function to print an arraystatic void print(String []str, int n){ for(int i = 0; i < n; i++) { Console.Write(str[i] + " "); } Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ // Input String String []str = { "midnight", "badge", "bag", "worker", "banner", "wander" }; // Size of the string int n = str.Length; Console.Write("Unsorted array : "); // Print the unsorted array print(str, n); // Function Call MSD_sort(str, 0, n - 1, 0); Console.Write("Sorted array : "); // Print the sorted array print(str, n);}} // This code is contributed by shikhasingrajput Unsorted array : midnight badge bag worker banner wander Sorted array : badge bag banner midnight wander worker C++ C Java C# // C++ implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()#include <iostream>#include <math.h>#include <unordered_map> using namespace std; // A utility function to print an arrayvoid print(int* arr, int n){ for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl;} // A utility function to get the digit// at index d in a integerint digit_at(int x, int d){ return (int)(x / pow(10, d - 1)) % 10;} // The main function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(int* arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return; } int count[10 + 2] = { 0 }; // temp is created to easily swap strings in arr[] unordered_map<int, int> temp; // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp[count++] = arr[i]; } // Copy all integers of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) arr[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1);} // function find the largest integerint getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortvoid radixsort(int* arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = floor(log10(abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d);} // Driver Codeint main(){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = sizeof(arr) / sizeof(arr[0]); printf("Unsorted array : "); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); printf("Sorted array : "); // Print the sorted array print(arr, n); return 0;} // C program for the implementation// of MSD Radix Sort using counting sort()#include <math.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // A utility function to print an arrayvoid print(int* arr, int n){ for (int i = 0; i < n; i++) { printf("%d, ", arr[i]); } printf("\n");} // A utility function to get the digit// at index d in a integerint digit_at(int x, int d){ return (int)(x / pow(10, d - 1)) % 10;} // array lengthint n; // function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(int* arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo || d < 1) { return; } int count[10 + 2] = { 0 }; // temp is created to easily swap strings in arr[] int temp[n]; // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp[count++] = arr[i]; } // Copy all integer of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) { arr[i] = temp[i - lo]; } // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1);} // function find the largest integerint getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortvoid radixsort(int* arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = floor(log10(abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d);} // Driver Codeint main(){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array n = sizeof(arr) / sizeof(arr[0]); printf("Unsorted array : "); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); printf("Sorted array : "); // Print the sorted array print(arr, n); return 0;} // Java implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()import java.util.*; class GFG{ // A utility function to print an arraystatic void print(int[] arr, int n){ for (int i = 0; i < n; i++) { System.out.print(arr[i]+ " "); } System.out.println();} // A utility function to get the digit// at index d in a integerstatic int digit_at(int x, int d){ return (int)(x / Math.pow(10, d - 1)) % 10;} // The main function to sort array using// MSD Radix Sort recursivelystatic void MSD_sort(int[] arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return; } int count[] = new int[10 + 2]; // temp is created to easily swap Strings in arr[] HashMap<Integer,Integer> temp = new HashMap<>(); // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp.put(count++, arr[i]); } // Copy all integers of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) arr[i] = temp.get(i - lo); // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1);} // function find the largest integerstatic int getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortstatic void radixsort(int[] arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int)Math.floor(Math.log10(Math.abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d);} // Driver Codepublic static void main(String[] args){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.length; System.out.printf("Unsorted array : "); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); System.out.printf("Sorted array : "); // Print the sorted array print(arr, n); }} // This code is contributed by Rajput-Ji // C# implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()using System;using System.Collections.Generic; public class GFG { // A utility function to print an array static void print(int[] arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); } // A utility function to get the digit // at index d in a integer static int digit_at(int x, int d) { return (int) (x / Math.Pow(10, d - 1)) % 10; } // The main function to sort array using // MSD Radix Sort recursively static void MSD_sort(int[] arr, int lo, int hi, int d) { // recursion break condition if (hi <= lo) { return; } int []count = new int[10 + 2]; // temp is created to easily swap Strings in []arr Dictionary<int, int> temp = new Dictionary<int, int>(); // Store occurrences of most significant character // from each integer in []count for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change []count so that []count now contains actual // position of this digits in []temp for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp.Add(count++, arr[i]); } // Copy all integers of temp to []arr, so that []arr now // contains partially sorted integers for (int i = lo; i <= hi; i++) arr[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); } // function find the largest integer static int getMax(int []arr, int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // Main function to call MSD_sort static void radixsort(int[] arr, int n) { // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int) Math.Floor(Math.Log10(Math.Abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d); } // Driver Code public static void Main(String[] args) { // Input array int []arr = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.Length; Console.Write("Unsorted array : "); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); Console.Write("Sorted array : "); // Print the sorted array print(arr, n); }} // This code is contributed by Rajput-Ji Unsorted array : 9330 9950 718 8977 6790 95 9807 741 8586 5710 Sorted array : 95 718 741 5710 6790 8586 8977 9330 9807 9950 Kingash shikhasingrajput scorchingeagle abhishek0719kadiyan GauravRajput1 Rajput-Ji simranarora5sos Algorithms Arrays Linked List Sorting Linked List Arrays Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Arrays in C/C++
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Mar, 2022" }, { "code": null, "e": 84, "s": 28, "text": "In this article, two types of Radix Sort are discussed:" }, { "code": null, "e": 173, "s": 84, "text": "LSD Radix Sort: It starts sorting from the end of strings (the Least significant digit)." }, { "code": null, "e": 267, "s": 173, "text": "MSD Radix Sort: It starts sorting from the beginning of strings (the Most significant digit)." }, { "code": null, "e": 362, "s": 267, "text": "In this article, the task is to discuss the MSD Radix Sort and compare it with LSD Radix Sort." }, { "code": null, "e": 524, "s": 362, "text": "Approach: The idea is to perform the following steps for each digit i where the value of i varies from the most significant digit to the least significant digit:" }, { "code": null, "e": 590, "s": 524, "text": "Store elements in different buckets according to their ith digit." }, { "code": null, "e": 651, "s": 590, "text": "Recursively sort each bucket that has more than one element." }, { "code": null, "e": 793, "s": 651, "text": "The idea is to sort the fixed-length integers, MSD is more efficient than LSD because it may not have to examine every digit of each integer:" }, { "code": null, "e": 809, "s": 793, "text": "LSD Radix Sort:" }, { "code": null, "e": 825, "s": 809, "text": "MSD Radix Sort:" }, { "code": null, "e": 840, "s": 825, "text": "MSD Radix sort" }, { "code": null, "e": 1037, "s": 840, "text": "MSD can be used to sort strings of variable length, unlike LSD. LSD has to be stable in order to work correctly, but MSD can either be made stable or unstable and MSD can work with random strings." }, { "code": null, "e": 1076, "s": 1037, "text": "MSD Radix sort variable length string " }, { "code": null, "e": 1329, "s": 1076, "text": "Time Complexity:LSD Radix sort: Best and Worst-Case time complexity is O(N*M) where M = length of the longest string.MSD Radix sort: Best Case time complexity is O(N) and the Worst-Case time complexity is O(N*M) where M = the average length of strings." }, { "code": null, "e": 1566, "s": 1329, "text": "LSD Radix sort: Best and Worst-Case time complexity is O(N*M) where M = length of the longest string.MSD Radix sort: Best Case time complexity is O(N) and the Worst-Case time complexity is O(N*M) where M = the average length of strings." }, { "code": null, "e": 1757, "s": 1566, "text": "Auxiliary Space:LSD Radix sort: O(N + B)MSD Radix sort: O(N + MB), where M = length of the longest string and B = size of radix (B=10 possible numbers or B=256 characters or B=2 for Binary)." }, { "code": null, "e": 1782, "s": 1757, "text": "LSD Radix sort: O(N + B)" }, { "code": null, "e": 1933, "s": 1782, "text": "MSD Radix sort: O(N + MB), where M = length of the longest string and B = size of radix (B=10 possible numbers or B=256 characters or B=2 for Binary)." }, { "code": null, "e": 2065, "s": 1933, "text": "MSD uses recursion, so it requires more space than LSD. This means that MSD is much slower than LSD when working with a few inputs." }, { "code": null, "e": 2099, "s": 2065, "text": "Implementation of MSD Radix Sort:" }, { "code": null, "e": 2251, "s": 2099, "text": "Using linked list: This implementation is for integers using linked list. A fixed-length array for every node will take a very large amount of storage." }, { "code": null, "e": 2318, "s": 2251, "text": "Below is the implementation of MSD Radix Sort using a linked list:" }, { "code": null, "e": 2322, "s": 2318, "text": "C++" }, { "code": null, "e": 2324, "s": 2322, "text": "C" }, { "code": null, "e": 2329, "s": 2324, "text": "Java" }, { "code": null, "e": 2332, "s": 2329, "text": "C#" }, { "code": null, "e": 2343, "s": 2332, "text": "Javascript" }, { "code": "// C++ program for the implementation// of MSD Radix Sort using linked list#include <iostream>#include <vector> using namespace std; // Linked list node structurestruct node { vector<int> arr; struct node* nxt[10];}; // Function to create a new node of// the Linked Liststruct node* new_node(void){ struct node* tempNode = new node; for (int i = 0; i < 10; i++) { tempNode->nxt[i] = NULL; } // Return the created node return tempNode;} // Function to sort the given array// using MSD Radix Sort recursivelyvoid msd_sort(struct node* root, int exp, vector<int>& sorted_arr){ if (exp <= 0) { return; } int j; // Stores the numbers in different // buckets according their MSD for (int i = 0; i < root->arr.size(); i++) { // Get the MSD in j j = (root->arr[i] / exp) % 10; // If j-th index in the node // array is empty create and // link a new node in index if (root->nxt[j] == NULL) { root->nxt[j] = new_node(); } // Store the number in j-th node root->nxt[j]->arr.push_back( root->arr[i]); } // Sort again every child node that // has more than one number for (int i = 0; i < 10; i++) { // If root->next is NULL if (root->nxt[i] != NULL) { if (root->nxt[i]->arr.size() > 1) { // Sort recursively msd_sort(root->nxt[i], exp / 10, sorted_arr); } // If any node have only // one number then it means // the number is sorted else { sorted_arr.push_back( root->nxt[i]->arr[0]); } } }} // Function to calculate the MSD of the// maximum value in the arrayint get_max_exp(vector<int> arr){ // Stores the maximum element int mx = arr[0]; // Traverse the given array for (int i = 1; i < arr.size(); i++) { // Update the value of maximum if (arr[i] > mx) { mx = arr[i]; } } int exp = 1; while (mx > 10) { mx /= 10; exp *= 10; } // Return the resultant value return exp;} // Function to print an arrayvoid print(vector<int> arr){ for (int i = 0; i < arr.size(); i++) cout << arr[i] << \" \"; cout << endl;} // Driver Codeint main(){ // create the root node struct node* root = new_node(); // Stores the unsorted array // in the root node root->arr.insert(root->arr.end(), { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }); cout << \"Unsorted array : \"; // Print the unsorted array print(root->arr); // Find the optimal longest exponent int exp = get_max_exp(root->arr); // Stores the sorted numbers vector<int> sorted_arr; // Function Call msd_sort(root, exp, sorted_arr); cout << \"Sorted array : \"; // Print the sorted array print(sorted_arr); return 0;}", "e": 5457, "s": 2343, "text": null }, { "code": "// C program for the implementation// of MSD Radix Sort using linked list// Linked list node structure#include <stdio.h>#include <stdlib.h> // For using malloc#include <string.h> // For using memset // Output array filled lengthint sorted_array_length = 0; struct node { int arr[100]; int arr_length; struct node* nxt[10];}; // Function to create a new node of// the Linked Liststruct node* new_node(void){ struct node* tempNode = (struct node*)malloc(sizeof(struct node)); tempNode->arr_length = 0; for (int i = 0; i < 10; i++) { tempNode->nxt[i] = NULL; } // Return the created node return tempNode;} // Function to sort the given array// using MSD Radix Sort recursivelyvoid msd_sort(struct node* root, int exp, int* sorted_arr){ if (exp <= 0) { return; } int j; // Stores the numbers in different // buckets according their MSD for (int i = 0; i < root->arr_length; i++) { // Get the MSD in j j = (root->arr[i] / exp) % 10; // If j-th index in the node // array is empty create and // link a new node in index if (root->nxt[j] == NULL) { root->nxt[j] = new_node(); } // Store the number in j-th node root->nxt[j]->arr[root->nxt[j]->arr_length++] = root->arr[i]; } // Sort again every child node that // has more than one number for (int i = 0; i < 10; i++) { // If root->next is NULL if (root->nxt[i] != NULL) { if (root->nxt[i]->arr_length > 1) { // Sort recursively msd_sort(root->nxt[i], exp / 10, sorted_arr); } // If any node have only // one number then it means // the number is sorted else { sorted_arr[sorted_array_length++] = root->nxt[i]->arr[0]; } } }} // Function to calculate the MSD of the// maximum value in the arrayint get_max_exp(int* arr, int n){ // Stores the maximum element int mx = arr[0]; // Traverse the given array for (int i = 1; i < n; i++) { // Update the value of maximum if (arr[i] > mx) { mx = arr[i]; } } int exp = 1; while (mx > 10) { mx /= 10; exp *= 10; } // Return the resultant value return exp;} // Function to print an arrayvoid print(int* arr, int n){ for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver Codeint main(){ // Unsorted array int array[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Input array length int n = sizeof(array) / sizeof(array[0]); // create the root node struct node* root = new_node(); // Stores the unsorted array // in the root node and // set arr_length memcpy(root->arr, array, sizeof(array)); root->arr_length = n; printf(\"Unsorted array : \"); // Print the unsorted array print(root->arr, n); // Find the optimal longest exponent int exp = get_max_exp(root->arr, root->arr_length); // Stores the sorted numbers int output[n]; int* sorted_arr = &output[0]; // Function Call msd_sort(root, exp, sorted_arr); printf(\"Sorted array : \"); // Print the sorted array print(sorted_arr, n); return 0;}", "e": 8837, "s": 5457, "text": null }, { "code": "// Java implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()import java.util.*; class GFG{ // A utility function to print an arraystatic void print(int[] arr, int n){ for (int i = 0; i < n; i++) { System.out.print(arr[i]+ \" \"); } System.out.println();} // A utility function to get the digit// at index d in a integerstatic int digit_at(int x, int d){ return (int)(x / Math.pow(10, d - 1)) % 10;} // The main function to sort array using// MSD Radix Sort recursivelystatic int[] MSD_sort(int[] arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return arr; } int count[] = new int[10 + 2]; // temp is created to easily swap Strings in arr[] HashMap<Integer,Integer> temp = new HashMap<>(); // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); if(temp.containsKey(count+1)) temp.put(count++, arr[i]); else temp.put(count++, arr[i]); } // Copy all integers of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) if(temp.containsKey(i-lo)) arr[i] = temp.get(i - lo); // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) arr = MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); return arr;} // function find the largest integerstatic int getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortstatic int[] radixsort(int[] arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int)Math.floor(Math.log10(Math.abs(m))) + 1; // function call return MSD_sort(arr, 0, n - 1, d);} // Driver Codepublic static void main(String[] args){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.length; System.out.printf(\"Unsorted array : \"); // Print the unsorted array print(arr, n); // Function Call arr = radixsort(arr, n); System.out.printf(\"Sorted array : \"); // Print the sorted array print(arr, n); }} // This code is contributed by gauravrajput1", "e": 11639, "s": 8837, "text": null }, { "code": "// C# implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()using System;using System.Collections.Generic; public class GFG { // A utility function to print an array static void print(int[] arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); } // A utility function to get the digit // at index d in a integer static int digit_at(int x, int d) { return (int) (x / Math.Pow(10, d - 1)) % 10; } // The main function to sort array using // MSD Radix Sort recursively static int[] MSD_sort(int[] arr, int lo, int hi, int d) { // recursion break condition if (hi <= lo) { return arr; } int []count = new int[10 + 2]; // temp is created to easily swap Strings in []arr Dictionary<int, int> temp = new Dictionary<int, int>(); // Store occurrences of most significant character // from each integer in []count for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change []count so that []count now contains actual // position of this digits in []temp for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); if (temp.ContainsKey(count + 1)) temp.Add(count++, arr[i]); else temp.Add(count++, arr[i]); } // Copy all integers of temp to []arr, so that []arr now // contains partially sorted integers for (int i = lo; i <= hi; i++) if (temp.ContainsKey(i - lo)) arr[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) arr = MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); return arr; } // function find the largest integer static int getMax(int []arr, int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // Main function to call MSD_sort static int[] radixsort(int[] arr, int n) { // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int) Math.Floor(Math.Log10(Math.Abs(m))) + 1; // function call return MSD_sort(arr, 0, n - 1, d); } // Driver Code public static void Main(String[] args) { // Input array int []arr = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.Length; Console.Write(\"Unsorted array : \"); // Print the unsorted array print(arr, n); // Function Call arr = radixsort(arr, n); Console.Write(\"Sorted array : \"); // Print the sorted array print(arr, n); }} // This code is contributed by Rajput-Ji", "e": 14455, "s": 11639, "text": null }, { "code": "<script>// javascript implementation of MSD Radix Sort// of MSD Radix Sort using counting sort() // A utility function to print an array function print(arr , n) { for (var i = 0; i < n; i++) { document.write(arr[i] + \" \"); } document.write(); } // A utility function to get the digit // at index d in a integer function digit_at(x , d) { return parseInt( x / Math.pow(10, d - 1)) % 10; } // The main function to sort array using // MSD Radix Sort recursively function MSD_sort(arr , lo , hi , d) { // recursion break condition if (hi <= lo) { return arr; } var count = Array(10 + 2).fill(0); // temp is created to easily swap Strings in arr var temp = new Map(); // Store occurrences of most significant character // from each integer in count for (var i = lo; i <= hi; i++) { var c = digit_at(arr[i], d); count++; } // Change count so that count now contains actual // position of this digits in temp for (var r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (i = lo; i <= hi; i++) { var c = digit_at(arr[i], d); if (temp.has(count + 1)) temp.set(count++, arr[i]); else temp.set(count++, arr[i]); } // Copy all integers of temp to arr, so that arr now // contains partially sorted integers for (i = lo; i <= hi; i++) if (temp.has(i - lo)) arr[i] = temp.get(i - lo); // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (r = 0; r < 10; r++) arr = MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); return arr; } // function find the largest integer function getMax(arr , n) { var mx = arr[0]; for (i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // Main function to call MSD_sort function radixsort(arr , n) { // Find the maximum number to know number of digits var m = getMax(arr, n); // get the length of the largest integer var d = parseInt( Math.floor(Math.log10(Math.abs(m)))) + 1; // function call return MSD_sort(arr, 0, n - 1, d); } // Driver Code // Input array var arr = [ 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 ]; // Size of the array var n = arr.length; document.write(\"Unsorted array : \"); // Print the unsorted array print(arr, n); // Function Call arr = radixsort(arr, n); document.write(\"<br/>Sorted array : \"); // Print the sorted array print(arr, n); // This code is contributed by Rajput-Ji</script>", "e": 17387, "s": 14455, "text": null }, { "code": null, "e": 17513, "s": 17387, "text": "Unsorted array : 9330 9950 718 8977 6790 95 9807 741 8586 5710 \nSorted array : 95 718 741 5710 6790 8586 8977 9330 9807 9950 " }, { "code": null, "e": 17768, "s": 17513, "text": "Using Counting Sort() method: This implementation is for the strings based on the counting sort() method. As C style ASCII character is 1 byte. So, the 256 size array is used to count occurrences of characters, and it sorts the strings lexicographically." }, { "code": null, "e": 17849, "s": 17768, "text": "Below is the implementation of MSD Radix Sort using the counting sort() method: " }, { "code": null, "e": 17853, "s": 17849, "text": "C++" }, { "code": null, "e": 17855, "s": 17853, "text": "C" }, { "code": null, "e": 17860, "s": 17855, "text": "Java" }, { "code": null, "e": 17863, "s": 17860, "text": "C#" }, { "code": "// C++ implementation of MSD Radix Sort#include <iostream>#include <unordered_map> using namespace std; // A utility function to print an arrayvoid print(string* str, int n){ for (int i = 0; i < n; i++) { cout << str[i] << \" \"; } cout << endl;} // A utility function to get the ASCII value// of the character at index d in a stringint char_at(string str, int d){ if (str.size() <= d) return -1; else return str.at(d);} // The main function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(string* str, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return; } int count[256 + 2] = { 0 }; // temp is created to easily swap strings in str[] // int temp[n] can also be used but, // it will take more space. unordered_map<int, string> temp; // Store occurrences of most significant character // from each string in count[] for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 256 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); temp[count++] = str[i]; } // Copy all strings of temp to str[], so that str[] now // contains partially sorted strings for (int i = lo; i <= hi; i++) str[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // strings set to sort them by their next character for (int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1);} int main(){ string str[] = { \"midnight\", \"badge\", \"bag\", \"worker\", \"banner\", \"wander\" }; int n = sizeof(str) / sizeof(str[0]); cout << \"Unsorted array : \"; // print the unsorted array print(str, n); // Function call MSD_sort(str, 0, n - 1, 0); cout << \"Sorted array : \"; // print the sorted array print(str, n); return 0;}", "e": 19958, "s": 17863, "text": null }, { "code": "// C program for the implementation// of MSD Radix Sort using counting sort()#include <stdio.h>#include <string.h> // A utility function to get the ASCII value// of the character at index d in a stringint char_at(char* str, int d){ if (sizeof(str) / sizeof(str[0]) <= d) return -1; else return str[d];} int n; // The main function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(char** str, int lo, int hi, int d){ // recursion break condition if (hi <= lo + 1) { return; } int count[256 + 2] = { 0 }; // temp is created to easily swap strings in str[] char temp[n][100]; // Store occurrences of most significant character // from each string in count[] for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 256 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); memcpy(temp[count++], str[i], strlen(str[i]) + 1); } // Copy all strings of temp to str[], so that str[] now // contains partially sorted strings for (int i = lo; i <= hi; i++) { str[i] = strdup(temp[i - lo]); } // Recursively MSD_sort() on each partially sorted // strings set to sort them by their next character for (int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1);} // Function to print an arrayvoid print(char** str, int n){ for (int i = 0; i < n; i++) { printf(\"%s \", str[i]); } printf(\"\\n\");} // Driver Codeint main(){ // Input String char* str[] = { (char*)\"midnight\", (char*)\"badge\", (char*)\"bag\", (char*)\"worker\", (char*)\"banner\", (char*)\"wander\" }; // Size of the string n = sizeof(str) / sizeof(str[0]); printf(\"Unsorted array : \"); // Print the unsorted array print(str, n); // Function Call MSD_sort(str, 0, n - 1, 0); printf(\"Sorted array : \"); // Print the sorted array print(str, n); return 0;}", "e": 22167, "s": 19958, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Utility function to get the ASCII // value of the character at index d // in the string static int char_at(String str, int d) { if (str.length() <= d) return -1; else return (int)(str.charAt(d)); } // Function to sort the array using // MSD Radix Sort recursively static void MSD_sort(String str[], int lo, int hi, int d) { // Recursive break condition if (hi <= lo) { return; } // Stores the ASCII Values int count[] = new int[256 + 1]; // Temp is created to easily // swap strings in str[] HashMap<Integer, String> temp = new HashMap<>(); // Store the occurrences of the most // significant character from // each string in count[] for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change count[] so that count[] // now contains actual position // of this digits in temp[] for (int r = 0; r < 256; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = char_at(str[i], d); temp.put(count++, str[i]); } // Copy all strings of temp to str[], // so that str[] now contains // partially sorted strings for (int i = lo; i <= hi; i++) str[i] = temp.get(i - lo); // Recursively MSD_sort() on each // partially sorted strings set to // sort them by their next character for (int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1); } // Function to print an array static void print(String str[], int n) { for (int i = 0; i < n; i++) { System.out.print(str[i] + \" \"); } System.out.println(); } // Driver Code public static void main(String[] args) { // Input String String str[] = { \"midnight\", \"badge\", \"bag\", \"worker\", \"banner\", \"wander\" }; // Size of the string int n = str.length; System.out.print(\"Unsorted array : \"); // Print the unsorted array print(str, n); // Function Call MSD_sort(str, 0, n - 1, 0); System.out.print(\"Sorted array : \"); // Print the sorted array print(str, n); }} // This code is contributed by Kingash.", "e": 24779, "s": 22167, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Utility function to get the ASCII// value of the character at index d// in the stringstatic int char_at(String str, int d){ if (str.Length <= d) return -1; else return(int)(str[d]);} // Function to sort the array using// MSD Radix Sort recursivelystatic void MSD_sort(String []str, int lo, int hi, int d){ // Recursive break condition if (hi <= lo) { return; } // Stores the ASCII Values int []count = new int[256 + 1]; // Temp is created to easily // swap strings in []str Dictionary<int, String> temp = new Dictionary<int, String>(); // Store the occurrences of the most // significant character from // each string in []count for(int i = lo; i <= hi; i++) { int c = char_at(str[i], d); count++; } // Change []count so that []count // now contains actual position // of this digits in []temp for(int r = 0; r < 256; r++) count[r + 1] += count[r]; // Build the temp for(int i = lo; i <= hi; i++) { int c = char_at(str[i], d); temp.Add(count++, str[i]); } // Copy all strings of temp to []str, // so that []str now contains // partially sorted strings for(int i = lo; i <= hi; i++) str[i] = temp[i - lo]; // Recursively MSD_sort() on each // partially sorted strings set to // sort them by their next character for(int r = 0; r < 256; r++) MSD_sort(str, lo + count[r], lo + count[r + 1] - 1, d + 1);} // Function to print an arraystatic void print(String []str, int n){ for(int i = 0; i < n; i++) { Console.Write(str[i] + \" \"); } Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ // Input String String []str = { \"midnight\", \"badge\", \"bag\", \"worker\", \"banner\", \"wander\" }; // Size of the string int n = str.Length; Console.Write(\"Unsorted array : \"); // Print the unsorted array print(str, n); // Function Call MSD_sort(str, 0, n - 1, 0); Console.Write(\"Sorted array : \"); // Print the sorted array print(str, n);}} // This code is contributed by shikhasingrajput", "e": 27156, "s": 24779, "text": null }, { "code": null, "e": 27270, "s": 27156, "text": "Unsorted array : midnight badge bag worker banner wander \nSorted array : badge bag banner midnight wander worker " }, { "code": null, "e": 27274, "s": 27270, "text": "C++" }, { "code": null, "e": 27276, "s": 27274, "text": "C" }, { "code": null, "e": 27281, "s": 27276, "text": "Java" }, { "code": null, "e": 27284, "s": 27281, "text": "C#" }, { "code": "// C++ implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()#include <iostream>#include <math.h>#include <unordered_map> using namespace std; // A utility function to print an arrayvoid print(int* arr, int n){ for (int i = 0; i < n; i++) { cout << arr[i] << \" \"; } cout << endl;} // A utility function to get the digit// at index d in a integerint digit_at(int x, int d){ return (int)(x / pow(10, d - 1)) % 10;} // The main function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(int* arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return; } int count[10 + 2] = { 0 }; // temp is created to easily swap strings in arr[] unordered_map<int, int> temp; // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp[count++] = arr[i]; } // Copy all integers of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) arr[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1);} // function find the largest integerint getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortvoid radixsort(int* arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = floor(log10(abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d);} // Driver Codeint main(){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = sizeof(arr) / sizeof(arr[0]); printf(\"Unsorted array : \"); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); printf(\"Sorted array : \"); // Print the sorted array print(arr, n); return 0;}", "e": 29801, "s": 27284, "text": null }, { "code": "// C program for the implementation// of MSD Radix Sort using counting sort()#include <math.h>#include <stdio.h>#include <stdlib.h>#include <string.h> // A utility function to print an arrayvoid print(int* arr, int n){ for (int i = 0; i < n; i++) { printf(\"%d, \", arr[i]); } printf(\"\\n\");} // A utility function to get the digit// at index d in a integerint digit_at(int x, int d){ return (int)(x / pow(10, d - 1)) % 10;} // array lengthint n; // function to sort array using// MSD Radix Sort recursivelyvoid MSD_sort(int* arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo || d < 1) { return; } int count[10 + 2] = { 0 }; // temp is created to easily swap strings in arr[] int temp[n]; // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp[count++] = arr[i]; } // Copy all integer of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) { arr[i] = temp[i - lo]; } // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1);} // function find the largest integerint getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortvoid radixsort(int* arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = floor(log10(abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d);} // Driver Codeint main(){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array n = sizeof(arr) / sizeof(arr[0]); printf(\"Unsorted array : \"); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); printf(\"Sorted array : \"); // Print the sorted array print(arr, n); return 0;}", "e": 32314, "s": 29801, "text": null }, { "code": "// Java implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()import java.util.*; class GFG{ // A utility function to print an arraystatic void print(int[] arr, int n){ for (int i = 0; i < n; i++) { System.out.print(arr[i]+ \" \"); } System.out.println();} // A utility function to get the digit// at index d in a integerstatic int digit_at(int x, int d){ return (int)(x / Math.pow(10, d - 1)) % 10;} // The main function to sort array using// MSD Radix Sort recursivelystatic void MSD_sort(int[] arr, int lo, int hi, int d){ // recursion break condition if (hi <= lo) { return; } int count[] = new int[10 + 2]; // temp is created to easily swap Strings in arr[] HashMap<Integer,Integer> temp = new HashMap<>(); // Store occurrences of most significant character // from each integer in count[] for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change count[] so that count[] now contains actual // position of this digits in temp[] for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp.put(count++, arr[i]); } // Copy all integers of temp to arr[], so that arr[] now // contains partially sorted integers for (int i = lo; i <= hi; i++) arr[i] = temp.get(i - lo); // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1);} // function find the largest integerstatic int getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // Main function to call MSD_sortstatic void radixsort(int[] arr, int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int)Math.floor(Math.log10(Math.abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d);} // Driver Codepublic static void main(String[] args){ // Input array int arr[] = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.length; System.out.printf(\"Unsorted array : \"); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); System.out.printf(\"Sorted array : \"); // Print the sorted array print(arr, n); }} // This code is contributed by Rajput-Ji", "e": 34951, "s": 32314, "text": null }, { "code": "// C# implementation of MSD Radix Sort// of MSD Radix Sort using counting sort()using System;using System.Collections.Generic; public class GFG { // A utility function to print an array static void print(int[] arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); } // A utility function to get the digit // at index d in a integer static int digit_at(int x, int d) { return (int) (x / Math.Pow(10, d - 1)) % 10; } // The main function to sort array using // MSD Radix Sort recursively static void MSD_sort(int[] arr, int lo, int hi, int d) { // recursion break condition if (hi <= lo) { return; } int []count = new int[10 + 2]; // temp is created to easily swap Strings in []arr Dictionary<int, int> temp = new Dictionary<int, int>(); // Store occurrences of most significant character // from each integer in []count for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); count++; } // Change []count so that []count now contains actual // position of this digits in []temp for (int r = 0; r < 10 + 1; r++) count[r + 1] += count[r]; // Build the temp for (int i = lo; i <= hi; i++) { int c = digit_at(arr[i], d); temp.Add(count++, arr[i]); } // Copy all integers of temp to []arr, so that []arr now // contains partially sorted integers for (int i = lo; i <= hi; i++) arr[i] = temp[i - lo]; // Recursively MSD_sort() on each partially sorted // integers set to sort them by their next digit for (int r = 0; r < 10; r++) MSD_sort(arr, lo + count[r], lo + count[r + 1] - 1, d - 1); } // function find the largest integer static int getMax(int []arr, int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // Main function to call MSD_sort static void radixsort(int[] arr, int n) { // Find the maximum number to know number of digits int m = getMax(arr, n); // get the length of the largest integer int d = (int) Math.Floor(Math.Log10(Math.Abs(m))) + 1; // function call MSD_sort(arr, 0, n - 1, d); } // Driver Code public static void Main(String[] args) { // Input array int []arr = { 9330, 9950, 718, 8977, 6790, 95, 9807, 741, 8586, 5710 }; // Size of the array int n = arr.Length; Console.Write(\"Unsorted array : \"); // Print the unsorted array print(arr, n); // Function Call radixsort(arr, n); Console.Write(\"Sorted array : \"); // Print the sorted array print(arr, n); }} // This code is contributed by Rajput-Ji", "e": 37604, "s": 34951, "text": null }, { "code": null, "e": 37730, "s": 37604, "text": "Unsorted array : 9330 9950 718 8977 6790 95 9807 741 8586 5710 \nSorted array : 95 718 741 5710 6790 8586 8977 9330 9807 9950 " }, { "code": null, "e": 37740, "s": 37732, "text": "Kingash" }, { "code": null, "e": 37757, "s": 37740, "text": "shikhasingrajput" }, { "code": null, "e": 37772, "s": 37757, "text": "scorchingeagle" }, { "code": null, "e": 37792, "s": 37772, "text": "abhishek0719kadiyan" }, { "code": null, "e": 37806, "s": 37792, "text": "GauravRajput1" }, { "code": null, "e": 37816, "s": 37806, "text": "Rajput-Ji" }, { "code": null, "e": 37832, "s": 37816, "text": "simranarora5sos" }, { "code": null, "e": 37843, "s": 37832, "text": "Algorithms" }, { "code": null, "e": 37850, "s": 37843, "text": "Arrays" }, { "code": null, "e": 37862, "s": 37850, "text": "Linked List" }, { "code": null, "e": 37870, "s": 37862, "text": "Sorting" }, { "code": null, "e": 37882, "s": 37870, "text": "Linked List" }, { "code": null, "e": 37889, "s": 37882, "text": "Arrays" }, { "code": null, "e": 37897, "s": 37889, "text": "Sorting" }, { "code": null, "e": 37908, "s": 37897, "text": "Algorithms" }, { "code": null, "e": 38006, "s": 37908, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38044, "s": 38006, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 38112, "s": 38044, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 38139, "s": 38112, "text": "How to Start Learning DSA?" }, { "code": null, "e": 38182, "s": 38139, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 38249, "s": 38182, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 38264, "s": 38249, "text": "Arrays in Java" }, { "code": null, "e": 38310, "s": 38264, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38378, "s": 38310, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38410, "s": 38378, "text": "Largest Sum Contiguous Subarray" } ]